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::VAEND , MVT::Other, Expand);
331 if (Subtarget->is64Bit()) {
332 setOperationAction(ISD::VAARG , MVT::Other, Custom);
333 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
335 setOperationAction(ISD::VAARG , MVT::Other, Expand);
336 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
339 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
340 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
341 if (Subtarget->is64Bit())
342 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
343 if (Subtarget->isTargetCygMing())
344 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
346 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
348 if (X86ScalarSSEf64) {
349 // f32 and f64 use SSE.
350 // Set up the FP register classes.
351 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
352 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
354 // Use ANDPD to simulate FABS.
355 setOperationAction(ISD::FABS , MVT::f64, Custom);
356 setOperationAction(ISD::FABS , MVT::f32, Custom);
358 // Use XORP to simulate FNEG.
359 setOperationAction(ISD::FNEG , MVT::f64, Custom);
360 setOperationAction(ISD::FNEG , MVT::f32, Custom);
362 // Use ANDPD and ORPD to simulate FCOPYSIGN.
363 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
364 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
366 // We don't support sin/cos/fmod
367 setOperationAction(ISD::FSIN , MVT::f64, Expand);
368 setOperationAction(ISD::FCOS , MVT::f64, Expand);
369 setOperationAction(ISD::FSIN , MVT::f32, Expand);
370 setOperationAction(ISD::FCOS , MVT::f32, Expand);
372 // Expand FP immediates into loads from the stack, except for the special
374 addLegalFPImmediate(APFloat(+0.0)); // xorpd
375 addLegalFPImmediate(APFloat(+0.0f)); // xorps
377 // Floating truncations from f80 and extensions to f80 go through memory.
378 // If optimizing, we lie about this though and handle it in
379 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
381 setConvertAction(MVT::f32, MVT::f80, Expand);
382 setConvertAction(MVT::f64, MVT::f80, Expand);
383 setConvertAction(MVT::f80, MVT::f32, Expand);
384 setConvertAction(MVT::f80, MVT::f64, Expand);
386 } else if (X86ScalarSSEf32) {
387 // Use SSE for f32, x87 for f64.
388 // Set up the FP register classes.
389 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
390 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
392 // Use ANDPS to simulate FABS.
393 setOperationAction(ISD::FABS , MVT::f32, Custom);
395 // Use XORP to simulate FNEG.
396 setOperationAction(ISD::FNEG , MVT::f32, Custom);
398 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
400 // Use ANDPS and ORPS to simulate FCOPYSIGN.
401 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
402 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
404 // We don't support sin/cos/fmod
405 setOperationAction(ISD::FSIN , MVT::f32, Expand);
406 setOperationAction(ISD::FCOS , MVT::f32, Expand);
408 // Special cases we handle for FP constants.
409 addLegalFPImmediate(APFloat(+0.0f)); // xorps
410 addLegalFPImmediate(APFloat(+0.0)); // FLD0
411 addLegalFPImmediate(APFloat(+1.0)); // FLD1
412 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
413 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
415 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
416 // this though and handle it in InstructionSelectPreprocess so that
417 // dagcombine2 can hack on these.
419 setConvertAction(MVT::f32, MVT::f64, Expand);
420 setConvertAction(MVT::f32, MVT::f80, Expand);
421 setConvertAction(MVT::f80, MVT::f32, Expand);
422 setConvertAction(MVT::f64, MVT::f32, Expand);
423 // And x87->x87 truncations also.
424 setConvertAction(MVT::f80, MVT::f64, Expand);
428 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
429 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
432 // f32 and f64 in x87.
433 // Set up the FP register classes.
434 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
435 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
437 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
438 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
439 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
440 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
442 // Floating truncations go through memory. If optimizing, we lie about
443 // this though and handle it in InstructionSelectPreprocess so that
444 // dagcombine2 can hack on these.
446 setConvertAction(MVT::f80, MVT::f32, Expand);
447 setConvertAction(MVT::f64, MVT::f32, Expand);
448 setConvertAction(MVT::f80, MVT::f64, Expand);
452 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
453 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
455 addLegalFPImmediate(APFloat(+0.0)); // FLD0
456 addLegalFPImmediate(APFloat(+1.0)); // FLD1
457 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
458 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
459 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
460 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
461 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
462 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
465 // Long double always uses X87.
466 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
467 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
468 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
470 APFloat TmpFlt(+0.0);
471 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
472 addLegalFPImmediate(TmpFlt); // FLD0
474 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
475 APFloat TmpFlt2(+1.0);
476 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
477 addLegalFPImmediate(TmpFlt2); // FLD1
478 TmpFlt2.changeSign();
479 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
483 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
484 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
487 // Always use a library call for pow.
488 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
489 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
490 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
492 // First set operation action for all vector types to expand. Then we
493 // will selectively turn on ones that can be effectively codegen'd.
494 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
495 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
496 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
497 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
498 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
499 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
500 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
501 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
502 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
503 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
504 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
505 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
506 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
507 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
508 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
509 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
510 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
511 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
512 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
513 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
514 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
515 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
516 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
517 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
518 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
519 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
520 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
521 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
522 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
523 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
524 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
525 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
526 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
527 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
528 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
529 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
530 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
531 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
532 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
535 if (Subtarget->hasMMX()) {
536 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
537 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
538 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
539 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
541 // FIXME: add MMX packed arithmetics
543 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
544 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
545 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
546 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
548 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
549 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
550 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
551 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
553 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
554 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
556 setOperationAction(ISD::AND, MVT::v8i8, Promote);
557 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
558 setOperationAction(ISD::AND, MVT::v4i16, Promote);
559 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
560 setOperationAction(ISD::AND, MVT::v2i32, Promote);
561 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
562 setOperationAction(ISD::AND, MVT::v1i64, Legal);
564 setOperationAction(ISD::OR, MVT::v8i8, Promote);
565 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
566 setOperationAction(ISD::OR, MVT::v4i16, Promote);
567 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
568 setOperationAction(ISD::OR, MVT::v2i32, Promote);
569 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
570 setOperationAction(ISD::OR, MVT::v1i64, Legal);
572 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
573 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
574 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
575 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
576 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
577 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
578 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
580 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
581 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
582 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
583 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
584 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
585 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
586 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
588 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
589 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
590 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
591 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
593 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
594 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
595 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
596 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
598 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
599 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
600 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
603 if (Subtarget->hasSSE1()) {
604 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
606 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
607 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
608 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
609 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
610 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
611 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
612 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
613 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
614 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
615 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
616 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
619 if (Subtarget->hasSSE2()) {
620 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
621 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
622 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
623 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
624 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
626 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
627 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
628 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
629 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
630 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
631 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
632 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
633 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
634 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
635 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
636 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
637 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
638 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
639 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
640 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
642 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
643 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
644 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
645 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
646 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
648 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
649 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
650 // Do not attempt to custom lower non-power-of-2 vectors
651 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
653 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
654 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
655 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
657 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
658 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
659 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
660 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
661 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
663 if (Subtarget->is64Bit()) {
664 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
665 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
668 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
669 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
670 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
671 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
672 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
673 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
674 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
675 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
676 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
677 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
678 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
679 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
682 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
684 // Custom lower v2i64 and v2f64 selects.
685 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
686 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
687 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
688 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
691 if (Subtarget->hasSSE41()) {
692 // FIXME: Do we need to handle scalar-to-vector here?
693 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
695 // i8 and i16 vectors are custom , because the source register and source
696 // source memory operand types are not the same width. f32 vectors are
697 // custom since the immediate controlling the insert encodes additional
699 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
700 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
701 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
702 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
704 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
705 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
706 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
707 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
709 if (Subtarget->is64Bit()) {
710 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
711 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
715 // We want to custom lower some of our intrinsics.
716 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
718 // We have target-specific dag combine patterns for the following nodes:
719 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
720 setTargetDAGCombine(ISD::BUILD_VECTOR);
721 setTargetDAGCombine(ISD::SELECT);
722 setTargetDAGCombine(ISD::STORE);
724 computeRegisterProperties();
726 // FIXME: These should be based on subtarget info. Plus, the values should
727 // be smaller when we are in optimizing for size mode.
728 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
729 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
730 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
731 allowUnalignedMemoryAccesses = true; // x86 supports it!
732 setPrefLoopAlignment(16);
737 X86TargetLowering::getSetCCResultType(const SDOperand &) const {
742 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
743 /// the desired ByVal argument alignment.
744 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
747 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
748 if (VTy->getBitWidth() == 128)
750 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
751 unsigned EltAlign = 0;
752 getMaxByValAlign(ATy->getElementType(), EltAlign);
753 if (EltAlign > MaxAlign)
755 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
756 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
757 unsigned EltAlign = 0;
758 getMaxByValAlign(STy->getElementType(i), EltAlign);
759 if (EltAlign > MaxAlign)
768 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
769 /// function arguments in the caller parameter area. For X86, aggregates
770 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
771 /// are at 4-byte boundaries.
772 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
773 if (Subtarget->is64Bit())
774 return getTargetData()->getABITypeAlignment(Ty);
776 if (Subtarget->hasSSE1())
777 getMaxByValAlign(Ty, Align);
781 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
783 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
784 SelectionDAG &DAG) const {
785 if (usesGlobalOffsetTable())
786 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
787 if (!Subtarget->isPICStyleRIPRel())
788 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
792 //===----------------------------------------------------------------------===//
793 // Return Value Calling Convention Implementation
794 //===----------------------------------------------------------------------===//
796 #include "X86GenCallingConv.inc"
798 /// LowerRET - Lower an ISD::RET node.
799 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
800 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
802 SmallVector<CCValAssign, 16> RVLocs;
803 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
804 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
805 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
806 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
808 // If this is the first return lowered for this function, add the regs to the
809 // liveout set for the function.
810 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
811 for (unsigned i = 0; i != RVLocs.size(); ++i)
812 if (RVLocs[i].isRegLoc())
813 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
815 SDOperand Chain = Op.getOperand(0);
817 // Handle tail call return.
818 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
819 if (Chain.getOpcode() == X86ISD::TAILCALL) {
820 SDOperand TailCall = Chain;
821 SDOperand TargetAddress = TailCall.getOperand(1);
822 SDOperand StackAdjustment = TailCall.getOperand(2);
823 assert(((TargetAddress.getOpcode() == ISD::Register &&
824 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
825 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
826 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
827 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
828 "Expecting an global address, external symbol, or register");
829 assert(StackAdjustment.getOpcode() == ISD::Constant &&
830 "Expecting a const value");
832 SmallVector<SDOperand,8> Operands;
833 Operands.push_back(Chain.getOperand(0));
834 Operands.push_back(TargetAddress);
835 Operands.push_back(StackAdjustment);
836 // Copy registers used by the call. Last operand is a flag so it is not
838 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
839 Operands.push_back(Chain.getOperand(i));
841 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
848 SmallVector<SDOperand, 6> RetOps;
849 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
850 // Operand #1 = Bytes To Pop
851 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
853 // Copy the result values into the output registers.
854 for (unsigned i = 0; i != RVLocs.size(); ++i) {
855 CCValAssign &VA = RVLocs[i];
856 assert(VA.isRegLoc() && "Can only return in registers!");
857 SDOperand ValToCopy = Op.getOperand(i*2+1);
859 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
860 // the RET instruction and handled by the FP Stackifier.
861 if (RVLocs[i].getLocReg() == X86::ST0 ||
862 RVLocs[i].getLocReg() == X86::ST1) {
863 // If this is a copy from an xmm register to ST(0), use an FPExtend to
864 // change the value to the FP stack register class.
865 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
866 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
867 RetOps.push_back(ValToCopy);
868 // Don't emit a copytoreg.
872 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
873 Flag = Chain.getValue(1);
876 // The x86-64 ABI for returning structs by value requires that we copy
877 // the sret argument into %rax for the return. We saved the argument into
878 // a virtual register in the entry block, so now we copy the value out
880 if (Subtarget->is64Bit() &&
881 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
882 MachineFunction &MF = DAG.getMachineFunction();
883 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
884 unsigned Reg = FuncInfo->getSRetReturnReg();
886 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
887 FuncInfo->setSRetReturnReg(Reg);
889 SDOperand Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
891 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
892 Flag = Chain.getValue(1);
895 RetOps[0] = Chain; // Update chain.
897 // Add the flag if we have it.
899 RetOps.push_back(Flag);
901 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
905 /// LowerCallResult - Lower the result values of an ISD::CALL into the
906 /// appropriate copies out of appropriate physical registers. This assumes that
907 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
908 /// being lowered. The returns a SDNode with the same number of values as the
910 SDNode *X86TargetLowering::
911 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
912 unsigned CallingConv, SelectionDAG &DAG) {
914 // Assign locations to each value returned by this call.
915 SmallVector<CCValAssign, 16> RVLocs;
916 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
917 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
918 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
920 SmallVector<SDOperand, 8> ResultVals;
922 // Copy all of the result registers out of their specified physreg.
923 for (unsigned i = 0; i != RVLocs.size(); ++i) {
924 MVT::ValueType CopyVT = RVLocs[i].getValVT();
926 // If this is a call to a function that returns an fp value on the floating
927 // point stack, but where we prefer to use the value in xmm registers, copy
928 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
929 if (RVLocs[i].getLocReg() == X86::ST0 &&
930 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
934 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
935 CopyVT, InFlag).getValue(1);
936 SDOperand Val = Chain.getValue(0);
937 InFlag = Chain.getValue(2);
939 if (CopyVT != RVLocs[i].getValVT()) {
940 // Round the F80 the right size, which also moves to the appropriate xmm
942 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
943 // This truncation won't change the value.
944 DAG.getIntPtrConstant(1));
947 ResultVals.push_back(Val);
950 // Merge everything together with a MERGE_VALUES node.
951 ResultVals.push_back(Chain);
952 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
953 &ResultVals[0], ResultVals.size()).Val;
957 //===----------------------------------------------------------------------===//
958 // C & StdCall & Fast Calling Convention implementation
959 //===----------------------------------------------------------------------===//
960 // StdCall calling convention seems to be standard for many Windows' API
961 // routines and around. It differs from C calling convention just a little:
962 // callee should clean up the stack, not caller. Symbols should be also
963 // decorated in some fancy way :) It doesn't support any vector arguments.
964 // For info on fast calling convention see Fast Calling Convention (tail call)
965 // implementation LowerX86_32FastCCCallTo.
967 /// AddLiveIn - This helper function adds the specified physical register to the
968 /// MachineFunction as a live in value. It also creates a corresponding virtual
970 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
971 const TargetRegisterClass *RC) {
972 assert(RC->contains(PReg) && "Not the correct regclass!");
973 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
974 MF.getRegInfo().addLiveIn(PReg, VReg);
978 /// CallIsStructReturn - Determines whether a CALL node uses struct return
980 static bool CallIsStructReturn(SDOperand Op) {
981 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
985 return cast<ARG_FLAGSSDNode>(Op.getOperand(6))->getArgFlags().isSRet();
988 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
989 /// return semantics.
990 static bool ArgsAreStructReturn(SDOperand Op) {
991 unsigned NumArgs = Op.Val->getNumValues() - 1;
995 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
998 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
999 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1001 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1002 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1006 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1009 case CallingConv::X86_StdCall:
1010 return !Subtarget->is64Bit();
1011 case CallingConv::X86_FastCall:
1012 return !Subtarget->is64Bit();
1013 case CallingConv::Fast:
1014 return PerformTailCallOpt;
1018 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1019 /// FORMAL_ARGUMENTS node.
1020 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1021 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1023 if (Subtarget->is64Bit()) {
1024 if (Subtarget->isTargetWin64())
1025 return CC_X86_Win64_C;
1027 if (CC == CallingConv::Fast && PerformTailCallOpt)
1028 return CC_X86_64_TailCall;
1034 if (CC == CallingConv::X86_FastCall)
1035 return CC_X86_32_FastCall;
1036 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1037 return CC_X86_32_TailCall;
1042 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1043 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1045 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1046 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1047 if (CC == CallingConv::X86_FastCall)
1049 else if (CC == CallingConv::X86_StdCall)
1055 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1056 /// in a register before calling.
1057 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1058 return !IsTailCall && !Is64Bit &&
1059 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1060 Subtarget->isPICStyleGOT();
1063 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1064 /// address to be loaded in a register.
1066 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1067 return !Is64Bit && IsTailCall &&
1068 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1069 Subtarget->isPICStyleGOT();
1072 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1073 /// by "Src" to address "Dst" with size and alignment information specified by
1074 /// the specific parameter attribute. The copy will be passed as a byval
1075 /// function parameter.
1077 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1078 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1079 SDOperand SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1080 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1081 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1084 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1085 const CCValAssign &VA,
1086 MachineFrameInfo *MFI,
1088 SDOperand Root, unsigned i) {
1089 // Create the nodes corresponding to a load from this parameter slot.
1090 ISD::ArgFlagsTy Flags =
1091 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1092 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1093 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1095 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1096 // changed with more analysis.
1097 // In case of tail call optimization mark all arguments mutable. Since they
1098 // could be overwritten by lowering of arguments in case of a tail call.
1099 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1100 VA.getLocMemOffset(), isImmutable);
1101 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1102 if (Flags.isByVal())
1104 return DAG.getLoad(VA.getValVT(), Root, FIN,
1105 PseudoSourceValue::getFixedStack(), FI);
1109 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1110 MachineFunction &MF = DAG.getMachineFunction();
1111 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1113 const Function* Fn = MF.getFunction();
1114 if (Fn->hasExternalLinkage() &&
1115 Subtarget->isTargetCygMing() &&
1116 Fn->getName() == "main")
1117 FuncInfo->setForceFramePointer(true);
1119 // Decorate the function name.
1120 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1122 MachineFrameInfo *MFI = MF.getFrameInfo();
1123 SDOperand Root = Op.getOperand(0);
1124 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1125 unsigned CC = MF.getFunction()->getCallingConv();
1126 bool Is64Bit = Subtarget->is64Bit();
1127 bool IsWin64 = Subtarget->isTargetWin64();
1129 assert(!(isVarArg && CC == CallingConv::Fast) &&
1130 "Var args not supported with calling convention fastcc");
1132 // Assign locations to all of the incoming arguments.
1133 SmallVector<CCValAssign, 16> ArgLocs;
1134 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1135 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1137 SmallVector<SDOperand, 8> ArgValues;
1138 unsigned LastVal = ~0U;
1139 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1140 CCValAssign &VA = ArgLocs[i];
1141 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1143 assert(VA.getValNo() != LastVal &&
1144 "Don't support value assigned to multiple locs yet");
1145 LastVal = VA.getValNo();
1147 if (VA.isRegLoc()) {
1148 MVT::ValueType RegVT = VA.getLocVT();
1149 TargetRegisterClass *RC;
1150 if (RegVT == MVT::i32)
1151 RC = X86::GR32RegisterClass;
1152 else if (Is64Bit && RegVT == MVT::i64)
1153 RC = X86::GR64RegisterClass;
1154 else if (RegVT == MVT::f32)
1155 RC = X86::FR32RegisterClass;
1156 else if (RegVT == MVT::f64)
1157 RC = X86::FR64RegisterClass;
1158 else if (MVT::isVector(RegVT) && MVT::getSizeInBits(RegVT) == 128)
1159 RC = X86::VR128RegisterClass;
1160 else if (MVT::isVector(RegVT)) {
1161 assert(MVT::getSizeInBits(RegVT) == 64);
1163 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1165 // Darwin calling convention passes MMX values in either GPRs or
1166 // XMMs in x86-64. Other targets pass them in memory.
1167 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1168 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1171 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1176 assert(0 && "Unknown argument type!");
1179 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1180 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1182 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1183 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1185 if (VA.getLocInfo() == CCValAssign::SExt)
1186 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1187 DAG.getValueType(VA.getValVT()));
1188 else if (VA.getLocInfo() == CCValAssign::ZExt)
1189 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1190 DAG.getValueType(VA.getValVT()));
1192 if (VA.getLocInfo() != CCValAssign::Full)
1193 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1195 // Handle MMX values passed in GPRs.
1196 if (Is64Bit && RegVT != VA.getLocVT()) {
1197 if (MVT::getSizeInBits(RegVT) == 64 && RC == X86::GR64RegisterClass)
1198 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1199 else if (RC == X86::VR128RegisterClass) {
1200 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1201 DAG.getConstant(0, MVT::i64));
1202 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1206 ArgValues.push_back(ArgValue);
1208 assert(VA.isMemLoc());
1209 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1213 // The x86-64 ABI for returning structs by value requires that we copy
1214 // the sret argument into %rax for the return. Save the argument into
1215 // a virtual register so that we can access it from the return points.
1216 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1217 MachineFunction &MF = DAG.getMachineFunction();
1218 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1219 unsigned Reg = FuncInfo->getSRetReturnReg();
1221 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1222 FuncInfo->setSRetReturnReg(Reg);
1224 SDOperand Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1225 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1228 unsigned StackSize = CCInfo.getNextStackOffset();
1229 // align stack specially for tail calls
1230 if (CC == CallingConv::Fast)
1231 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1233 // If the function takes variable number of arguments, make a frame index for
1234 // the start of the first vararg value... for expansion of llvm.va_start.
1236 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1237 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1240 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1242 // FIXME: We should really autogenerate these arrays
1243 static const unsigned GPR64ArgRegsWin64[] = {
1244 X86::RCX, X86::RDX, X86::R8, X86::R9
1246 static const unsigned XMMArgRegsWin64[] = {
1247 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1249 static const unsigned GPR64ArgRegs64Bit[] = {
1250 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1252 static const unsigned XMMArgRegs64Bit[] = {
1253 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1254 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1256 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1259 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1260 GPR64ArgRegs = GPR64ArgRegsWin64;
1261 XMMArgRegs = XMMArgRegsWin64;
1263 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1264 GPR64ArgRegs = GPR64ArgRegs64Bit;
1265 XMMArgRegs = XMMArgRegs64Bit;
1267 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1269 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1272 // For X86-64, if there are vararg parameters that are passed via
1273 // registers, then we must store them to their spots on the stack so they
1274 // may be loaded by deferencing the result of va_next.
1275 VarArgsGPOffset = NumIntRegs * 8;
1276 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1277 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1278 TotalNumXMMRegs * 16, 16);
1280 // Store the integer parameter registers.
1281 SmallVector<SDOperand, 8> MemOps;
1282 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1283 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1284 DAG.getIntPtrConstant(VarArgsGPOffset));
1285 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1286 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1287 X86::GR64RegisterClass);
1288 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1290 DAG.getStore(Val.getValue(1), Val, FIN,
1291 PseudoSourceValue::getFixedStack(),
1293 MemOps.push_back(Store);
1294 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1295 DAG.getIntPtrConstant(8));
1298 // Now store the XMM (fp + vector) parameter registers.
1299 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1300 DAG.getIntPtrConstant(VarArgsFPOffset));
1301 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1302 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1303 X86::VR128RegisterClass);
1304 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1306 DAG.getStore(Val.getValue(1), Val, FIN,
1307 PseudoSourceValue::getFixedStack(),
1309 MemOps.push_back(Store);
1310 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1311 DAG.getIntPtrConstant(16));
1313 if (!MemOps.empty())
1314 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1315 &MemOps[0], MemOps.size());
1319 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1320 // arguments and the arguments after the retaddr has been pushed are
1322 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1323 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1324 (StackSize & 7) == 0)
1327 ArgValues.push_back(Root);
1329 // Some CCs need callee pop.
1330 if (IsCalleePop(Op)) {
1331 BytesToPopOnReturn = StackSize; // Callee pops everything.
1332 BytesCallerReserves = 0;
1334 BytesToPopOnReturn = 0; // Callee pops nothing.
1335 // If this is an sret function, the return should pop the hidden pointer.
1336 if (!Is64Bit && ArgsAreStructReturn(Op))
1337 BytesToPopOnReturn = 4;
1338 BytesCallerReserves = StackSize;
1342 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1343 if (CC == CallingConv::X86_FastCall)
1344 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1347 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1349 // Return the new list of results.
1350 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1351 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1355 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1356 const SDOperand &StackPtr,
1357 const CCValAssign &VA,
1360 unsigned LocMemOffset = VA.getLocMemOffset();
1361 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1362 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1363 ISD::ArgFlagsTy Flags =
1364 cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->getArgFlags();
1365 if (Flags.isByVal()) {
1366 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1368 return DAG.getStore(Chain, Arg, PtrOff,
1369 PseudoSourceValue::getStack(), LocMemOffset);
1372 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1373 /// optimization is performed and it is required.
1375 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1376 SDOperand &OutRetAddr,
1381 if (!IsTailCall || FPDiff==0) return Chain;
1383 // Adjust the Return address stack slot.
1384 MVT::ValueType VT = getPointerTy();
1385 OutRetAddr = getReturnAddressFrameIndex(DAG);
1386 // Load the "old" Return address.
1387 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1388 return SDOperand(OutRetAddr.Val, 1);
1391 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1392 /// optimization is performed and it is required (FPDiff!=0).
1394 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1395 SDOperand Chain, SDOperand RetAddrFrIdx,
1396 bool Is64Bit, int FPDiff) {
1397 // Store the return address to the appropriate stack slot.
1398 if (!FPDiff) return Chain;
1399 // Calculate the new stack slot for the return address.
1400 int SlotSize = Is64Bit ? 8 : 4;
1401 int NewReturnAddrFI =
1402 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1403 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1404 SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1405 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1406 PseudoSourceValue::getFixedStack(), NewReturnAddrFI);
1410 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1411 MachineFunction &MF = DAG.getMachineFunction();
1412 SDOperand Chain = Op.getOperand(0);
1413 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1414 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1415 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1416 && CC == CallingConv::Fast && PerformTailCallOpt;
1417 SDOperand Callee = Op.getOperand(4);
1418 bool Is64Bit = Subtarget->is64Bit();
1419 bool IsStructRet = CallIsStructReturn(Op);
1421 assert(!(isVarArg && CC == CallingConv::Fast) &&
1422 "Var args not supported with calling convention fastcc");
1424 // Analyze operands of the call, assigning locations to each operand.
1425 SmallVector<CCValAssign, 16> ArgLocs;
1426 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1427 CCInfo.AnalyzeCallOperands(Op.Val, CCAssignFnForNode(Op));
1429 // Get a count of how many bytes are to be pushed on the stack.
1430 unsigned NumBytes = CCInfo.getNextStackOffset();
1431 if (CC == CallingConv::Fast)
1432 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1434 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1435 // arguments and the arguments after the retaddr has been pushed are aligned.
1436 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1437 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1438 (NumBytes & 7) == 0)
1443 // Lower arguments at fp - stackoffset + fpdiff.
1444 unsigned NumBytesCallerPushed =
1445 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1446 FPDiff = NumBytesCallerPushed - NumBytes;
1448 // Set the delta of movement of the returnaddr stackslot.
1449 // But only set if delta is greater than previous delta.
1450 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1451 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1454 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1456 SDOperand RetAddrFrIdx;
1457 // Load return adress for tail calls.
1458 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1461 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1462 SmallVector<SDOperand, 8> MemOpChains;
1465 // Walk the register/memloc assignments, inserting copies/loads. In the case
1466 // of tail call optimization arguments are handle later.
1467 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1468 CCValAssign &VA = ArgLocs[i];
1469 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1470 bool isByVal = cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->
1471 getArgFlags().isByVal();
1473 // Promote the value if needed.
1474 switch (VA.getLocInfo()) {
1475 default: assert(0 && "Unknown loc info!");
1476 case CCValAssign::Full: break;
1477 case CCValAssign::SExt:
1478 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1480 case CCValAssign::ZExt:
1481 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1483 case CCValAssign::AExt:
1484 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1488 if (VA.isRegLoc()) {
1490 MVT::ValueType RegVT = VA.getLocVT();
1491 if (MVT::isVector(RegVT) && MVT::getSizeInBits(RegVT) == 64)
1492 switch (VA.getLocReg()) {
1495 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1497 // Special case: passing MMX values in GPR registers.
1498 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1501 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1502 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1503 // Special case: passing MMX values in XMM registers.
1504 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1505 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1506 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1507 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1508 getMOVLMask(2, DAG));
1513 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1515 if (!IsTailCall || (IsTailCall && isByVal)) {
1516 assert(VA.isMemLoc());
1517 if (StackPtr.Val == 0)
1518 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1520 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1526 if (!MemOpChains.empty())
1527 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1528 &MemOpChains[0], MemOpChains.size());
1530 // Build a sequence of copy-to-reg nodes chained together with token chain
1531 // and flag operands which copy the outgoing args into registers.
1533 // Tail call byval lowering might overwrite argument registers so in case of
1534 // tail call optimization the copies to registers are lowered later.
1536 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1537 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1539 InFlag = Chain.getValue(1);
1542 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1544 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1545 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1546 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1548 InFlag = Chain.getValue(1);
1550 // If we are tail calling and generating PIC/GOT style code load the address
1551 // of the callee into ecx. The value in ecx is used as target of the tail
1552 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1553 // calls on PIC/GOT architectures. Normally we would just put the address of
1554 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1555 // restored (since ebx is callee saved) before jumping to the target@PLT.
1556 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1557 // Note: The actual moving to ecx is done further down.
1558 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1559 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1560 !G->getGlobal()->hasProtectedVisibility())
1561 Callee = LowerGlobalAddress(Callee, DAG);
1562 else if (isa<ExternalSymbolSDNode>(Callee))
1563 Callee = LowerExternalSymbol(Callee,DAG);
1566 if (Is64Bit && isVarArg) {
1567 // From AMD64 ABI document:
1568 // For calls that may call functions that use varargs or stdargs
1569 // (prototype-less calls or calls to functions containing ellipsis (...) in
1570 // the declaration) %al is used as hidden argument to specify the number
1571 // of SSE registers used. The contents of %al do not need to match exactly
1572 // the number of registers, but must be an ubound on the number of SSE
1573 // registers used and is in the range 0 - 8 inclusive.
1575 // FIXME: Verify this on Win64
1576 // Count the number of XMM registers allocated.
1577 static const unsigned XMMArgRegs[] = {
1578 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1579 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1581 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1583 Chain = DAG.getCopyToReg(Chain, X86::AL,
1584 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1585 InFlag = Chain.getValue(1);
1589 // For tail calls lower the arguments to the 'real' stack slot.
1591 SmallVector<SDOperand, 8> MemOpChains2;
1594 // Do not flag preceeding copytoreg stuff together with the following stuff.
1595 InFlag = SDOperand();
1596 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1597 CCValAssign &VA = ArgLocs[i];
1598 if (!VA.isRegLoc()) {
1599 assert(VA.isMemLoc());
1600 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1601 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1602 ISD::ArgFlagsTy Flags =
1603 cast<ARG_FLAGSSDNode>(FlagsOp)->getArgFlags();
1604 // Create frame index.
1605 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1606 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1607 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1608 FIN = DAG.getFrameIndex(FI, getPointerTy());
1610 if (Flags.isByVal()) {
1611 // Copy relative to framepointer.
1612 SDOperand Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1613 if (StackPtr.Val == 0)
1614 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1615 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1617 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1620 // Store relative to framepointer.
1621 MemOpChains2.push_back(
1622 DAG.getStore(Chain, Arg, FIN,
1623 PseudoSourceValue::getFixedStack(), FI));
1628 if (!MemOpChains2.empty())
1629 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1630 &MemOpChains2[0], MemOpChains2.size());
1632 // Copy arguments to their registers.
1633 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1634 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1636 InFlag = Chain.getValue(1);
1638 InFlag =SDOperand();
1640 // Store the return address to the appropriate stack slot.
1641 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1645 // If the callee is a GlobalAddress node (quite common, every direct call is)
1646 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1647 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1648 // We should use extra load for direct calls to dllimported functions in
1650 if ((IsTailCall || !Is64Bit ||
1651 getTargetMachine().getCodeModel() != CodeModel::Large)
1652 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1653 getTargetMachine(), true))
1654 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1655 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1656 if (IsTailCall || !Is64Bit ||
1657 getTargetMachine().getCodeModel() != CodeModel::Large)
1658 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1659 } else if (IsTailCall) {
1660 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1662 Chain = DAG.getCopyToReg(Chain,
1663 DAG.getRegister(Opc, getPointerTy()),
1665 Callee = DAG.getRegister(Opc, getPointerTy());
1666 // Add register as live out.
1667 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1670 // Returns a chain & a flag for retval copy to use.
1671 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1672 SmallVector<SDOperand, 8> Ops;
1675 Ops.push_back(Chain);
1676 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1677 Ops.push_back(DAG.getIntPtrConstant(0));
1679 Ops.push_back(InFlag);
1680 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1681 InFlag = Chain.getValue(1);
1683 // Returns a chain & a flag for retval copy to use.
1684 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1688 Ops.push_back(Chain);
1689 Ops.push_back(Callee);
1692 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1694 // Add argument registers to the end of the list so that they are known live
1696 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1697 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1698 RegsToPass[i].second.getValueType()));
1700 // Add an implicit use GOT pointer in EBX.
1701 if (!IsTailCall && !Is64Bit &&
1702 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1703 Subtarget->isPICStyleGOT())
1704 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1706 // Add an implicit use of AL for x86 vararg functions.
1707 if (Is64Bit && isVarArg)
1708 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1711 Ops.push_back(InFlag);
1714 assert(InFlag.Val &&
1715 "Flag must be set. Depend on flag being set in LowerRET");
1716 Chain = DAG.getNode(X86ISD::TAILCALL,
1717 Op.Val->getVTList(), &Ops[0], Ops.size());
1719 return SDOperand(Chain.Val, Op.ResNo);
1722 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1723 InFlag = Chain.getValue(1);
1725 // Create the CALLSEQ_END node.
1726 unsigned NumBytesForCalleeToPush;
1727 if (IsCalleePop(Op))
1728 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1729 else if (!Is64Bit && IsStructRet)
1730 // If this is is a call to a struct-return function, the callee
1731 // pops the hidden struct pointer, so we have to push it back.
1732 // This is common for Darwin/X86, Linux & Mingw32 targets.
1733 NumBytesForCalleeToPush = 4;
1735 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1737 // Returns a flag for retval copy to use.
1738 Chain = DAG.getCALLSEQ_END(Chain,
1739 DAG.getIntPtrConstant(NumBytes),
1740 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1742 InFlag = Chain.getValue(1);
1744 // Handle result values, copying them out of physregs into vregs that we
1746 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1750 //===----------------------------------------------------------------------===//
1751 // Fast Calling Convention (tail call) implementation
1752 //===----------------------------------------------------------------------===//
1754 // Like std call, callee cleans arguments, convention except that ECX is
1755 // reserved for storing the tail called function address. Only 2 registers are
1756 // free for argument passing (inreg). Tail call optimization is performed
1758 // * tailcallopt is enabled
1759 // * caller/callee are fastcc
1760 // On X86_64 architecture with GOT-style position independent code only local
1761 // (within module) calls are supported at the moment.
1762 // To keep the stack aligned according to platform abi the function
1763 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1764 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1765 // If a tail called function callee has more arguments than the caller the
1766 // caller needs to make sure that there is room to move the RETADDR to. This is
1767 // achieved by reserving an area the size of the argument delta right after the
1768 // original REtADDR, but before the saved framepointer or the spilled registers
1769 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1781 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1782 /// for a 16 byte align requirement.
1783 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1784 SelectionDAG& DAG) {
1785 if (PerformTailCallOpt) {
1786 MachineFunction &MF = DAG.getMachineFunction();
1787 const TargetMachine &TM = MF.getTarget();
1788 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1789 unsigned StackAlignment = TFI.getStackAlignment();
1790 uint64_t AlignMask = StackAlignment - 1;
1791 int64_t Offset = StackSize;
1792 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1793 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1794 // Number smaller than 12 so just add the difference.
1795 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1797 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1798 Offset = ((~AlignMask) & Offset) + StackAlignment +
1799 (StackAlignment-SlotSize);
1806 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1807 /// following the call is a return. A function is eligible if caller/callee
1808 /// calling conventions match, currently only fastcc supports tail calls, and
1809 /// the function CALL is immediatly followed by a RET.
1810 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1812 SelectionDAG& DAG) const {
1813 if (!PerformTailCallOpt)
1816 if (CheckTailCallReturnConstraints(Call, Ret)) {
1817 MachineFunction &MF = DAG.getMachineFunction();
1818 unsigned CallerCC = MF.getFunction()->getCallingConv();
1819 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1820 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1821 SDOperand Callee = Call.getOperand(4);
1822 // On x86/32Bit PIC/GOT tail calls are supported.
1823 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1824 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1827 // Can only do local tail calls (in same module, hidden or protected) on
1828 // x86_64 PIC/GOT at the moment.
1829 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1830 return G->getGlobal()->hasHiddenVisibility()
1831 || G->getGlobal()->hasProtectedVisibility();
1838 //===----------------------------------------------------------------------===//
1839 // Other Lowering Hooks
1840 //===----------------------------------------------------------------------===//
1843 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1844 MachineFunction &MF = DAG.getMachineFunction();
1845 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1846 int ReturnAddrIndex = FuncInfo->getRAIndex();
1848 if (ReturnAddrIndex == 0) {
1849 // Set up a frame object for the return address.
1850 if (Subtarget->is64Bit())
1851 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1853 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1855 FuncInfo->setRAIndex(ReturnAddrIndex);
1858 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1863 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1864 /// specific condition code. It returns a false if it cannot do a direct
1865 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1867 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1868 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1869 SelectionDAG &DAG) {
1870 X86CC = X86::COND_INVALID;
1872 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1873 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1874 // X > -1 -> X == 0, jump !sign.
1875 RHS = DAG.getConstant(0, RHS.getValueType());
1876 X86CC = X86::COND_NS;
1878 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1879 // X < 0 -> X == 0, jump on sign.
1880 X86CC = X86::COND_S;
1882 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1884 RHS = DAG.getConstant(0, RHS.getValueType());
1885 X86CC = X86::COND_LE;
1890 switch (SetCCOpcode) {
1892 case ISD::SETEQ: X86CC = X86::COND_E; break;
1893 case ISD::SETGT: X86CC = X86::COND_G; break;
1894 case ISD::SETGE: X86CC = X86::COND_GE; break;
1895 case ISD::SETLT: X86CC = X86::COND_L; break;
1896 case ISD::SETLE: X86CC = X86::COND_LE; break;
1897 case ISD::SETNE: X86CC = X86::COND_NE; break;
1898 case ISD::SETULT: X86CC = X86::COND_B; break;
1899 case ISD::SETUGT: X86CC = X86::COND_A; break;
1900 case ISD::SETULE: X86CC = X86::COND_BE; break;
1901 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1904 // On a floating point condition, the flags are set as follows:
1906 // 0 | 0 | 0 | X > Y
1907 // 0 | 0 | 1 | X < Y
1908 // 1 | 0 | 0 | X == Y
1909 // 1 | 1 | 1 | unordered
1911 switch (SetCCOpcode) {
1914 case ISD::SETEQ: X86CC = X86::COND_E; break;
1915 case ISD::SETOLT: Flip = true; // Fallthrough
1917 case ISD::SETGT: X86CC = X86::COND_A; break;
1918 case ISD::SETOLE: Flip = true; // Fallthrough
1920 case ISD::SETGE: X86CC = X86::COND_AE; break;
1921 case ISD::SETUGT: Flip = true; // Fallthrough
1923 case ISD::SETLT: X86CC = X86::COND_B; break;
1924 case ISD::SETUGE: Flip = true; // Fallthrough
1926 case ISD::SETLE: X86CC = X86::COND_BE; break;
1928 case ISD::SETNE: X86CC = X86::COND_NE; break;
1929 case ISD::SETUO: X86CC = X86::COND_P; break;
1930 case ISD::SETO: X86CC = X86::COND_NP; break;
1933 std::swap(LHS, RHS);
1936 return X86CC != X86::COND_INVALID;
1939 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1940 /// code. Current x86 isa includes the following FP cmov instructions:
1941 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1942 static bool hasFPCMov(unsigned X86CC) {
1958 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1959 /// true if Op is undef or if its value falls within the specified range (L, H].
1960 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1961 if (Op.getOpcode() == ISD::UNDEF)
1964 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1965 return (Val >= Low && Val < Hi);
1968 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
1969 /// true if Op is undef or if its value equal to the specified value.
1970 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1971 if (Op.getOpcode() == ISD::UNDEF)
1973 return cast<ConstantSDNode>(Op)->getValue() == Val;
1976 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1977 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1978 bool X86::isPSHUFDMask(SDNode *N) {
1979 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1981 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
1984 // Check if the value doesn't reference the second vector.
1985 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1986 SDOperand Arg = N->getOperand(i);
1987 if (Arg.getOpcode() == ISD::UNDEF) continue;
1988 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1989 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
1996 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1997 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1998 bool X86::isPSHUFHWMask(SDNode *N) {
1999 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2001 if (N->getNumOperands() != 8)
2004 // Lower quadword copied in order.
2005 for (unsigned i = 0; i != 4; ++i) {
2006 SDOperand Arg = N->getOperand(i);
2007 if (Arg.getOpcode() == ISD::UNDEF) continue;
2008 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2009 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2013 // Upper quadword shuffled.
2014 for (unsigned i = 4; i != 8; ++i) {
2015 SDOperand Arg = N->getOperand(i);
2016 if (Arg.getOpcode() == ISD::UNDEF) continue;
2017 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2018 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2019 if (Val < 4 || Val > 7)
2026 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2027 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2028 bool X86::isPSHUFLWMask(SDNode *N) {
2029 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2031 if (N->getNumOperands() != 8)
2034 // Upper quadword copied in order.
2035 for (unsigned i = 4; i != 8; ++i)
2036 if (!isUndefOrEqual(N->getOperand(i), i))
2039 // Lower quadword shuffled.
2040 for (unsigned i = 0; i != 4; ++i)
2041 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2047 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2048 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2049 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2050 if (NumElems != 2 && NumElems != 4) return false;
2052 unsigned Half = NumElems / 2;
2053 for (unsigned i = 0; i < Half; ++i)
2054 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2056 for (unsigned i = Half; i < NumElems; ++i)
2057 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2063 bool X86::isSHUFPMask(SDNode *N) {
2064 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2065 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2068 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2069 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2070 /// half elements to come from vector 1 (which would equal the dest.) and
2071 /// the upper half to come from vector 2.
2072 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2073 if (NumOps != 2 && NumOps != 4) return false;
2075 unsigned Half = NumOps / 2;
2076 for (unsigned i = 0; i < Half; ++i)
2077 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2079 for (unsigned i = Half; i < NumOps; ++i)
2080 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2085 static bool isCommutedSHUFP(SDNode *N) {
2086 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2087 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2090 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2091 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2092 bool X86::isMOVHLPSMask(SDNode *N) {
2093 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2095 if (N->getNumOperands() != 4)
2098 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2099 return isUndefOrEqual(N->getOperand(0), 6) &&
2100 isUndefOrEqual(N->getOperand(1), 7) &&
2101 isUndefOrEqual(N->getOperand(2), 2) &&
2102 isUndefOrEqual(N->getOperand(3), 3);
2105 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2106 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2108 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2109 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2111 if (N->getNumOperands() != 4)
2114 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2115 return isUndefOrEqual(N->getOperand(0), 2) &&
2116 isUndefOrEqual(N->getOperand(1), 3) &&
2117 isUndefOrEqual(N->getOperand(2), 2) &&
2118 isUndefOrEqual(N->getOperand(3), 3);
2121 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2122 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2123 bool X86::isMOVLPMask(SDNode *N) {
2124 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2126 unsigned NumElems = N->getNumOperands();
2127 if (NumElems != 2 && NumElems != 4)
2130 for (unsigned i = 0; i < NumElems/2; ++i)
2131 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2134 for (unsigned i = NumElems/2; i < NumElems; ++i)
2135 if (!isUndefOrEqual(N->getOperand(i), i))
2141 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2142 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2144 bool X86::isMOVHPMask(SDNode *N) {
2145 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2147 unsigned NumElems = N->getNumOperands();
2148 if (NumElems != 2 && NumElems != 4)
2151 for (unsigned i = 0; i < NumElems/2; ++i)
2152 if (!isUndefOrEqual(N->getOperand(i), i))
2155 for (unsigned i = 0; i < NumElems/2; ++i) {
2156 SDOperand Arg = N->getOperand(i + NumElems/2);
2157 if (!isUndefOrEqual(Arg, i + NumElems))
2164 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2165 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2166 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2167 bool V2IsSplat = false) {
2168 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2171 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2172 SDOperand BitI = Elts[i];
2173 SDOperand BitI1 = Elts[i+1];
2174 if (!isUndefOrEqual(BitI, j))
2177 if (isUndefOrEqual(BitI1, NumElts))
2180 if (!isUndefOrEqual(BitI1, j + NumElts))
2188 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2189 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2190 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2193 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2194 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2195 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2196 bool V2IsSplat = false) {
2197 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2200 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2201 SDOperand BitI = Elts[i];
2202 SDOperand BitI1 = Elts[i+1];
2203 if (!isUndefOrEqual(BitI, j + NumElts/2))
2206 if (isUndefOrEqual(BitI1, NumElts))
2209 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2217 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2218 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2219 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2222 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2223 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2225 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2226 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2228 unsigned NumElems = N->getNumOperands();
2229 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2232 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2233 SDOperand BitI = N->getOperand(i);
2234 SDOperand BitI1 = N->getOperand(i+1);
2236 if (!isUndefOrEqual(BitI, j))
2238 if (!isUndefOrEqual(BitI1, j))
2245 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2246 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2248 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2249 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2251 unsigned NumElems = N->getNumOperands();
2252 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2255 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2256 SDOperand BitI = N->getOperand(i);
2257 SDOperand BitI1 = N->getOperand(i + 1);
2259 if (!isUndefOrEqual(BitI, j))
2261 if (!isUndefOrEqual(BitI1, j))
2268 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2269 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2270 /// MOVSD, and MOVD, i.e. setting the lowest element.
2271 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2272 if (NumElts != 2 && NumElts != 4)
2275 if (!isUndefOrEqual(Elts[0], NumElts))
2278 for (unsigned i = 1; i < NumElts; ++i) {
2279 if (!isUndefOrEqual(Elts[i], i))
2286 bool X86::isMOVLMask(SDNode *N) {
2287 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2288 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2291 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2292 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2293 /// element of vector 2 and the other elements to come from vector 1 in order.
2294 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2295 bool V2IsSplat = false,
2296 bool V2IsUndef = false) {
2297 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2300 if (!isUndefOrEqual(Ops[0], 0))
2303 for (unsigned i = 1; i < NumOps; ++i) {
2304 SDOperand Arg = Ops[i];
2305 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2306 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2307 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2314 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2315 bool V2IsUndef = false) {
2316 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2317 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2318 V2IsSplat, V2IsUndef);
2321 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2322 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2323 bool X86::isMOVSHDUPMask(SDNode *N) {
2324 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2326 if (N->getNumOperands() != 4)
2329 // Expect 1, 1, 3, 3
2330 for (unsigned i = 0; i < 2; ++i) {
2331 SDOperand Arg = N->getOperand(i);
2332 if (Arg.getOpcode() == ISD::UNDEF) continue;
2333 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2334 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2335 if (Val != 1) return false;
2339 for (unsigned i = 2; i < 4; ++i) {
2340 SDOperand Arg = N->getOperand(i);
2341 if (Arg.getOpcode() == ISD::UNDEF) continue;
2342 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2343 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2344 if (Val != 3) return false;
2348 // Don't use movshdup if it can be done with a shufps.
2352 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2353 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2354 bool X86::isMOVSLDUPMask(SDNode *N) {
2355 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2357 if (N->getNumOperands() != 4)
2360 // Expect 0, 0, 2, 2
2361 for (unsigned i = 0; i < 2; ++i) {
2362 SDOperand Arg = N->getOperand(i);
2363 if (Arg.getOpcode() == ISD::UNDEF) continue;
2364 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2365 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2366 if (Val != 0) return false;
2370 for (unsigned i = 2; i < 4; ++i) {
2371 SDOperand Arg = N->getOperand(i);
2372 if (Arg.getOpcode() == ISD::UNDEF) continue;
2373 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2374 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2375 if (Val != 2) return false;
2379 // Don't use movshdup if it can be done with a shufps.
2383 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2384 /// specifies a identity operation on the LHS or RHS.
2385 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2386 unsigned NumElems = N->getNumOperands();
2387 for (unsigned i = 0; i < NumElems; ++i)
2388 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2393 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2394 /// a splat of a single element.
2395 static bool isSplatMask(SDNode *N) {
2396 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2398 // This is a splat operation if each element of the permute is the same, and
2399 // if the value doesn't reference the second vector.
2400 unsigned NumElems = N->getNumOperands();
2401 SDOperand ElementBase;
2403 for (; i != NumElems; ++i) {
2404 SDOperand Elt = N->getOperand(i);
2405 if (isa<ConstantSDNode>(Elt)) {
2411 if (!ElementBase.Val)
2414 for (; i != NumElems; ++i) {
2415 SDOperand Arg = N->getOperand(i);
2416 if (Arg.getOpcode() == ISD::UNDEF) continue;
2417 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2418 if (Arg != ElementBase) return false;
2421 // Make sure it is a splat of the first vector operand.
2422 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2425 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2426 /// a splat of a single element and it's a 2 or 4 element mask.
2427 bool X86::isSplatMask(SDNode *N) {
2428 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2430 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2431 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2433 return ::isSplatMask(N);
2436 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2437 /// specifies a splat of zero element.
2438 bool X86::isSplatLoMask(SDNode *N) {
2439 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2441 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2442 if (!isUndefOrEqual(N->getOperand(i), 0))
2447 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2448 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2450 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2451 unsigned NumOperands = N->getNumOperands();
2452 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2454 for (unsigned i = 0; i < NumOperands; ++i) {
2456 SDOperand Arg = N->getOperand(NumOperands-i-1);
2457 if (Arg.getOpcode() != ISD::UNDEF)
2458 Val = cast<ConstantSDNode>(Arg)->getValue();
2459 if (Val >= NumOperands) Val -= NumOperands;
2461 if (i != NumOperands - 1)
2468 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2469 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2471 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2473 // 8 nodes, but we only care about the last 4.
2474 for (unsigned i = 7; i >= 4; --i) {
2476 SDOperand Arg = N->getOperand(i);
2477 if (Arg.getOpcode() != ISD::UNDEF)
2478 Val = cast<ConstantSDNode>(Arg)->getValue();
2487 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2488 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2490 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2492 // 8 nodes, but we only care about the first 4.
2493 for (int i = 3; i >= 0; --i) {
2495 SDOperand Arg = N->getOperand(i);
2496 if (Arg.getOpcode() != ISD::UNDEF)
2497 Val = cast<ConstantSDNode>(Arg)->getValue();
2506 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2507 /// specifies a 8 element shuffle that can be broken into a pair of
2508 /// PSHUFHW and PSHUFLW.
2509 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2510 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2512 if (N->getNumOperands() != 8)
2515 // Lower quadword shuffled.
2516 for (unsigned i = 0; i != 4; ++i) {
2517 SDOperand Arg = N->getOperand(i);
2518 if (Arg.getOpcode() == ISD::UNDEF) continue;
2519 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2520 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2525 // Upper quadword shuffled.
2526 for (unsigned i = 4; i != 8; ++i) {
2527 SDOperand Arg = N->getOperand(i);
2528 if (Arg.getOpcode() == ISD::UNDEF) continue;
2529 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2530 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2531 if (Val < 4 || Val > 7)
2538 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2539 /// values in ther permute mask.
2540 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2541 SDOperand &V2, SDOperand &Mask,
2542 SelectionDAG &DAG) {
2543 MVT::ValueType VT = Op.getValueType();
2544 MVT::ValueType MaskVT = Mask.getValueType();
2545 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2546 unsigned NumElems = Mask.getNumOperands();
2547 SmallVector<SDOperand, 8> MaskVec;
2549 for (unsigned i = 0; i != NumElems; ++i) {
2550 SDOperand Arg = Mask.getOperand(i);
2551 if (Arg.getOpcode() == ISD::UNDEF) {
2552 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2555 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2556 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2558 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2560 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2564 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2565 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2568 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2569 /// the two vector operands have swapped position.
2571 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2572 MVT::ValueType MaskVT = Mask.getValueType();
2573 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2574 unsigned NumElems = Mask.getNumOperands();
2575 SmallVector<SDOperand, 8> MaskVec;
2576 for (unsigned i = 0; i != NumElems; ++i) {
2577 SDOperand Arg = Mask.getOperand(i);
2578 if (Arg.getOpcode() == ISD::UNDEF) {
2579 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2582 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2583 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2585 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2587 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2589 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2593 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2594 /// match movhlps. The lower half elements should come from upper half of
2595 /// V1 (and in order), and the upper half elements should come from the upper
2596 /// half of V2 (and in order).
2597 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2598 unsigned NumElems = Mask->getNumOperands();
2601 for (unsigned i = 0, e = 2; i != e; ++i)
2602 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2604 for (unsigned i = 2; i != 4; ++i)
2605 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2610 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2611 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2613 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2614 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2615 N = N->getOperand(0).Val;
2616 if (ISD::isNON_EXTLoad(N)) {
2618 *LD = cast<LoadSDNode>(N);
2625 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2626 /// match movlp{s|d}. The lower half elements should come from lower half of
2627 /// V1 (and in order), and the upper half elements should come from the upper
2628 /// half of V2 (and in order). And since V1 will become the source of the
2629 /// MOVLP, it must be either a vector load or a scalar load to vector.
2630 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2631 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2633 // Is V2 is a vector load, don't do this transformation. We will try to use
2634 // load folding shufps op.
2635 if (ISD::isNON_EXTLoad(V2))
2638 unsigned NumElems = Mask->getNumOperands();
2639 if (NumElems != 2 && NumElems != 4)
2641 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2642 if (!isUndefOrEqual(Mask->getOperand(i), i))
2644 for (unsigned i = NumElems/2; i != NumElems; ++i)
2645 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2650 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2652 static bool isSplatVector(SDNode *N) {
2653 if (N->getOpcode() != ISD::BUILD_VECTOR)
2656 SDOperand SplatValue = N->getOperand(0);
2657 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2658 if (N->getOperand(i) != SplatValue)
2663 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2665 static bool isUndefShuffle(SDNode *N) {
2666 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2669 SDOperand V1 = N->getOperand(0);
2670 SDOperand V2 = N->getOperand(1);
2671 SDOperand Mask = N->getOperand(2);
2672 unsigned NumElems = Mask.getNumOperands();
2673 for (unsigned i = 0; i != NumElems; ++i) {
2674 SDOperand Arg = Mask.getOperand(i);
2675 if (Arg.getOpcode() != ISD::UNDEF) {
2676 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2677 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2679 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2686 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2688 static inline bool isZeroNode(SDOperand Elt) {
2689 return ((isa<ConstantSDNode>(Elt) &&
2690 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2691 (isa<ConstantFPSDNode>(Elt) &&
2692 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2695 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2696 /// to an zero vector.
2697 static bool isZeroShuffle(SDNode *N) {
2698 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2701 SDOperand V1 = N->getOperand(0);
2702 SDOperand V2 = N->getOperand(1);
2703 SDOperand Mask = N->getOperand(2);
2704 unsigned NumElems = Mask.getNumOperands();
2705 for (unsigned i = 0; i != NumElems; ++i) {
2706 SDOperand Arg = Mask.getOperand(i);
2707 if (Arg.getOpcode() == ISD::UNDEF)
2710 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2711 if (Idx < NumElems) {
2712 unsigned Opc = V1.Val->getOpcode();
2713 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2715 if (Opc != ISD::BUILD_VECTOR ||
2716 !isZeroNode(V1.Val->getOperand(Idx)))
2718 } else if (Idx >= NumElems) {
2719 unsigned Opc = V2.Val->getOpcode();
2720 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2722 if (Opc != ISD::BUILD_VECTOR ||
2723 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2730 /// getZeroVector - Returns a vector of specified type with all zero elements.
2732 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2733 assert(MVT::isVector(VT) && "Expected a vector type");
2735 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2736 // type. This ensures they get CSE'd.
2737 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2739 if (MVT::getSizeInBits(VT) == 64) // MMX
2740 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2742 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2743 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2746 /// getOnesVector - Returns a vector of specified type with all bits set.
2748 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2749 assert(MVT::isVector(VT) && "Expected a vector type");
2751 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2752 // type. This ensures they get CSE'd.
2753 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2755 if (MVT::getSizeInBits(VT) == 64) // MMX
2756 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2758 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2759 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2763 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2764 /// that point to V2 points to its first element.
2765 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2766 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2768 bool Changed = false;
2769 SmallVector<SDOperand, 8> MaskVec;
2770 unsigned NumElems = Mask.getNumOperands();
2771 for (unsigned i = 0; i != NumElems; ++i) {
2772 SDOperand Arg = Mask.getOperand(i);
2773 if (Arg.getOpcode() != ISD::UNDEF) {
2774 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2775 if (Val > NumElems) {
2776 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2780 MaskVec.push_back(Arg);
2784 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2785 &MaskVec[0], MaskVec.size());
2789 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2790 /// operation of specified width.
2791 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2792 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2793 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2795 SmallVector<SDOperand, 8> MaskVec;
2796 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2797 for (unsigned i = 1; i != NumElems; ++i)
2798 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2799 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2802 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2803 /// of specified width.
2804 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2805 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2806 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2807 SmallVector<SDOperand, 8> MaskVec;
2808 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2809 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2810 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2812 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2815 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2816 /// of specified width.
2817 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2818 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2819 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2820 unsigned Half = NumElems/2;
2821 SmallVector<SDOperand, 8> MaskVec;
2822 for (unsigned i = 0; i != Half; ++i) {
2823 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2824 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2826 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2829 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2830 /// element #0 of a vector with the specified index, leaving the rest of the
2831 /// elements in place.
2832 static SDOperand getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2833 SelectionDAG &DAG) {
2834 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2835 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2836 SmallVector<SDOperand, 8> MaskVec;
2837 // Element #0 of the result gets the elt we are replacing.
2838 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2839 for (unsigned i = 1; i != NumElems; ++i)
2840 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2841 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2844 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2845 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG, bool HasSSE2) {
2846 MVT::ValueType PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2847 MVT::ValueType VT = Op.getValueType();
2850 SDOperand V1 = Op.getOperand(0);
2851 SDOperand Mask = Op.getOperand(2);
2852 unsigned NumElems = Mask.getNumOperands();
2853 // Special handling of v4f32 -> v4i32.
2854 if (VT != MVT::v4f32) {
2855 Mask = getUnpacklMask(NumElems, DAG);
2856 while (NumElems > 4) {
2857 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2860 Mask = getZeroVector(MVT::v4i32, DAG);
2863 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2864 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2865 DAG.getNode(ISD::UNDEF, PVT), Mask);
2866 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2869 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2870 /// vector of zero or undef vector. This produces a shuffle where the low
2871 /// element of V2 is swizzled into the zero/undef vector, landing at element
2872 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2873 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, unsigned Idx,
2874 bool isZero, SelectionDAG &DAG) {
2875 MVT::ValueType VT = V2.getValueType();
2876 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2877 unsigned NumElems = MVT::getVectorNumElements(V2.getValueType());
2878 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2879 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2880 SmallVector<SDOperand, 16> MaskVec;
2881 for (unsigned i = 0; i != NumElems; ++i)
2882 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2883 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2885 MaskVec.push_back(DAG.getConstant(i, EVT));
2886 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2887 &MaskVec[0], MaskVec.size());
2888 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2891 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2893 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2894 unsigned NumNonZero, unsigned NumZero,
2895 SelectionDAG &DAG, TargetLowering &TLI) {
2901 for (unsigned i = 0; i < 16; ++i) {
2902 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2903 if (ThisIsNonZero && First) {
2905 V = getZeroVector(MVT::v8i16, DAG);
2907 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2912 SDOperand ThisElt(0, 0), LastElt(0, 0);
2913 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2914 if (LastIsNonZero) {
2915 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2917 if (ThisIsNonZero) {
2918 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2919 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2920 ThisElt, DAG.getConstant(8, MVT::i8));
2922 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2927 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2928 DAG.getIntPtrConstant(i/2));
2932 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2935 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2937 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2938 unsigned NumNonZero, unsigned NumZero,
2939 SelectionDAG &DAG, TargetLowering &TLI) {
2945 for (unsigned i = 0; i < 8; ++i) {
2946 bool isNonZero = (NonZeros & (1 << i)) != 0;
2950 V = getZeroVector(MVT::v8i16, DAG);
2952 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2955 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2956 DAG.getIntPtrConstant(i));
2964 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2965 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
2966 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
2967 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
2968 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
2969 // eliminated on x86-32 hosts.
2970 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
2973 if (ISD::isBuildVectorAllOnes(Op.Val))
2974 return getOnesVector(Op.getValueType(), DAG);
2975 return getZeroVector(Op.getValueType(), DAG);
2978 MVT::ValueType VT = Op.getValueType();
2979 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2980 unsigned EVTBits = MVT::getSizeInBits(EVT);
2982 unsigned NumElems = Op.getNumOperands();
2983 unsigned NumZero = 0;
2984 unsigned NumNonZero = 0;
2985 unsigned NonZeros = 0;
2986 bool IsAllConstants = true;
2987 SmallSet<SDOperand, 8> Values;
2988 for (unsigned i = 0; i < NumElems; ++i) {
2989 SDOperand Elt = Op.getOperand(i);
2990 if (Elt.getOpcode() == ISD::UNDEF)
2993 if (Elt.getOpcode() != ISD::Constant &&
2994 Elt.getOpcode() != ISD::ConstantFP)
2995 IsAllConstants = false;
2996 if (isZeroNode(Elt))
2999 NonZeros |= (1 << i);
3004 if (NumNonZero == 0) {
3005 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3006 return DAG.getNode(ISD::UNDEF, VT);
3009 // Special case for single non-zero, non-undef, element.
3010 if (NumNonZero == 1 && NumElems <= 4) {
3011 unsigned Idx = CountTrailingZeros_32(NonZeros);
3012 SDOperand Item = Op.getOperand(Idx);
3014 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3015 // the value are obviously zero, truncate the value to i32 and do the
3016 // insertion that way. Only do this if the value is non-constant or if the
3017 // value is a constant being inserted into element 0. It is cheaper to do
3018 // a constant pool load than it is to do a movd + shuffle.
3019 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3020 (!IsAllConstants || Idx == 0)) {
3021 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3022 // Handle MMX and SSE both.
3023 MVT::ValueType VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3024 MVT::ValueType VecElts = VT == MVT::v2i64 ? 4 : 2;
3026 // Truncate the value (which may itself be a constant) to i32, and
3027 // convert it to a vector with movd (S2V+shuffle to zero extend).
3028 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3029 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3030 Item = getShuffleVectorZeroOrUndef(Item, 0, true, DAG);
3032 // Now we have our 32-bit value zero extended in the low element of
3033 // a vector. If Idx != 0, swizzle it into place.
3036 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3037 getSwapEltZeroMask(VecElts, Idx, DAG)
3039 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3041 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3045 // If we have a constant or non-constant insertion into the low element of
3046 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3047 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3048 // depending on what the source datatype is. Because we can only get here
3049 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3051 // Don't do this for i64 values on x86-32.
3052 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3053 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3054 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3055 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3058 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3061 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3062 // is a non-constant being inserted into an element other than the low one,
3063 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3064 // movd/movss) to move this into the low element, then shuffle it into
3066 if (EVTBits == 32) {
3067 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3069 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3070 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3071 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3072 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3073 SmallVector<SDOperand, 8> MaskVec;
3074 for (unsigned i = 0; i < NumElems; i++)
3075 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3076 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3077 &MaskVec[0], MaskVec.size());
3078 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3079 DAG.getNode(ISD::UNDEF, VT), Mask);
3083 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3084 if (Values.size() == 1)
3087 // A vector full of immediates; various special cases are already
3088 // handled, so this is best done with a single constant-pool load.
3092 // Let legalizer expand 2-wide build_vectors.
3093 if (EVTBits == 64) {
3094 if (NumNonZero == 1) {
3095 // One half is zero or undef.
3096 unsigned Idx = CountTrailingZeros_32(NonZeros);
3097 SDOperand V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3098 Op.getOperand(Idx));
3099 return getShuffleVectorZeroOrUndef(V2, Idx, true, DAG);
3104 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3105 if (EVTBits == 8 && NumElems == 16) {
3106 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3108 if (V.Val) return V;
3111 if (EVTBits == 16 && NumElems == 8) {
3112 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3114 if (V.Val) return V;
3117 // If element VT is == 32 bits, turn it into a number of shuffles.
3118 SmallVector<SDOperand, 8> V;
3120 if (NumElems == 4 && NumZero > 0) {
3121 for (unsigned i = 0; i < 4; ++i) {
3122 bool isZero = !(NonZeros & (1 << i));
3124 V[i] = getZeroVector(VT, DAG);
3126 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3129 for (unsigned i = 0; i < 2; ++i) {
3130 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3133 V[i] = V[i*2]; // Must be a zero vector.
3136 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3137 getMOVLMask(NumElems, DAG));
3140 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3141 getMOVLMask(NumElems, DAG));
3144 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3145 getUnpacklMask(NumElems, DAG));
3150 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3151 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3152 SmallVector<SDOperand, 8> MaskVec;
3153 bool Reverse = (NonZeros & 0x3) == 2;
3154 for (unsigned i = 0; i < 2; ++i)
3156 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3158 MaskVec.push_back(DAG.getConstant(i, EVT));
3159 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3160 for (unsigned i = 0; i < 2; ++i)
3162 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3164 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3165 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3166 &MaskVec[0], MaskVec.size());
3167 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3170 if (Values.size() > 2) {
3171 // Expand into a number of unpckl*.
3173 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3174 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3175 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3176 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3177 for (unsigned i = 0; i < NumElems; ++i)
3178 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3180 while (NumElems != 0) {
3181 for (unsigned i = 0; i < NumElems; ++i)
3182 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3193 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3194 SDOperand PermMask, SelectionDAG &DAG,
3195 TargetLowering &TLI) {
3197 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3198 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3199 MVT::ValueType PtrVT = TLI.getPointerTy();
3200 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3201 PermMask.Val->op_end());
3203 // First record which half of which vector the low elements come from.
3204 SmallVector<unsigned, 4> LowQuad(4);
3205 for (unsigned i = 0; i < 4; ++i) {
3206 SDOperand Elt = MaskElts[i];
3207 if (Elt.getOpcode() == ISD::UNDEF)
3209 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3210 int QuadIdx = EltIdx / 4;
3213 int BestLowQuad = -1;
3214 unsigned MaxQuad = 1;
3215 for (unsigned i = 0; i < 4; ++i) {
3216 if (LowQuad[i] > MaxQuad) {
3218 MaxQuad = LowQuad[i];
3222 // Record which half of which vector the high elements come from.
3223 SmallVector<unsigned, 4> HighQuad(4);
3224 for (unsigned i = 4; i < 8; ++i) {
3225 SDOperand Elt = MaskElts[i];
3226 if (Elt.getOpcode() == ISD::UNDEF)
3228 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3229 int QuadIdx = EltIdx / 4;
3230 ++HighQuad[QuadIdx];
3232 int BestHighQuad = -1;
3234 for (unsigned i = 0; i < 4; ++i) {
3235 if (HighQuad[i] > MaxQuad) {
3237 MaxQuad = HighQuad[i];
3241 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3242 if (BestLowQuad != -1 || BestHighQuad != -1) {
3243 // First sort the 4 chunks in order using shufpd.
3244 SmallVector<SDOperand, 8> MaskVec;
3245 if (BestLowQuad != -1)
3246 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3248 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3249 if (BestHighQuad != -1)
3250 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3252 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3253 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3254 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3255 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3256 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3257 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3259 // Now sort high and low parts separately.
3260 BitVector InOrder(8);
3261 if (BestLowQuad != -1) {
3262 // Sort lower half in order using PSHUFLW.
3264 bool AnyOutOrder = false;
3265 for (unsigned i = 0; i != 4; ++i) {
3266 SDOperand Elt = MaskElts[i];
3267 if (Elt.getOpcode() == ISD::UNDEF) {
3268 MaskVec.push_back(Elt);
3271 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3274 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3275 // If this element is in the right place after this shuffle, then
3277 if ((int)(EltIdx / 4) == BestLowQuad)
3282 for (unsigned i = 4; i != 8; ++i)
3283 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3284 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3285 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3289 if (BestHighQuad != -1) {
3290 // Sort high half in order using PSHUFHW if possible.
3292 for (unsigned i = 0; i != 4; ++i)
3293 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3294 bool AnyOutOrder = false;
3295 for (unsigned i = 4; i != 8; ++i) {
3296 SDOperand Elt = MaskElts[i];
3297 if (Elt.getOpcode() == ISD::UNDEF) {
3298 MaskVec.push_back(Elt);
3301 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3304 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3305 // If this element is in the right place after this shuffle, then
3307 if ((int)(EltIdx / 4) == BestHighQuad)
3312 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3313 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3317 // The other elements are put in the right place using pextrw and pinsrw.
3318 for (unsigned i = 0; i != 8; ++i) {
3321 SDOperand Elt = MaskElts[i];
3322 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3325 SDOperand ExtOp = (EltIdx < 8)
3326 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3327 DAG.getConstant(EltIdx, PtrVT))
3328 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3329 DAG.getConstant(EltIdx - 8, PtrVT));
3330 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3331 DAG.getConstant(i, PtrVT));
3336 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3337 ///as few as possible.
3338 // First, let's find out how many elements are already in the right order.
3339 unsigned V1InOrder = 0;
3340 unsigned V1FromV1 = 0;
3341 unsigned V2InOrder = 0;
3342 unsigned V2FromV2 = 0;
3343 SmallVector<SDOperand, 8> V1Elts;
3344 SmallVector<SDOperand, 8> V2Elts;
3345 for (unsigned i = 0; i < 8; ++i) {
3346 SDOperand Elt = MaskElts[i];
3347 if (Elt.getOpcode() == ISD::UNDEF) {
3348 V1Elts.push_back(Elt);
3349 V2Elts.push_back(Elt);
3354 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3356 V1Elts.push_back(Elt);
3357 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3359 } else if (EltIdx == i+8) {
3360 V1Elts.push_back(Elt);
3361 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3363 } else if (EltIdx < 8) {
3364 V1Elts.push_back(Elt);
3367 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3372 if (V2InOrder > V1InOrder) {
3373 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3375 std::swap(V1Elts, V2Elts);
3376 std::swap(V1FromV1, V2FromV2);
3379 if ((V1FromV1 + V1InOrder) != 8) {
3380 // Some elements are from V2.
3382 // If there are elements that are from V1 but out of place,
3383 // then first sort them in place
3384 SmallVector<SDOperand, 8> MaskVec;
3385 for (unsigned i = 0; i < 8; ++i) {
3386 SDOperand Elt = V1Elts[i];
3387 if (Elt.getOpcode() == ISD::UNDEF) {
3388 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3391 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3393 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3395 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3397 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3398 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3402 for (unsigned i = 0; i < 8; ++i) {
3403 SDOperand Elt = V1Elts[i];
3404 if (Elt.getOpcode() == ISD::UNDEF)
3406 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3409 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3410 DAG.getConstant(EltIdx - 8, PtrVT));
3411 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3412 DAG.getConstant(i, PtrVT));
3416 // All elements are from V1.
3418 for (unsigned i = 0; i < 8; ++i) {
3419 SDOperand Elt = V1Elts[i];
3420 if (Elt.getOpcode() == ISD::UNDEF)
3422 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3423 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3424 DAG.getConstant(EltIdx, PtrVT));
3425 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3426 DAG.getConstant(i, PtrVT));
3432 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3433 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3434 /// done when every pair / quad of shuffle mask elements point to elements in
3435 /// the right sequence. e.g.
3436 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3438 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3440 SDOperand PermMask, SelectionDAG &DAG,
3441 TargetLowering &TLI) {
3442 unsigned NumElems = PermMask.getNumOperands();
3443 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3444 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3445 MVT::ValueType NewVT = MaskVT;
3447 case MVT::v4f32: NewVT = MVT::v2f64; break;
3448 case MVT::v4i32: NewVT = MVT::v2i64; break;
3449 case MVT::v8i16: NewVT = MVT::v4i32; break;
3450 case MVT::v16i8: NewVT = MVT::v4i32; break;
3451 default: assert(false && "Unexpected!");
3454 if (NewWidth == 2) {
3455 if (MVT::isInteger(VT))
3460 unsigned Scale = NumElems / NewWidth;
3461 SmallVector<SDOperand, 8> MaskVec;
3462 for (unsigned i = 0; i < NumElems; i += Scale) {
3463 unsigned StartIdx = ~0U;
3464 for (unsigned j = 0; j < Scale; ++j) {
3465 SDOperand Elt = PermMask.getOperand(i+j);
3466 if (Elt.getOpcode() == ISD::UNDEF)
3468 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3469 if (StartIdx == ~0U)
3470 StartIdx = EltIdx - (EltIdx % Scale);
3471 if (EltIdx != StartIdx + j)
3474 if (StartIdx == ~0U)
3475 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3477 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3480 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3481 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3482 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3483 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3484 &MaskVec[0], MaskVec.size()));
3487 /// getVZextMovL - Return a zero-extending vector move low node.
3489 static SDOperand getVZextMovL(MVT::ValueType VT, MVT::ValueType OpVT,
3490 SDOperand SrcOp, SelectionDAG &DAG,
3491 const X86Subtarget *Subtarget) {
3492 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3493 LoadSDNode *LD = NULL;
3494 if (!isScalarLoadToVector(SrcOp.Val, &LD))
3495 LD = dyn_cast<LoadSDNode>(SrcOp);
3497 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3499 MVT::ValueType EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3500 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3501 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3502 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3503 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3505 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3506 return DAG.getNode(ISD::BIT_CONVERT, VT,
3507 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3508 DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3509 SrcOp.getOperand(0).getOperand(0))));
3514 return DAG.getNode(ISD::BIT_CONVERT, VT,
3515 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3516 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3520 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3521 SDOperand V1 = Op.getOperand(0);
3522 SDOperand V2 = Op.getOperand(1);
3523 SDOperand PermMask = Op.getOperand(2);
3524 MVT::ValueType VT = Op.getValueType();
3525 unsigned NumElems = PermMask.getNumOperands();
3526 bool isMMX = MVT::getSizeInBits(VT) == 64;
3527 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3528 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3529 bool V1IsSplat = false;
3530 bool V2IsSplat = false;
3532 if (isUndefShuffle(Op.Val))
3533 return DAG.getNode(ISD::UNDEF, VT);
3535 if (isZeroShuffle(Op.Val))
3536 return getZeroVector(VT, DAG);
3538 if (isIdentityMask(PermMask.Val))
3540 else if (isIdentityMask(PermMask.Val, true))
3543 if (isSplatMask(PermMask.Val)) {
3544 if (isMMX || NumElems < 4) return Op;
3545 // Promote it to a v4{if}32 splat.
3546 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3549 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3551 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3552 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3554 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3555 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3556 // FIXME: Figure out a cleaner way to do this.
3557 // Try to make use of movq to zero out the top part.
3558 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3559 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3562 SDOperand NewV1 = NewOp.getOperand(0);
3563 SDOperand NewV2 = NewOp.getOperand(1);
3564 SDOperand NewMask = NewOp.getOperand(2);
3565 if (isCommutedMOVL(NewMask.Val, true, false)) {
3566 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3567 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
3570 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3571 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3573 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3574 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3579 if (X86::isMOVLMask(PermMask.Val)) {
3582 if (ISD::isBuildVectorAllZeros(V1.Val))
3583 return getVZextMovL(VT, VT, V2, DAG, Subtarget);
3587 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3588 X86::isMOVSLDUPMask(PermMask.Val) ||
3589 X86::isMOVHLPSMask(PermMask.Val) ||
3590 X86::isMOVHPMask(PermMask.Val) ||
3591 X86::isMOVLPMask(PermMask.Val))
3594 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3595 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3596 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3598 bool Commuted = false;
3599 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3600 // 1,1,1,1 -> v8i16 though.
3601 V1IsSplat = isSplatVector(V1.Val);
3602 V2IsSplat = isSplatVector(V2.Val);
3604 // Canonicalize the splat or undef, if present, to be on the RHS.
3605 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3606 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3607 std::swap(V1IsSplat, V2IsSplat);
3608 std::swap(V1IsUndef, V2IsUndef);
3612 // FIXME: Figure out a cleaner way to do this.
3613 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3614 if (V2IsUndef) return V1;
3615 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3617 // V2 is a splat, so the mask may be malformed. That is, it may point
3618 // to any V2 element. The instruction selectior won't like this. Get
3619 // a corrected mask and commute to form a proper MOVS{S|D}.
3620 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3621 if (NewMask.Val != PermMask.Val)
3622 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3627 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3628 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3629 X86::isUNPCKLMask(PermMask.Val) ||
3630 X86::isUNPCKHMask(PermMask.Val))
3634 // Normalize mask so all entries that point to V2 points to its first
3635 // element then try to match unpck{h|l} again. If match, return a
3636 // new vector_shuffle with the corrected mask.
3637 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3638 if (NewMask.Val != PermMask.Val) {
3639 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3640 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3641 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3642 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3643 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3644 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3649 // Normalize the node to match x86 shuffle ops if needed
3650 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3651 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3654 // Commute is back and try unpck* again.
3655 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3656 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3657 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3658 X86::isUNPCKLMask(PermMask.Val) ||
3659 X86::isUNPCKHMask(PermMask.Val))
3663 // Try PSHUF* first, then SHUFP*.
3664 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
3665 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3666 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.Val)) {
3667 if (V2.getOpcode() != ISD::UNDEF)
3668 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3669 DAG.getNode(ISD::UNDEF, VT), PermMask);
3674 if (Subtarget->hasSSE2() &&
3675 (X86::isPSHUFDMask(PermMask.Val) ||
3676 X86::isPSHUFHWMask(PermMask.Val) ||
3677 X86::isPSHUFLWMask(PermMask.Val))) {
3678 MVT::ValueType RVT = VT;
3679 if (VT == MVT::v4f32) {
3681 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
3682 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
3683 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3684 } else if (V2.getOpcode() != ISD::UNDEF)
3685 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
3686 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3688 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
3692 // Binary or unary shufps.
3693 if (X86::isSHUFPMask(PermMask.Val) ||
3694 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.Val)))
3698 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3699 if (VT == MVT::v8i16) {
3700 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3705 // Handle all 4 wide cases with a number of shuffles.
3706 if (NumElems == 4 && !isMMX) {
3707 // Don't do this for MMX.
3708 MVT::ValueType MaskVT = PermMask.getValueType();
3709 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3710 SmallVector<std::pair<int, int>, 8> Locs;
3711 Locs.reserve(NumElems);
3712 SmallVector<SDOperand, 8> Mask1(NumElems,
3713 DAG.getNode(ISD::UNDEF, MaskEVT));
3714 SmallVector<SDOperand, 8> Mask2(NumElems,
3715 DAG.getNode(ISD::UNDEF, MaskEVT));
3718 // If no more than two elements come from either vector. This can be
3719 // implemented with two shuffles. First shuffle gather the elements.
3720 // The second shuffle, which takes the first shuffle as both of its
3721 // vector operands, put the elements into the right order.
3722 for (unsigned i = 0; i != NumElems; ++i) {
3723 SDOperand Elt = PermMask.getOperand(i);
3724 if (Elt.getOpcode() == ISD::UNDEF) {
3725 Locs[i] = std::make_pair(-1, -1);
3727 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3728 if (Val < NumElems) {
3729 Locs[i] = std::make_pair(0, NumLo);
3733 Locs[i] = std::make_pair(1, NumHi);
3734 if (2+NumHi < NumElems)
3735 Mask1[2+NumHi] = Elt;
3740 if (NumLo <= 2 && NumHi <= 2) {
3741 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3742 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3743 &Mask1[0], Mask1.size()));
3744 for (unsigned i = 0; i != NumElems; ++i) {
3745 if (Locs[i].first == -1)
3748 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3749 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3750 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3754 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3755 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3756 &Mask2[0], Mask2.size()));
3759 // Break it into (shuffle shuffle_hi, shuffle_lo).
3761 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3762 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3763 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3764 unsigned MaskIdx = 0;
3766 unsigned HiIdx = NumElems/2;
3767 for (unsigned i = 0; i != NumElems; ++i) {
3768 if (i == NumElems/2) {
3774 SDOperand Elt = PermMask.getOperand(i);
3775 if (Elt.getOpcode() == ISD::UNDEF) {
3776 Locs[i] = std::make_pair(-1, -1);
3777 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3778 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3779 (*MaskPtr)[LoIdx] = Elt;
3782 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3783 (*MaskPtr)[HiIdx] = Elt;
3788 SDOperand LoShuffle =
3789 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3790 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3791 &LoMask[0], LoMask.size()));
3792 SDOperand HiShuffle =
3793 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3794 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3795 &HiMask[0], HiMask.size()));
3796 SmallVector<SDOperand, 8> MaskOps;
3797 for (unsigned i = 0; i != NumElems; ++i) {
3798 if (Locs[i].first == -1) {
3799 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3801 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3802 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3805 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3806 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3807 &MaskOps[0], MaskOps.size()));
3814 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3815 SelectionDAG &DAG) {
3816 MVT::ValueType VT = Op.getValueType();
3817 if (MVT::getSizeInBits(VT) == 8) {
3818 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3819 Op.getOperand(0), Op.getOperand(1));
3820 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3821 DAG.getValueType(VT));
3822 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3823 } else if (MVT::getSizeInBits(VT) == 16) {
3824 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3825 Op.getOperand(0), Op.getOperand(1));
3826 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3827 DAG.getValueType(VT));
3828 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3829 } else if (VT == MVT::f32) {
3830 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
3831 // the result back to FR32 register. It's only worth matching if the
3832 // result has a single use which is a store or a bitcast to i32.
3833 if (!Op.hasOneUse())
3835 SDNode *User = Op.Val->use_begin()->getUser();
3836 if (User->getOpcode() != ISD::STORE &&
3837 (User->getOpcode() != ISD::BIT_CONVERT ||
3838 User->getValueType(0) != MVT::i32))
3840 SDOperand Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3841 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
3843 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
3850 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3851 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3854 if (Subtarget->hasSSE41()) {
3855 SDOperand Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3860 MVT::ValueType VT = Op.getValueType();
3861 // TODO: handle v16i8.
3862 if (MVT::getSizeInBits(VT) == 16) {
3863 SDOperand Vec = Op.getOperand(0);
3864 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3866 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3867 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3868 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3870 // Transform it so it match pextrw which produces a 32-bit result.
3871 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3872 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3873 Op.getOperand(0), Op.getOperand(1));
3874 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3875 DAG.getValueType(VT));
3876 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3877 } else if (MVT::getSizeInBits(VT) == 32) {
3878 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3881 // SHUFPS the element to the lowest double word, then movss.
3882 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3883 SmallVector<SDOperand, 8> IdxVec;
3885 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3887 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3889 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3891 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3892 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3893 &IdxVec[0], IdxVec.size());
3894 SDOperand Vec = Op.getOperand(0);
3895 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3896 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3897 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3898 DAG.getIntPtrConstant(0));
3899 } else if (MVT::getSizeInBits(VT) == 64) {
3900 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3901 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3902 // to match extract_elt for f64.
3903 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3907 // UNPCKHPD the element to the lowest double word, then movsd.
3908 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3909 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3910 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3911 SmallVector<SDOperand, 8> IdxVec;
3912 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3914 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3915 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3916 &IdxVec[0], IdxVec.size());
3917 SDOperand Vec = Op.getOperand(0);
3918 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3919 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3920 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3921 DAG.getIntPtrConstant(0));
3928 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3929 MVT::ValueType VT = Op.getValueType();
3930 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3932 SDOperand N0 = Op.getOperand(0);
3933 SDOperand N1 = Op.getOperand(1);
3934 SDOperand N2 = Op.getOperand(2);
3936 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3937 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3939 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3941 if (N1.getValueType() != MVT::i32)
3942 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3943 if (N2.getValueType() != MVT::i32)
3944 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3945 return DAG.getNode(Opc, VT, N0, N1, N2);
3946 } else if (EVT == MVT::f32) {
3947 // Bits [7:6] of the constant are the source select. This will always be
3948 // zero here. The DAG Combiner may combine an extract_elt index into these
3949 // bits. For example (insert (extract, 3), 2) could be matched by putting
3950 // the '3' into bits [7:6] of X86ISD::INSERTPS.
3951 // Bits [5:4] of the constant are the destination select. This is the
3952 // value of the incoming immediate.
3953 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
3954 // combine either bitwise AND or insert of float 0.0 to set these bits.
3955 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3956 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3962 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3963 MVT::ValueType VT = Op.getValueType();
3964 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3966 if (Subtarget->hasSSE41())
3967 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3972 SDOperand N0 = Op.getOperand(0);
3973 SDOperand N1 = Op.getOperand(1);
3974 SDOperand N2 = Op.getOperand(2);
3976 if (MVT::getSizeInBits(EVT) == 16) {
3977 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3978 // as its second argument.
3979 if (N1.getValueType() != MVT::i32)
3980 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3981 if (N2.getValueType() != MVT::i32)
3982 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3983 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3989 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3990 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3991 MVT::ValueType VT = MVT::v2i32;
3992 switch (Op.getValueType()) {
3999 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4000 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4003 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4004 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4005 // one of the above mentioned nodes. It has to be wrapped because otherwise
4006 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4007 // be used to form addressing mode. These wrapped nodes will be selected
4010 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
4011 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4012 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
4014 CP->getAlignment());
4015 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4016 // With PIC, the address is actually $g + Offset.
4017 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4018 !Subtarget->isPICStyleRIPRel()) {
4019 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4020 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4028 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4029 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4030 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4031 // If it's a debug information descriptor, don't mess with it.
4032 if (DAG.isVerifiedDebugInfoDesc(Op))
4034 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4035 // With PIC, the address is actually $g + Offset.
4036 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4037 !Subtarget->isPICStyleRIPRel()) {
4038 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4039 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4043 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4044 // load the value at address GV, not the value of GV itself. This means that
4045 // the GlobalAddress must be in the base or index register of the address, not
4046 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4047 // The same applies for external symbols during PIC codegen
4048 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4049 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4050 PseudoSourceValue::getGOT(), 0);
4055 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4057 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4058 const MVT::ValueType PtrVT) {
4060 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4061 DAG.getNode(X86ISD::GlobalBaseReg,
4063 InFlag = Chain.getValue(1);
4065 // emit leal symbol@TLSGD(,%ebx,1), %eax
4066 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4067 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4068 GA->getValueType(0),
4070 SDOperand Ops[] = { Chain, TGA, InFlag };
4071 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4072 InFlag = Result.getValue(2);
4073 Chain = Result.getValue(1);
4075 // call ___tls_get_addr. This function receives its argument in
4076 // the register EAX.
4077 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4078 InFlag = Chain.getValue(1);
4080 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4081 SDOperand Ops1[] = { Chain,
4082 DAG.getTargetExternalSymbol("___tls_get_addr",
4084 DAG.getRegister(X86::EAX, PtrVT),
4085 DAG.getRegister(X86::EBX, PtrVT),
4087 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4088 InFlag = Chain.getValue(1);
4090 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4093 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4095 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4096 const MVT::ValueType PtrVT) {
4097 SDOperand InFlag, Chain;
4099 // emit leaq symbol@TLSGD(%rip), %rdi
4100 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4101 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4102 GA->getValueType(0),
4104 SDOperand Ops[] = { DAG.getEntryNode(), TGA};
4105 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4106 Chain = Result.getValue(1);
4107 InFlag = Result.getValue(2);
4109 // call ___tls_get_addr. This function receives its argument in
4110 // the register RDI.
4111 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4112 InFlag = Chain.getValue(1);
4114 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4115 SDOperand Ops1[] = { Chain,
4116 DAG.getTargetExternalSymbol("___tls_get_addr",
4118 DAG.getRegister(X86::RDI, PtrVT),
4120 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4121 InFlag = Chain.getValue(1);
4123 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4126 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4127 // "local exec" model.
4129 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4130 const MVT::ValueType PtrVT) {
4131 // Get the Thread Pointer
4132 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4133 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4135 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4136 GA->getValueType(0),
4138 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4140 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4141 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4142 PseudoSourceValue::getGOT(), 0);
4144 // The address of the thread local variable is the add of the thread
4145 // pointer with the offset of the variable.
4146 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4150 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4151 // TODO: implement the "local dynamic" model
4152 // TODO: implement the "initial exec"model for pic executables
4153 assert(Subtarget->isTargetELF() &&
4154 "TLS not implemented for non-ELF targets");
4155 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4156 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4157 // otherwise use the "Local Exec"TLS Model
4158 if (Subtarget->is64Bit()) {
4159 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4161 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4162 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4164 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4169 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4170 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4171 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4172 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4173 // With PIC, the address is actually $g + Offset.
4174 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4175 !Subtarget->isPICStyleRIPRel()) {
4176 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4177 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4184 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4185 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4186 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4187 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4188 // With PIC, the address is actually $g + Offset.
4189 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4190 !Subtarget->isPICStyleRIPRel()) {
4191 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4192 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4199 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4200 /// take a 2 x i32 value to shift plus a shift amount.
4201 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4202 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4203 MVT::ValueType VT = Op.getValueType();
4204 unsigned VTBits = MVT::getSizeInBits(VT);
4205 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4206 SDOperand ShOpLo = Op.getOperand(0);
4207 SDOperand ShOpHi = Op.getOperand(1);
4208 SDOperand ShAmt = Op.getOperand(2);
4209 SDOperand Tmp1 = isSRA ?
4210 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4211 DAG.getConstant(0, VT);
4213 SDOperand Tmp2, Tmp3;
4214 if (Op.getOpcode() == ISD::SHL_PARTS) {
4215 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4216 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4218 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4219 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4222 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4223 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4224 DAG.getConstant(VTBits, MVT::i8));
4225 SDOperand Cond = DAG.getNode(X86ISD::CMP, VT,
4226 AndNode, DAG.getConstant(0, MVT::i8));
4229 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4230 VTs = DAG.getNodeValueTypes(VT, MVT::Flag);
4231 SmallVector<SDOperand, 4> Ops;
4232 if (Op.getOpcode() == ISD::SHL_PARTS) {
4233 Ops.push_back(Tmp2);
4234 Ops.push_back(Tmp3);
4236 Ops.push_back(Cond);
4237 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4240 Ops.push_back(Tmp3);
4241 Ops.push_back(Tmp1);
4243 Ops.push_back(Cond);
4244 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4246 Ops.push_back(Tmp2);
4247 Ops.push_back(Tmp3);
4249 Ops.push_back(Cond);
4250 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4253 Ops.push_back(Tmp3);
4254 Ops.push_back(Tmp1);
4256 Ops.push_back(Cond);
4257 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4260 VTs = DAG.getNodeValueTypes(VT, VT);
4264 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4267 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4268 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4269 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
4270 "Unknown SINT_TO_FP to lower!");
4272 // These are really Legal; caller falls through into that case.
4273 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4275 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4276 Subtarget->is64Bit())
4279 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4280 MachineFunction &MF = DAG.getMachineFunction();
4281 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4282 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4283 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4285 PseudoSourceValue::getFixedStack(),
4290 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4292 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4294 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4295 SmallVector<SDOperand, 8> Ops;
4296 Ops.push_back(Chain);
4297 Ops.push_back(StackSlot);
4298 Ops.push_back(DAG.getValueType(SrcVT));
4299 SDOperand Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4300 Tys, &Ops[0], Ops.size());
4303 Chain = Result.getValue(1);
4304 SDOperand InFlag = Result.getValue(2);
4306 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4307 // shouldn't be necessary except that RFP cannot be live across
4308 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4309 MachineFunction &MF = DAG.getMachineFunction();
4310 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4311 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4312 Tys = DAG.getVTList(MVT::Other);
4313 SmallVector<SDOperand, 8> Ops;
4314 Ops.push_back(Chain);
4315 Ops.push_back(Result);
4316 Ops.push_back(StackSlot);
4317 Ops.push_back(DAG.getValueType(Op.getValueType()));
4318 Ops.push_back(InFlag);
4319 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4320 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4321 PseudoSourceValue::getFixedStack(), SSFI);
4327 std::pair<SDOperand,SDOperand> X86TargetLowering::
4328 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4329 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4330 "Unknown FP_TO_SINT to lower!");
4332 // These are really Legal.
4333 if (Op.getValueType() == MVT::i32 &&
4334 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4335 return std::make_pair(SDOperand(), SDOperand());
4336 if (Subtarget->is64Bit() &&
4337 Op.getValueType() == MVT::i64 &&
4338 Op.getOperand(0).getValueType() != MVT::f80)
4339 return std::make_pair(SDOperand(), SDOperand());
4341 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4343 MachineFunction &MF = DAG.getMachineFunction();
4344 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4345 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4346 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4348 switch (Op.getValueType()) {
4349 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4350 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4351 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4352 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4355 SDOperand Chain = DAG.getEntryNode();
4356 SDOperand Value = Op.getOperand(0);
4357 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4358 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4359 Chain = DAG.getStore(Chain, Value, StackSlot,
4360 PseudoSourceValue::getFixedStack(), SSFI);
4361 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4363 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4365 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4366 Chain = Value.getValue(1);
4367 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4368 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4371 // Build the FP_TO_INT*_IN_MEM
4372 SDOperand Ops[] = { Chain, Value, StackSlot };
4373 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4375 return std::make_pair(FIST, StackSlot);
4378 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4379 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4380 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4381 if (FIST.Val == 0) return SDOperand();
4384 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4387 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4388 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4389 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4390 if (FIST.Val == 0) return 0;
4392 // Return an i64 load from the stack slot.
4393 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4395 // Use a MERGE_VALUES node to drop the chain result value.
4396 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4399 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4400 MVT::ValueType VT = Op.getValueType();
4401 MVT::ValueType EltVT = VT;
4402 if (MVT::isVector(VT))
4403 EltVT = MVT::getVectorElementType(VT);
4404 std::vector<Constant*> CV;
4405 if (EltVT == MVT::f64) {
4406 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4410 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4416 Constant *C = ConstantVector::get(CV);
4417 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4418 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4419 PseudoSourceValue::getConstantPool(), 0,
4421 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4424 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4425 MVT::ValueType VT = Op.getValueType();
4426 MVT::ValueType EltVT = VT;
4427 unsigned EltNum = 1;
4428 if (MVT::isVector(VT)) {
4429 EltVT = MVT::getVectorElementType(VT);
4430 EltNum = MVT::getVectorNumElements(VT);
4432 std::vector<Constant*> CV;
4433 if (EltVT == MVT::f64) {
4434 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4438 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4444 Constant *C = ConstantVector::get(CV);
4445 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4446 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4447 PseudoSourceValue::getConstantPool(), 0,
4449 if (MVT::isVector(VT)) {
4450 return DAG.getNode(ISD::BIT_CONVERT, VT,
4451 DAG.getNode(ISD::XOR, MVT::v2i64,
4452 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4453 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4455 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4459 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4460 SDOperand Op0 = Op.getOperand(0);
4461 SDOperand Op1 = Op.getOperand(1);
4462 MVT::ValueType VT = Op.getValueType();
4463 MVT::ValueType SrcVT = Op1.getValueType();
4465 // If second operand is smaller, extend it first.
4466 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4467 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4470 // And if it is bigger, shrink it first.
4471 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4472 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4476 // At this point the operands and the result should have the same
4477 // type, and that won't be f80 since that is not custom lowered.
4479 // First get the sign bit of second operand.
4480 std::vector<Constant*> CV;
4481 if (SrcVT == MVT::f64) {
4482 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4483 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4485 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4486 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4487 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4488 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4490 Constant *C = ConstantVector::get(CV);
4491 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4492 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4493 PseudoSourceValue::getConstantPool(), 0,
4495 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4497 // Shift sign bit right or left if the two operands have different types.
4498 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4499 // Op0 is MVT::f32, Op1 is MVT::f64.
4500 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4501 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4502 DAG.getConstant(32, MVT::i32));
4503 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4504 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4505 DAG.getIntPtrConstant(0));
4508 // Clear first operand sign bit.
4510 if (VT == MVT::f64) {
4511 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4512 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4514 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4515 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4516 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4517 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4519 C = ConstantVector::get(CV);
4520 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4521 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4522 PseudoSourceValue::getConstantPool(), 0,
4524 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4526 // Or the value with the sign bit.
4527 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4530 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4531 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4533 SDOperand Op0 = Op.getOperand(0);
4534 SDOperand Op1 = Op.getOperand(1);
4535 SDOperand CC = Op.getOperand(2);
4536 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4537 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4540 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4542 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4543 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4544 DAG.getConstant(X86CC, MVT::i8), Cond);
4547 assert(isFP && "Illegal integer SetCC!");
4549 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4550 switch (SetCCOpcode) {
4551 default: assert(false && "Illegal floating point SetCC!");
4552 case ISD::SETOEQ: { // !PF & ZF
4553 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4554 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4555 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4556 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4557 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4559 case ISD::SETUNE: { // PF | !ZF
4560 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4561 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4562 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4563 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4564 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4570 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4571 bool addTest = true;
4572 SDOperand Cond = Op.getOperand(0);
4575 if (Cond.getOpcode() == ISD::SETCC)
4576 Cond = LowerSETCC(Cond, DAG);
4578 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4579 // setting operand in place of the X86ISD::SETCC.
4580 if (Cond.getOpcode() == X86ISD::SETCC) {
4581 CC = Cond.getOperand(0);
4583 SDOperand Cmp = Cond.getOperand(1);
4584 unsigned Opc = Cmp.getOpcode();
4585 MVT::ValueType VT = Op.getValueType();
4587 bool IllegalFPCMov = false;
4588 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4589 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4590 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4592 if ((Opc == X86ISD::CMP ||
4593 Opc == X86ISD::COMI ||
4594 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4601 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4602 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4605 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4607 SmallVector<SDOperand, 4> Ops;
4608 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4609 // condition is true.
4610 Ops.push_back(Op.getOperand(2));
4611 Ops.push_back(Op.getOperand(1));
4613 Ops.push_back(Cond);
4614 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4617 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4618 bool addTest = true;
4619 SDOperand Chain = Op.getOperand(0);
4620 SDOperand Cond = Op.getOperand(1);
4621 SDOperand Dest = Op.getOperand(2);
4624 if (Cond.getOpcode() == ISD::SETCC)
4625 Cond = LowerSETCC(Cond, DAG);
4627 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4628 // setting operand in place of the X86ISD::SETCC.
4629 if (Cond.getOpcode() == X86ISD::SETCC) {
4630 CC = Cond.getOperand(0);
4632 SDOperand Cmp = Cond.getOperand(1);
4633 unsigned Opc = Cmp.getOpcode();
4634 if (Opc == X86ISD::CMP ||
4635 Opc == X86ISD::COMI ||
4636 Opc == X86ISD::UCOMI) {
4643 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4644 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4646 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4647 Chain, Op.getOperand(2), CC, Cond);
4651 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4652 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4653 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4654 // that the guard pages used by the OS virtual memory manager are allocated in
4655 // correct sequence.
4657 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4658 SelectionDAG &DAG) {
4659 assert(Subtarget->isTargetCygMing() &&
4660 "This should be used only on Cygwin/Mingw targets");
4663 SDOperand Chain = Op.getOperand(0);
4664 SDOperand Size = Op.getOperand(1);
4665 // FIXME: Ensure alignment here
4669 MVT::ValueType IntPtr = getPointerTy();
4670 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4672 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4673 Flag = Chain.getValue(1);
4675 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4676 SDOperand Ops[] = { Chain,
4677 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4678 DAG.getRegister(X86::EAX, IntPtr),
4680 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4681 Flag = Chain.getValue(1);
4683 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4685 std::vector<MVT::ValueType> Tys;
4686 Tys.push_back(SPTy);
4687 Tys.push_back(MVT::Other);
4688 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4689 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4693 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
4695 SDOperand Dst, SDOperand Src,
4696 SDOperand Size, unsigned Align,
4697 const Value *DstSV, uint64_t DstSVOff) {
4698 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4700 /// If not DWORD aligned or size is more than the threshold, call the library.
4701 /// The libc version is likely to be faster for these cases. It can use the
4702 /// address value and run time information about the CPU.
4703 if ((Align & 3) == 0 ||
4705 ConstantSize->getValue() > getSubtarget()->getMaxInlineSizeThreshold()) {
4706 SDOperand InFlag(0, 0);
4708 // Check to see if there is a specialized entry-point for memory zeroing.
4709 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
4710 if (const char *bzeroEntry =
4711 V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
4712 MVT::ValueType IntPtr = getPointerTy();
4713 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4714 TargetLowering::ArgListTy Args;
4715 TargetLowering::ArgListEntry Entry;
4717 Entry.Ty = IntPtrTy;
4718 Args.push_back(Entry);
4720 Args.push_back(Entry);
4721 std::pair<SDOperand,SDOperand> CallResult =
4722 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4723 false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
4725 return CallResult.second;
4728 // Otherwise have the target-independent code call memset.
4732 uint64_t SizeVal = ConstantSize->getValue();
4733 SDOperand InFlag(0, 0);
4736 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
4737 unsigned BytesLeft = 0;
4738 bool TwoRepStos = false;
4741 uint64_t Val = ValC->getValue() & 255;
4743 // If the value is a constant, then we can potentially use larger sets.
4744 switch (Align & 3) {
4745 case 2: // WORD aligned
4748 Val = (Val << 8) | Val;
4750 case 0: // DWORD aligned
4753 Val = (Val << 8) | Val;
4754 Val = (Val << 16) | Val;
4755 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
4758 Val = (Val << 32) | Val;
4761 default: // Byte aligned
4764 Count = DAG.getIntPtrConstant(SizeVal);
4768 if (AVT > MVT::i8) {
4769 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4770 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
4771 BytesLeft = SizeVal % UBytes;
4774 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4776 InFlag = Chain.getValue(1);
4779 Count = DAG.getIntPtrConstant(SizeVal);
4780 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
4781 InFlag = Chain.getValue(1);
4784 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4786 InFlag = Chain.getValue(1);
4787 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4789 InFlag = Chain.getValue(1);
4791 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4792 SmallVector<SDOperand, 8> Ops;
4793 Ops.push_back(Chain);
4794 Ops.push_back(DAG.getValueType(AVT));
4795 Ops.push_back(InFlag);
4796 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4799 InFlag = Chain.getValue(1);
4801 MVT::ValueType CVT = Count.getValueType();
4802 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4803 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4804 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4806 InFlag = Chain.getValue(1);
4807 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4809 Ops.push_back(Chain);
4810 Ops.push_back(DAG.getValueType(MVT::i8));
4811 Ops.push_back(InFlag);
4812 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4813 } else if (BytesLeft) {
4814 // Handle the last 1 - 7 bytes.
4815 unsigned Offset = SizeVal - BytesLeft;
4816 MVT::ValueType AddrVT = Dst.getValueType();
4817 MVT::ValueType SizeVT = Size.getValueType();
4819 Chain = DAG.getMemset(Chain,
4820 DAG.getNode(ISD::ADD, AddrVT, Dst,
4821 DAG.getConstant(Offset, AddrVT)),
4823 DAG.getConstant(BytesLeft, SizeVT),
4824 Align, DstSV, DstSVOff + Offset);
4827 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
4832 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
4834 SDOperand Dst, SDOperand Src,
4835 SDOperand Size, unsigned Align,
4837 const Value *DstSV, uint64_t DstSVOff,
4838 const Value *SrcSV, uint64_t SrcSVOff){
4840 // This requires the copy size to be a constant, preferrably
4841 // within a subtarget-specific limit.
4842 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4845 uint64_t SizeVal = ConstantSize->getValue();
4846 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
4850 unsigned BytesLeft = 0;
4851 if (Align >= 8 && Subtarget->is64Bit())
4853 else if (Align >= 4)
4855 else if (Align >= 2)
4860 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4861 unsigned CountVal = SizeVal / UBytes;
4862 SDOperand Count = DAG.getIntPtrConstant(CountVal);
4863 BytesLeft = SizeVal % UBytes;
4865 SDOperand InFlag(0, 0);
4866 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4868 InFlag = Chain.getValue(1);
4869 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4871 InFlag = Chain.getValue(1);
4872 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4874 InFlag = Chain.getValue(1);
4876 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4877 SmallVector<SDOperand, 8> Ops;
4878 Ops.push_back(Chain);
4879 Ops.push_back(DAG.getValueType(AVT));
4880 Ops.push_back(InFlag);
4881 SDOperand RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4883 SmallVector<SDOperand, 4> Results;
4884 Results.push_back(RepMovs);
4886 // Handle the last 1 - 7 bytes.
4887 unsigned Offset = SizeVal - BytesLeft;
4888 MVT::ValueType DstVT = Dst.getValueType();
4889 MVT::ValueType SrcVT = Src.getValueType();
4890 MVT::ValueType SizeVT = Size.getValueType();
4891 Results.push_back(DAG.getMemcpy(Chain,
4892 DAG.getNode(ISD::ADD, DstVT, Dst,
4893 DAG.getConstant(Offset, DstVT)),
4894 DAG.getNode(ISD::ADD, SrcVT, Src,
4895 DAG.getConstant(Offset, SrcVT)),
4896 DAG.getConstant(BytesLeft, SizeVT),
4897 Align, AlwaysInline,
4898 DstSV, DstSVOff + Offset,
4899 SrcSV, SrcSVOff + Offset));
4902 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
4905 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4906 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4907 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4908 SDOperand TheChain = N->getOperand(0);
4909 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4910 if (Subtarget->is64Bit()) {
4911 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4912 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4913 MVT::i64, rax.getValue(2));
4914 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4915 DAG.getConstant(32, MVT::i8));
4917 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4920 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4921 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4924 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4925 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4926 MVT::i32, eax.getValue(2));
4927 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4928 SDOperand Ops[] = { eax, edx };
4929 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4931 // Use a MERGE_VALUES to return the value and chain.
4932 Ops[1] = edx.getValue(1);
4933 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4934 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4937 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4938 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4940 if (!Subtarget->is64Bit()) {
4941 // vastart just stores the address of the VarArgsFrameIndex slot into the
4942 // memory location argument.
4943 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4944 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4948 // gp_offset (0 - 6 * 8)
4949 // fp_offset (48 - 48 + 8 * 16)
4950 // overflow_arg_area (point to parameters coming in memory).
4952 SmallVector<SDOperand, 8> MemOps;
4953 SDOperand FIN = Op.getOperand(1);
4955 SDOperand Store = DAG.getStore(Op.getOperand(0),
4956 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4958 MemOps.push_back(Store);
4961 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4962 Store = DAG.getStore(Op.getOperand(0),
4963 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4965 MemOps.push_back(Store);
4967 // Store ptr to overflow_arg_area
4968 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4969 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4970 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4971 MemOps.push_back(Store);
4973 // Store ptr to reg_save_area.
4974 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4975 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4976 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4977 MemOps.push_back(Store);
4978 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4981 SDOperand X86TargetLowering::LowerVAARG(SDOperand Op, SelectionDAG &DAG) {
4982 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4983 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
4984 SDOperand Chain = Op.getOperand(0);
4985 SDOperand SrcPtr = Op.getOperand(1);
4986 SDOperand SrcSV = Op.getOperand(2);
4988 assert(0 && "VAArgInst is not yet implemented for x86-64!");
4993 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4994 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4995 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
4996 SDOperand Chain = Op.getOperand(0);
4997 SDOperand DstPtr = Op.getOperand(1);
4998 SDOperand SrcPtr = Op.getOperand(2);
4999 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5000 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5002 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5003 DAG.getIntPtrConstant(24), 8, false,
5004 DstSV, 0, SrcSV, 0);
5008 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5009 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5011 default: return SDOperand(); // Don't custom lower most intrinsics.
5012 // Comparison intrinsics.
5013 case Intrinsic::x86_sse_comieq_ss:
5014 case Intrinsic::x86_sse_comilt_ss:
5015 case Intrinsic::x86_sse_comile_ss:
5016 case Intrinsic::x86_sse_comigt_ss:
5017 case Intrinsic::x86_sse_comige_ss:
5018 case Intrinsic::x86_sse_comineq_ss:
5019 case Intrinsic::x86_sse_ucomieq_ss:
5020 case Intrinsic::x86_sse_ucomilt_ss:
5021 case Intrinsic::x86_sse_ucomile_ss:
5022 case Intrinsic::x86_sse_ucomigt_ss:
5023 case Intrinsic::x86_sse_ucomige_ss:
5024 case Intrinsic::x86_sse_ucomineq_ss:
5025 case Intrinsic::x86_sse2_comieq_sd:
5026 case Intrinsic::x86_sse2_comilt_sd:
5027 case Intrinsic::x86_sse2_comile_sd:
5028 case Intrinsic::x86_sse2_comigt_sd:
5029 case Intrinsic::x86_sse2_comige_sd:
5030 case Intrinsic::x86_sse2_comineq_sd:
5031 case Intrinsic::x86_sse2_ucomieq_sd:
5032 case Intrinsic::x86_sse2_ucomilt_sd:
5033 case Intrinsic::x86_sse2_ucomile_sd:
5034 case Intrinsic::x86_sse2_ucomigt_sd:
5035 case Intrinsic::x86_sse2_ucomige_sd:
5036 case Intrinsic::x86_sse2_ucomineq_sd: {
5038 ISD::CondCode CC = ISD::SETCC_INVALID;
5041 case Intrinsic::x86_sse_comieq_ss:
5042 case Intrinsic::x86_sse2_comieq_sd:
5046 case Intrinsic::x86_sse_comilt_ss:
5047 case Intrinsic::x86_sse2_comilt_sd:
5051 case Intrinsic::x86_sse_comile_ss:
5052 case Intrinsic::x86_sse2_comile_sd:
5056 case Intrinsic::x86_sse_comigt_ss:
5057 case Intrinsic::x86_sse2_comigt_sd:
5061 case Intrinsic::x86_sse_comige_ss:
5062 case Intrinsic::x86_sse2_comige_sd:
5066 case Intrinsic::x86_sse_comineq_ss:
5067 case Intrinsic::x86_sse2_comineq_sd:
5071 case Intrinsic::x86_sse_ucomieq_ss:
5072 case Intrinsic::x86_sse2_ucomieq_sd:
5073 Opc = X86ISD::UCOMI;
5076 case Intrinsic::x86_sse_ucomilt_ss:
5077 case Intrinsic::x86_sse2_ucomilt_sd:
5078 Opc = X86ISD::UCOMI;
5081 case Intrinsic::x86_sse_ucomile_ss:
5082 case Intrinsic::x86_sse2_ucomile_sd:
5083 Opc = X86ISD::UCOMI;
5086 case Intrinsic::x86_sse_ucomigt_ss:
5087 case Intrinsic::x86_sse2_ucomigt_sd:
5088 Opc = X86ISD::UCOMI;
5091 case Intrinsic::x86_sse_ucomige_ss:
5092 case Intrinsic::x86_sse2_ucomige_sd:
5093 Opc = X86ISD::UCOMI;
5096 case Intrinsic::x86_sse_ucomineq_ss:
5097 case Intrinsic::x86_sse2_ucomineq_sd:
5098 Opc = X86ISD::UCOMI;
5104 SDOperand LHS = Op.getOperand(1);
5105 SDOperand RHS = Op.getOperand(2);
5106 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5108 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5109 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5110 DAG.getConstant(X86CC, MVT::i8), Cond);
5111 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5114 // Fix vector shift instructions where the last operand is a non-immediate
5116 case Intrinsic::x86_sse2_pslli_w:
5117 case Intrinsic::x86_sse2_pslli_d:
5118 case Intrinsic::x86_sse2_pslli_q:
5119 case Intrinsic::x86_sse2_psrli_w:
5120 case Intrinsic::x86_sse2_psrli_d:
5121 case Intrinsic::x86_sse2_psrli_q:
5122 case Intrinsic::x86_sse2_psrai_w:
5123 case Intrinsic::x86_sse2_psrai_d:
5124 case Intrinsic::x86_mmx_pslli_w:
5125 case Intrinsic::x86_mmx_pslli_d:
5126 case Intrinsic::x86_mmx_pslli_q:
5127 case Intrinsic::x86_mmx_psrli_w:
5128 case Intrinsic::x86_mmx_psrli_d:
5129 case Intrinsic::x86_mmx_psrli_q:
5130 case Intrinsic::x86_mmx_psrai_w:
5131 case Intrinsic::x86_mmx_psrai_d: {
5132 SDOperand ShAmt = Op.getOperand(2);
5133 if (isa<ConstantSDNode>(ShAmt))
5136 unsigned NewIntNo = 0;
5137 MVT::ValueType ShAmtVT = MVT::v4i32;
5139 case Intrinsic::x86_sse2_pslli_w:
5140 NewIntNo = Intrinsic::x86_sse2_psll_w;
5142 case Intrinsic::x86_sse2_pslli_d:
5143 NewIntNo = Intrinsic::x86_sse2_psll_d;
5145 case Intrinsic::x86_sse2_pslli_q:
5146 NewIntNo = Intrinsic::x86_sse2_psll_q;
5148 case Intrinsic::x86_sse2_psrli_w:
5149 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5151 case Intrinsic::x86_sse2_psrli_d:
5152 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5154 case Intrinsic::x86_sse2_psrli_q:
5155 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5157 case Intrinsic::x86_sse2_psrai_w:
5158 NewIntNo = Intrinsic::x86_sse2_psra_w;
5160 case Intrinsic::x86_sse2_psrai_d:
5161 NewIntNo = Intrinsic::x86_sse2_psra_d;
5164 ShAmtVT = MVT::v2i32;
5166 case Intrinsic::x86_mmx_pslli_w:
5167 NewIntNo = Intrinsic::x86_mmx_psll_w;
5169 case Intrinsic::x86_mmx_pslli_d:
5170 NewIntNo = Intrinsic::x86_mmx_psll_d;
5172 case Intrinsic::x86_mmx_pslli_q:
5173 NewIntNo = Intrinsic::x86_mmx_psll_q;
5175 case Intrinsic::x86_mmx_psrli_w:
5176 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5178 case Intrinsic::x86_mmx_psrli_d:
5179 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5181 case Intrinsic::x86_mmx_psrli_q:
5182 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5184 case Intrinsic::x86_mmx_psrai_w:
5185 NewIntNo = Intrinsic::x86_mmx_psra_w;
5187 case Intrinsic::x86_mmx_psrai_d:
5188 NewIntNo = Intrinsic::x86_mmx_psra_d;
5190 default: abort(); // Can't reach here.
5195 MVT::ValueType VT = Op.getValueType();
5196 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5197 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5198 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5199 DAG.getConstant(NewIntNo, MVT::i32),
5200 Op.getOperand(1), ShAmt);
5205 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5206 // Depths > 0 not supported yet!
5207 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5210 // Just load the return address
5211 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5212 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5215 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5216 // Depths > 0 not supported yet!
5217 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5220 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5221 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5222 DAG.getIntPtrConstant(4));
5225 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5226 SelectionDAG &DAG) {
5227 // Is not yet supported on x86-64
5228 if (Subtarget->is64Bit())
5231 return DAG.getIntPtrConstant(8);
5234 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5236 assert(!Subtarget->is64Bit() &&
5237 "Lowering of eh_return builtin is not supported yet on x86-64");
5239 MachineFunction &MF = DAG.getMachineFunction();
5240 SDOperand Chain = Op.getOperand(0);
5241 SDOperand Offset = Op.getOperand(1);
5242 SDOperand Handler = Op.getOperand(2);
5244 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5247 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5248 DAG.getIntPtrConstant(-4UL));
5249 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5250 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5251 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5252 MF.getRegInfo().addLiveOut(X86::ECX);
5254 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5255 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5258 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5259 SelectionDAG &DAG) {
5260 SDOperand Root = Op.getOperand(0);
5261 SDOperand Trmp = Op.getOperand(1); // trampoline
5262 SDOperand FPtr = Op.getOperand(2); // nested function
5263 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5265 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5267 const X86InstrInfo *TII =
5268 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5270 if (Subtarget->is64Bit()) {
5271 SDOperand OutChains[6];
5273 // Large code-model.
5275 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5276 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5278 const unsigned char N86R10 =
5279 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5280 const unsigned char N86R11 =
5281 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5283 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5285 // Load the pointer to the nested function into R11.
5286 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5287 SDOperand Addr = Trmp;
5288 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5291 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5292 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5294 // Load the 'nest' parameter value into R10.
5295 // R10 is specified in X86CallingConv.td
5296 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5297 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5298 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5301 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5302 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5304 // Jump to the nested function.
5305 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5306 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5307 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5310 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5311 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5312 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5316 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5317 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5319 const Function *Func =
5320 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5321 unsigned CC = Func->getCallingConv();
5326 assert(0 && "Unsupported calling convention");
5327 case CallingConv::C:
5328 case CallingConv::X86_StdCall: {
5329 // Pass 'nest' parameter in ECX.
5330 // Must be kept in sync with X86CallingConv.td
5333 // Check that ECX wasn't needed by an 'inreg' parameter.
5334 const FunctionType *FTy = Func->getFunctionType();
5335 const PAListPtr &Attrs = Func->getParamAttrs();
5337 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5338 unsigned InRegCount = 0;
5341 for (FunctionType::param_iterator I = FTy->param_begin(),
5342 E = FTy->param_end(); I != E; ++I, ++Idx)
5343 if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5344 // FIXME: should only count parameters that are lowered to integers.
5345 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5347 if (InRegCount > 2) {
5348 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5354 case CallingConv::X86_FastCall:
5355 // Pass 'nest' parameter in EAX.
5356 // Must be kept in sync with X86CallingConv.td
5361 SDOperand OutChains[4];
5362 SDOperand Addr, Disp;
5364 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5365 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5367 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5368 const unsigned char N86Reg =
5369 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5370 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5373 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5374 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5376 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5377 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5378 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5379 TrmpAddr, 5, false, 1);
5381 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5382 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5385 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5386 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5390 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5392 The rounding mode is in bits 11:10 of FPSR, and has the following
5399 FLT_ROUNDS, on the other hand, expects the following:
5406 To perform the conversion, we do:
5407 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5410 MachineFunction &MF = DAG.getMachineFunction();
5411 const TargetMachine &TM = MF.getTarget();
5412 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5413 unsigned StackAlignment = TFI.getStackAlignment();
5414 MVT::ValueType VT = Op.getValueType();
5416 // Save FP Control Word to stack slot
5417 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5418 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5420 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5421 DAG.getEntryNode(), StackSlot);
5423 // Load FP Control Word from stack slot
5424 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5426 // Transform as necessary
5428 DAG.getNode(ISD::SRL, MVT::i16,
5429 DAG.getNode(ISD::AND, MVT::i16,
5430 CWD, DAG.getConstant(0x800, MVT::i16)),
5431 DAG.getConstant(11, MVT::i8));
5433 DAG.getNode(ISD::SRL, MVT::i16,
5434 DAG.getNode(ISD::AND, MVT::i16,
5435 CWD, DAG.getConstant(0x400, MVT::i16)),
5436 DAG.getConstant(9, MVT::i8));
5439 DAG.getNode(ISD::AND, MVT::i16,
5440 DAG.getNode(ISD::ADD, MVT::i16,
5441 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5442 DAG.getConstant(1, MVT::i16)),
5443 DAG.getConstant(3, MVT::i16));
5446 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5447 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5450 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5451 MVT::ValueType VT = Op.getValueType();
5452 MVT::ValueType OpVT = VT;
5453 unsigned NumBits = MVT::getSizeInBits(VT);
5455 Op = Op.getOperand(0);
5456 if (VT == MVT::i8) {
5457 // Zero extend to i32 since there is not an i8 bsr.
5459 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5462 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5463 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5464 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5466 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5467 SmallVector<SDOperand, 4> Ops;
5469 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5470 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5471 Ops.push_back(Op.getValue(1));
5472 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5474 // Finally xor with NumBits-1.
5475 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5478 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5482 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5483 MVT::ValueType VT = Op.getValueType();
5484 MVT::ValueType OpVT = VT;
5485 unsigned NumBits = MVT::getSizeInBits(VT);
5487 Op = Op.getOperand(0);
5488 if (VT == MVT::i8) {
5490 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5493 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5494 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5495 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5497 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5498 SmallVector<SDOperand, 4> Ops;
5500 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5501 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5502 Ops.push_back(Op.getValue(1));
5503 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5506 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5510 SDOperand X86TargetLowering::LowerLCS(SDOperand Op, SelectionDAG &DAG) {
5511 MVT::ValueType T = cast<AtomicSDNode>(Op.Val)->getVT();
5515 case MVT::i8: Reg = X86::AL; size = 1; break;
5516 case MVT::i16: Reg = X86::AX; size = 2; break;
5517 case MVT::i32: Reg = X86::EAX; size = 4; break;
5519 if (Subtarget->is64Bit()) {
5520 Reg = X86::RAX; size = 8;
5521 } else //Should go away when LowerType stuff lands
5522 return SDOperand(ExpandATOMIC_LCS(Op.Val, DAG), 0);
5525 SDOperand cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5526 Op.getOperand(3), SDOperand());
5527 SDOperand Ops[] = { cpIn.getValue(0),
5530 DAG.getTargetConstant(size, MVT::i8),
5532 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5533 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5535 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5539 SDNode* X86TargetLowering::ExpandATOMIC_LCS(SDNode* Op, SelectionDAG &DAG) {
5540 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5541 assert (T == MVT::i64 && "Only know how to expand i64 CAS");
5542 SDOperand cpInL, cpInH;
5543 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5544 DAG.getConstant(0, MVT::i32));
5545 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5546 DAG.getConstant(1, MVT::i32));
5547 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5548 cpInL, SDOperand());
5549 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5550 cpInH, cpInL.getValue(1));
5551 SDOperand swapInL, swapInH;
5552 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5553 DAG.getConstant(0, MVT::i32));
5554 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5555 DAG.getConstant(1, MVT::i32));
5556 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5557 swapInL, cpInH.getValue(1));
5558 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5559 swapInH, swapInL.getValue(1));
5560 SDOperand Ops[] = { swapInH.getValue(0),
5562 swapInH.getValue(1)};
5563 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5564 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5565 SDOperand cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5566 Result.getValue(1));
5567 SDOperand cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5568 cpOutL.getValue(2));
5569 SDOperand OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5570 SDOperand ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5571 Tys = DAG.getVTList(MVT::i64, MVT::Other);
5572 return DAG.getNode(ISD::MERGE_VALUES, Tys, ResultVal, cpOutH.getValue(1)).Val;
5575 SDNode* X86TargetLowering::ExpandATOMIC_LSS(SDNode* Op, SelectionDAG &DAG) {
5576 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5577 assert (T == MVT::i32 && "Only know how to expand i32 LSS");
5578 SDOperand negOp = DAG.getNode(ISD::SUB, T,
5579 DAG.getConstant(0, T), Op->getOperand(2));
5580 return DAG.getAtomic(ISD::ATOMIC_LAS, Op->getOperand(0),
5581 Op->getOperand(1), negOp, T).Val;
5584 /// LowerOperation - Provide custom lowering hooks for some operations.
5586 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5587 switch (Op.getOpcode()) {
5588 default: assert(0 && "Should not custom lower this!");
5589 case ISD::ATOMIC_LCS: return LowerLCS(Op,DAG);
5590 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5591 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5592 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5593 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5594 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5595 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5596 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5597 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5598 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5599 case ISD::SHL_PARTS:
5600 case ISD::SRA_PARTS:
5601 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5602 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5603 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5604 case ISD::FABS: return LowerFABS(Op, DAG);
5605 case ISD::FNEG: return LowerFNEG(Op, DAG);
5606 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5607 case ISD::SETCC: return LowerSETCC(Op, DAG);
5608 case ISD::SELECT: return LowerSELECT(Op, DAG);
5609 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5610 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5611 case ISD::CALL: return LowerCALL(Op, DAG);
5612 case ISD::RET: return LowerRET(Op, DAG);
5613 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5614 case ISD::VASTART: return LowerVASTART(Op, DAG);
5615 case ISD::VAARG: return LowerVAARG(Op, DAG);
5616 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5617 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5618 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5619 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5620 case ISD::FRAME_TO_ARGS_OFFSET:
5621 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5622 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5623 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5624 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5625 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5626 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5627 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5629 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5630 case ISD::READCYCLECOUNTER:
5631 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5635 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5636 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5637 switch (N->getOpcode()) {
5638 default: assert(0 && "Should not custom lower this!");
5639 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5640 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5641 case ISD::ATOMIC_LCS: return ExpandATOMIC_LCS(N, DAG);
5642 case ISD::ATOMIC_LSS: return ExpandATOMIC_LSS(N,DAG);
5646 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5648 default: return NULL;
5649 case X86ISD::BSF: return "X86ISD::BSF";
5650 case X86ISD::BSR: return "X86ISD::BSR";
5651 case X86ISD::SHLD: return "X86ISD::SHLD";
5652 case X86ISD::SHRD: return "X86ISD::SHRD";
5653 case X86ISD::FAND: return "X86ISD::FAND";
5654 case X86ISD::FOR: return "X86ISD::FOR";
5655 case X86ISD::FXOR: return "X86ISD::FXOR";
5656 case X86ISD::FSRL: return "X86ISD::FSRL";
5657 case X86ISD::FILD: return "X86ISD::FILD";
5658 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5659 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5660 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5661 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5662 case X86ISD::FLD: return "X86ISD::FLD";
5663 case X86ISD::FST: return "X86ISD::FST";
5664 case X86ISD::CALL: return "X86ISD::CALL";
5665 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5666 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5667 case X86ISD::CMP: return "X86ISD::CMP";
5668 case X86ISD::COMI: return "X86ISD::COMI";
5669 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5670 case X86ISD::SETCC: return "X86ISD::SETCC";
5671 case X86ISD::CMOV: return "X86ISD::CMOV";
5672 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5673 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5674 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5675 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5676 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5677 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5678 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5679 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5680 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5681 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5682 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5683 case X86ISD::FMAX: return "X86ISD::FMAX";
5684 case X86ISD::FMIN: return "X86ISD::FMIN";
5685 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5686 case X86ISD::FRCP: return "X86ISD::FRCP";
5687 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5688 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5689 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5690 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5691 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5692 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
5693 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
5694 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
5695 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
5699 // isLegalAddressingMode - Return true if the addressing mode represented
5700 // by AM is legal for this target, for a load/store of the specified type.
5701 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5702 const Type *Ty) const {
5703 // X86 supports extremely general addressing modes.
5705 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5706 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5710 // We can only fold this if we don't need an extra load.
5711 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5714 // X86-64 only supports addr of globals in small code model.
5715 if (Subtarget->is64Bit()) {
5716 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5718 // If lower 4G is not available, then we must use rip-relative addressing.
5719 if (AM.BaseOffs || AM.Scale > 1)
5730 // These scales always work.
5735 // These scales are formed with basereg+scalereg. Only accept if there is
5740 default: // Other stuff never works.
5748 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5749 if (!Ty1->isInteger() || !Ty2->isInteger())
5751 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5752 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5753 if (NumBits1 <= NumBits2)
5755 return Subtarget->is64Bit() || NumBits1 < 64;
5758 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5759 MVT::ValueType VT2) const {
5760 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5762 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5763 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5764 if (NumBits1 <= NumBits2)
5766 return Subtarget->is64Bit() || NumBits1 < 64;
5769 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5770 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5771 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5772 /// are assumed to be legal.
5774 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5775 // Only do shuffles on 128-bit vector types for now.
5776 if (MVT::getSizeInBits(VT) == 64) return false;
5777 return (Mask.Val->getNumOperands() <= 4 ||
5778 isIdentityMask(Mask.Val) ||
5779 isIdentityMask(Mask.Val, true) ||
5780 isSplatMask(Mask.Val) ||
5781 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5782 X86::isUNPCKLMask(Mask.Val) ||
5783 X86::isUNPCKHMask(Mask.Val) ||
5784 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5785 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5789 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDOperand> &BVOps,
5791 SelectionDAG &DAG) const {
5792 unsigned NumElts = BVOps.size();
5793 // Only do shuffles on 128-bit vector types for now.
5794 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5795 if (NumElts == 2) return true;
5797 return (isMOVLMask(&BVOps[0], 4) ||
5798 isCommutedMOVL(&BVOps[0], 4, true) ||
5799 isSHUFPMask(&BVOps[0], 4) ||
5800 isCommutedSHUFP(&BVOps[0], 4));
5805 //===----------------------------------------------------------------------===//
5806 // X86 Scheduler Hooks
5807 //===----------------------------------------------------------------------===//
5809 // private utility function
5811 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
5812 MachineBasicBlock *MBB,
5815 // For the atomic bitwise operator, we generate
5818 // ld t1 = [bitinstr.addr]
5819 // op t2 = t1, [bitinstr.val]
5821 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
5823 // fallthrough -->nextMBB
5824 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5825 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
5826 ilist<MachineBasicBlock>::iterator MBBIter = MBB;
5829 /// First build the CFG
5830 MachineFunction *F = MBB->getParent();
5831 MachineBasicBlock *thisMBB = MBB;
5832 MachineBasicBlock *newMBB = new MachineBasicBlock(LLVM_BB);
5833 MachineBasicBlock *nextMBB = new MachineBasicBlock(LLVM_BB);
5834 F->getBasicBlockList().insert(MBBIter, newMBB);
5835 F->getBasicBlockList().insert(MBBIter, nextMBB);
5837 // Move all successors to thisMBB to nextMBB
5838 nextMBB->transferSuccessors(thisMBB);
5840 // Update thisMBB to fall through to newMBB
5841 thisMBB->addSuccessor(newMBB);
5843 // newMBB jumps to itself and fall through to nextMBB
5844 newMBB->addSuccessor(nextMBB);
5845 newMBB->addSuccessor(newMBB);
5847 // Insert instructions into newMBB based on incoming instruction
5848 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
5849 MachineOperand& destOper = bInstr->getOperand(0);
5850 MachineOperand* argOpers[6];
5851 int numArgs = bInstr->getNumOperands() - 1;
5852 for (int i=0; i < numArgs; ++i)
5853 argOpers[i] = &bInstr->getOperand(i+1);
5855 // x86 address has 4 operands: base, index, scale, and displacement
5856 int lastAddrIndx = 3; // [0,3]
5859 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5860 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
5861 for (int i=0; i <= lastAddrIndx; ++i)
5862 (*MIB).addOperand(*argOpers[i]);
5864 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5865 assert( (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
5866 && "invalid operand");
5867 if (argOpers[valArgIndx]->isReg())
5868 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
5870 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
5872 (*MIB).addOperand(*argOpers[valArgIndx]);
5874 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
5877 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
5878 for (int i=0; i <= lastAddrIndx; ++i)
5879 (*MIB).addOperand(*argOpers[i]);
5882 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
5883 MIB.addReg(X86::EAX);
5886 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
5888 delete bInstr; // The pseudo instruction is gone now.
5892 // private utility function
5894 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
5895 MachineBasicBlock *MBB,
5897 // For the atomic min/max operator, we generate
5900 // ld t1 = [min/max.addr]
5901 // mov t2 = [min/max.val]
5903 // cmov[cond] t2 = t1
5905 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
5907 // fallthrough -->nextMBB
5909 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5910 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
5911 ilist<MachineBasicBlock>::iterator MBBIter = MBB;
5914 /// First build the CFG
5915 MachineFunction *F = MBB->getParent();
5916 MachineBasicBlock *thisMBB = MBB;
5917 MachineBasicBlock *newMBB = new MachineBasicBlock(LLVM_BB);
5918 MachineBasicBlock *nextMBB = new MachineBasicBlock(LLVM_BB);
5919 F->getBasicBlockList().insert(MBBIter, newMBB);
5920 F->getBasicBlockList().insert(MBBIter, nextMBB);
5922 // Move all successors to thisMBB to nextMBB
5923 nextMBB->transferSuccessors(thisMBB);
5925 // Update thisMBB to fall through to newMBB
5926 thisMBB->addSuccessor(newMBB);
5928 // newMBB jumps to newMBB and fall through to nextMBB
5929 newMBB->addSuccessor(nextMBB);
5930 newMBB->addSuccessor(newMBB);
5932 // Insert instructions into newMBB based on incoming instruction
5933 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
5934 MachineOperand& destOper = mInstr->getOperand(0);
5935 MachineOperand* argOpers[6];
5936 int numArgs = mInstr->getNumOperands() - 1;
5937 for (int i=0; i < numArgs; ++i)
5938 argOpers[i] = &mInstr->getOperand(i+1);
5940 // x86 address has 4 operands: base, index, scale, and displacement
5941 int lastAddrIndx = 3; // [0,3]
5944 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5945 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
5946 for (int i=0; i <= lastAddrIndx; ++i)
5947 (*MIB).addOperand(*argOpers[i]);
5949 // We only support register and immediate values
5950 assert( (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
5951 && "invalid operand");
5953 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5954 if (argOpers[valArgIndx]->isReg())
5955 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
5957 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
5958 (*MIB).addOperand(*argOpers[valArgIndx]);
5960 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
5963 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
5968 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5969 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
5973 // Cmp and exchange if none has modified the memory location
5974 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
5975 for (int i=0; i <= lastAddrIndx; ++i)
5976 (*MIB).addOperand(*argOpers[i]);
5979 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
5980 MIB.addReg(X86::EAX);
5983 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
5985 delete mInstr; // The pseudo instruction is gone now.
5991 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5992 MachineBasicBlock *BB) {
5993 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5994 switch (MI->getOpcode()) {
5995 default: assert(false && "Unexpected instr type to insert");
5996 case X86::CMOV_FR32:
5997 case X86::CMOV_FR64:
5998 case X86::CMOV_V4F32:
5999 case X86::CMOV_V2F64:
6000 case X86::CMOV_V2I64: {
6001 // To "insert" a SELECT_CC instruction, we actually have to insert the
6002 // diamond control-flow pattern. The incoming instruction knows the
6003 // destination vreg to set, the condition code register to branch on, the
6004 // true/false values to select between, and a branch opcode to use.
6005 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6006 ilist<MachineBasicBlock>::iterator It = BB;
6012 // cmpTY ccX, r1, r2
6014 // fallthrough --> copy0MBB
6015 MachineBasicBlock *thisMBB = BB;
6016 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
6017 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
6019 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6020 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6021 MachineFunction *F = BB->getParent();
6022 F->getBasicBlockList().insert(It, copy0MBB);
6023 F->getBasicBlockList().insert(It, sinkMBB);
6024 // Update machine-CFG edges by transferring all successors of the current
6025 // block to the new block which will contain the Phi node for the select.
6026 sinkMBB->transferSuccessors(BB);
6028 // Add the true and fallthrough blocks as its successors.
6029 BB->addSuccessor(copy0MBB);
6030 BB->addSuccessor(sinkMBB);
6033 // %FalseValue = ...
6034 // # fallthrough to sinkMBB
6037 // Update machine-CFG edges
6038 BB->addSuccessor(sinkMBB);
6041 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6044 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6045 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6046 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6048 delete MI; // The pseudo instruction is gone now.
6052 case X86::FP32_TO_INT16_IN_MEM:
6053 case X86::FP32_TO_INT32_IN_MEM:
6054 case X86::FP32_TO_INT64_IN_MEM:
6055 case X86::FP64_TO_INT16_IN_MEM:
6056 case X86::FP64_TO_INT32_IN_MEM:
6057 case X86::FP64_TO_INT64_IN_MEM:
6058 case X86::FP80_TO_INT16_IN_MEM:
6059 case X86::FP80_TO_INT32_IN_MEM:
6060 case X86::FP80_TO_INT64_IN_MEM: {
6061 // Change the floating point control register to use "round towards zero"
6062 // mode when truncating to an integer value.
6063 MachineFunction *F = BB->getParent();
6064 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6065 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6067 // Load the old value of the high byte of the control word...
6069 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6070 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6072 // Set the high part to be round to zero...
6073 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6076 // Reload the modified control word now...
6077 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6079 // Restore the memory image of control word to original value
6080 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6083 // Get the X86 opcode to use.
6085 switch (MI->getOpcode()) {
6086 default: assert(0 && "illegal opcode!");
6087 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6088 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6089 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6090 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6091 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6092 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6093 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6094 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6095 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6099 MachineOperand &Op = MI->getOperand(0);
6100 if (Op.isRegister()) {
6101 AM.BaseType = X86AddressMode::RegBase;
6102 AM.Base.Reg = Op.getReg();
6104 AM.BaseType = X86AddressMode::FrameIndexBase;
6105 AM.Base.FrameIndex = Op.getIndex();
6107 Op = MI->getOperand(1);
6108 if (Op.isImmediate())
6109 AM.Scale = Op.getImm();
6110 Op = MI->getOperand(2);
6111 if (Op.isImmediate())
6112 AM.IndexReg = Op.getImm();
6113 Op = MI->getOperand(3);
6114 if (Op.isGlobalAddress()) {
6115 AM.GV = Op.getGlobal();
6117 AM.Disp = Op.getImm();
6119 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6120 .addReg(MI->getOperand(4).getReg());
6122 // Reload the original control word now.
6123 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6125 delete MI; // The pseudo instruction is gone now.
6128 case X86::ATOMAND32:
6129 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6132 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
6134 case X86::ATOMXOR32:
6135 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
6137 case X86::ATOMMIN32:
6138 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
6139 case X86::ATOMMAX32:
6140 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
6141 case X86::ATOMUMIN32:
6142 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
6143 case X86::ATOMUMAX32:
6144 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
6148 //===----------------------------------------------------------------------===//
6149 // X86 Optimization Hooks
6150 //===----------------------------------------------------------------------===//
6152 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
6156 const SelectionDAG &DAG,
6157 unsigned Depth) const {
6158 unsigned Opc = Op.getOpcode();
6159 assert((Opc >= ISD::BUILTIN_OP_END ||
6160 Opc == ISD::INTRINSIC_WO_CHAIN ||
6161 Opc == ISD::INTRINSIC_W_CHAIN ||
6162 Opc == ISD::INTRINSIC_VOID) &&
6163 "Should use MaskedValueIsZero if you don't know whether Op"
6164 " is a target node!");
6166 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
6170 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
6171 Mask.getBitWidth() - 1);
6176 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
6177 /// element of the result of the vector shuffle.
6178 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
6179 MVT::ValueType VT = N->getValueType(0);
6180 SDOperand PermMask = N->getOperand(2);
6181 unsigned NumElems = PermMask.getNumOperands();
6182 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
6184 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6186 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
6187 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
6188 SDOperand Idx = PermMask.getOperand(i);
6189 if (Idx.getOpcode() == ISD::UNDEF)
6190 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
6191 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
6196 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
6197 /// node is a GlobalAddress + offset.
6198 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
6199 GlobalValue* &GA, int64_t &Offset) const{
6200 if (N->getOpcode() == X86ISD::Wrapper) {
6201 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
6202 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
6206 return TargetLowering::isGAPlusOffset(N, GA, Offset);
6209 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
6210 const TargetLowering &TLI) {
6213 if (TLI.isGAPlusOffset(Base, GV, Offset))
6214 return (GV->getAlignment() >= N && (Offset % N) == 0);
6215 // DAG combine handles the stack object case.
6219 static bool EltsFromConsecutiveLoads(SDNode *N, SDOperand PermMask,
6220 unsigned NumElems, MVT::ValueType EVT,
6222 SelectionDAG &DAG, MachineFrameInfo *MFI,
6223 const TargetLowering &TLI) {
6225 for (unsigned i = 0; i < NumElems; ++i) {
6226 SDOperand Idx = PermMask.getOperand(i);
6227 if (Idx.getOpcode() == ISD::UNDEF) {
6233 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
6234 SDOperand Elt = getShuffleScalarElt(N, Index, DAG);
6236 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.Val)))
6240 if (Base->getOpcode() == ISD::UNDEF)
6244 if (Elt.getOpcode() == ISD::UNDEF)
6247 if (!TLI.isConsecutiveLoad(Elt.Val, Base,
6248 MVT::getSizeInBits(EVT)/8, i, MFI))
6254 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6255 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6256 /// if the load addresses are consecutive, non-overlapping, and in the right
6258 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6259 const TargetLowering &TLI) {
6260 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6261 MVT::ValueType VT = N->getValueType(0);
6262 MVT::ValueType EVT = MVT::getVectorElementType(VT);
6263 SDOperand PermMask = N->getOperand(2);
6264 unsigned NumElems = PermMask.getNumOperands();
6265 SDNode *Base = NULL;
6266 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
6270 LoadSDNode *LD = cast<LoadSDNode>(Base);
6271 if (isBaseAlignmentOfN(16, Base->getOperand(1).Val, TLI))
6272 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6273 LD->getSrcValueOffset(), LD->isVolatile());
6274 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6275 LD->getSrcValueOffset(), LD->isVolatile(),
6276 LD->getAlignment());
6279 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6280 SDOperand Elt = N->getOperand(i);
6281 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6283 return Elt.getOperand(Elt.ResNo).Val;
6286 static SDOperand PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
6287 const X86Subtarget *Subtarget,
6288 const TargetLowering &TLI) {
6289 // Ignore single operand BUILD_VECTOR.
6290 if (N->getNumOperands() == 1)
6293 MVT::ValueType VT = N->getValueType(0);
6294 MVT::ValueType EVT = MVT::getVectorElementType(VT);
6295 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
6296 // We are looking for load i64 and zero extend. We want to transform
6297 // it before legalizer has a chance to expand it. Also look for i64
6298 // BUILD_PAIR bit casted to f64.
6300 // This must be an insertion into a zero vector.
6301 SDOperand HighElt = N->getOperand(1);
6302 if (!isZeroNode(HighElt))
6305 // Value must be a load.
6306 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6307 SDNode *Base = N->getOperand(0).Val;
6308 if (!isa<LoadSDNode>(Base)) {
6309 if (Base->getOpcode() == ISD::BIT_CONVERT)
6310 Base = Base->getOperand(0).Val;
6311 if (Base->getOpcode() != ISD::BUILD_PAIR)
6313 SDNode *Pair = Base;
6314 Base = getBuildPairElt(Pair, 0);
6315 if (!ISD::isNON_EXTLoad(Base))
6317 SDNode *NextLD = getBuildPairElt(Pair, 1);
6318 if (!ISD::isNON_EXTLoad(NextLD) ||
6319 !TLI.isConsecutiveLoad(NextLD, Base, 4/*32 bits*/, 1, MFI))
6322 LoadSDNode *LD = cast<LoadSDNode>(Base);
6324 // Transform it into VZEXT_LOAD addr.
6325 return DAG.getNode(X86ISD::VZEXT_LOAD, VT, LD->getChain(), LD->getBasePtr());
6328 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6329 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6330 const X86Subtarget *Subtarget) {
6331 SDOperand Cond = N->getOperand(0);
6333 // If we have SSE[12] support, try to form min/max nodes.
6334 if (Subtarget->hasSSE2() &&
6335 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6336 if (Cond.getOpcode() == ISD::SETCC) {
6337 // Get the LHS/RHS of the select.
6338 SDOperand LHS = N->getOperand(1);
6339 SDOperand RHS = N->getOperand(2);
6340 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6342 unsigned Opcode = 0;
6343 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6346 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6349 if (!UnsafeFPMath) break;
6351 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6353 Opcode = X86ISD::FMIN;
6356 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6359 if (!UnsafeFPMath) break;
6361 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6363 Opcode = X86ISD::FMAX;
6366 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6369 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6372 if (!UnsafeFPMath) break;
6374 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6376 Opcode = X86ISD::FMIN;
6379 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6382 if (!UnsafeFPMath) break;
6384 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6386 Opcode = X86ISD::FMAX;
6392 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6400 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6401 static SDOperand PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
6402 const X86Subtarget *Subtarget) {
6403 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
6404 // the FP state in cases where an emms may be missing.
6405 // A preferable solution to the general problem is to figure out the right
6406 // places to insert EMMS. This qualifies as a quick hack.
6407 StoreSDNode *St = cast<StoreSDNode>(N);
6408 if (MVT::isVector(St->getValue().getValueType()) &&
6409 MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
6410 isa<LoadSDNode>(St->getValue()) &&
6411 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6412 St->getChain().hasOneUse() && !St->isVolatile()) {
6413 SDNode* LdVal = St->getValue().Val;
6415 int TokenFactorIndex = -1;
6416 SmallVector<SDOperand, 8> Ops;
6417 SDNode* ChainVal = St->getChain().Val;
6418 // Must be a store of a load. We currently handle two cases: the load
6419 // is a direct child, and it's under an intervening TokenFactor. It is
6420 // possible to dig deeper under nested TokenFactors.
6421 if (ChainVal == LdVal)
6422 Ld = cast<LoadSDNode>(St->getChain());
6423 else if (St->getValue().hasOneUse() &&
6424 ChainVal->getOpcode() == ISD::TokenFactor) {
6425 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6426 if (ChainVal->getOperand(i).Val == LdVal) {
6427 TokenFactorIndex = i;
6428 Ld = cast<LoadSDNode>(St->getValue());
6430 Ops.push_back(ChainVal->getOperand(i));
6434 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6435 if (Subtarget->is64Bit()) {
6436 SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6437 Ld->getBasePtr(), Ld->getSrcValue(),
6438 Ld->getSrcValueOffset(), Ld->isVolatile(),
6439 Ld->getAlignment());
6440 SDOperand NewChain = NewLd.getValue(1);
6441 if (TokenFactorIndex != -1) {
6442 Ops.push_back(NewChain);
6443 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6446 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6447 St->getSrcValue(), St->getSrcValueOffset(),
6448 St->isVolatile(), St->getAlignment());
6451 // Otherwise, lower to two 32-bit copies.
6452 SDOperand LoAddr = Ld->getBasePtr();
6453 SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6454 DAG.getConstant(MVT::i32, 4));
6456 SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6457 Ld->getSrcValue(), Ld->getSrcValueOffset(),
6458 Ld->isVolatile(), Ld->getAlignment());
6459 SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6460 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6462 MinAlign(Ld->getAlignment(), 4));
6464 SDOperand NewChain = LoLd.getValue(1);
6465 if (TokenFactorIndex != -1) {
6466 Ops.push_back(LoLd);
6467 Ops.push_back(HiLd);
6468 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6472 LoAddr = St->getBasePtr();
6473 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6474 DAG.getConstant(MVT::i32, 4));
6476 SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6477 St->getSrcValue(), St->getSrcValueOffset(),
6478 St->isVolatile(), St->getAlignment());
6479 SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6480 St->getSrcValue(), St->getSrcValueOffset()+4,
6482 MinAlign(St->getAlignment(), 4));
6483 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6489 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6490 /// X86ISD::FXOR nodes.
6491 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6492 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6493 // F[X]OR(0.0, x) -> x
6494 // F[X]OR(x, 0.0) -> x
6495 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6496 if (C->getValueAPF().isPosZero())
6497 return N->getOperand(1);
6498 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6499 if (C->getValueAPF().isPosZero())
6500 return N->getOperand(0);
6504 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6505 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6506 // FAND(0.0, x) -> 0.0
6507 // FAND(x, 0.0) -> 0.0
6508 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6509 if (C->getValueAPF().isPosZero())
6510 return N->getOperand(0);
6511 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6512 if (C->getValueAPF().isPosZero())
6513 return N->getOperand(1);
6518 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6519 DAGCombinerInfo &DCI) const {
6520 SelectionDAG &DAG = DCI.DAG;
6521 switch (N->getOpcode()) {
6523 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
6524 case ISD::BUILD_VECTOR:
6525 return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
6526 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6527 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
6529 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6530 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6536 //===----------------------------------------------------------------------===//
6537 // X86 Inline Assembly Support
6538 //===----------------------------------------------------------------------===//
6540 /// getConstraintType - Given a constraint letter, return the type of
6541 /// constraint it is for this target.
6542 X86TargetLowering::ConstraintType
6543 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6544 if (Constraint.size() == 1) {
6545 switch (Constraint[0]) {
6556 return C_RegisterClass;
6561 return TargetLowering::getConstraintType(Constraint);
6564 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6565 /// with another that has more specific requirements based on the type of the
6566 /// corresponding operand.
6567 const char *X86TargetLowering::
6568 LowerXConstraint(MVT::ValueType ConstraintVT) const {
6569 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
6570 // 'f' like normal targets.
6571 if (MVT::isFloatingPoint(ConstraintVT)) {
6572 if (Subtarget->hasSSE2())
6574 if (Subtarget->hasSSE1())
6578 return TargetLowering::LowerXConstraint(ConstraintVT);
6581 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6582 /// vector. If it is invalid, don't add anything to Ops.
6583 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6585 std::vector<SDOperand>&Ops,
6586 SelectionDAG &DAG) const {
6587 SDOperand Result(0, 0);
6589 switch (Constraint) {
6592 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6593 if (C->getValue() <= 31) {
6594 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6600 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6601 if (C->getValue() <= 255) {
6602 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6608 // Literal immediates are always ok.
6609 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6610 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6614 // If we are in non-pic codegen mode, we allow the address of a global (with
6615 // an optional displacement) to be used with 'i'.
6616 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6619 // Match either (GA) or (GA+C)
6621 Offset = GA->getOffset();
6622 } else if (Op.getOpcode() == ISD::ADD) {
6623 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6624 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6626 Offset = GA->getOffset()+C->getValue();
6628 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6629 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6631 Offset = GA->getOffset()+C->getValue();
6638 // If addressing this global requires a load (e.g. in PIC mode), we can't
6640 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6644 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6650 // Otherwise, not valid for this mode.
6656 Ops.push_back(Result);
6659 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6662 std::vector<unsigned> X86TargetLowering::
6663 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6664 MVT::ValueType VT) const {
6665 if (Constraint.size() == 1) {
6666 // FIXME: not handling fp-stack yet!
6667 switch (Constraint[0]) { // GCC X86 Constraint Letters
6668 default: break; // Unknown constraint letter
6669 case 'A': // EAX/EDX
6670 if (VT == MVT::i32 || VT == MVT::i64)
6671 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6673 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6676 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6677 else if (VT == MVT::i16)
6678 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6679 else if (VT == MVT::i8)
6680 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6681 else if (VT == MVT::i64)
6682 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6687 return std::vector<unsigned>();
6690 std::pair<unsigned, const TargetRegisterClass*>
6691 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6692 MVT::ValueType VT) const {
6693 // First, see if this is a constraint that directly corresponds to an LLVM
6695 if (Constraint.size() == 1) {
6696 // GCC Constraint Letters
6697 switch (Constraint[0]) {
6699 case 'r': // GENERAL_REGS
6700 case 'R': // LEGACY_REGS
6701 case 'l': // INDEX_REGS
6702 if (VT == MVT::i64 && Subtarget->is64Bit())
6703 return std::make_pair(0U, X86::GR64RegisterClass);
6705 return std::make_pair(0U, X86::GR32RegisterClass);
6706 else if (VT == MVT::i16)
6707 return std::make_pair(0U, X86::GR16RegisterClass);
6708 else if (VT == MVT::i8)
6709 return std::make_pair(0U, X86::GR8RegisterClass);
6711 case 'f': // FP Stack registers.
6712 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
6713 // value to the correct fpstack register class.
6714 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
6715 return std::make_pair(0U, X86::RFP32RegisterClass);
6716 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
6717 return std::make_pair(0U, X86::RFP64RegisterClass);
6718 return std::make_pair(0U, X86::RFP80RegisterClass);
6719 case 'y': // MMX_REGS if MMX allowed.
6720 if (!Subtarget->hasMMX()) break;
6721 return std::make_pair(0U, X86::VR64RegisterClass);
6723 case 'Y': // SSE_REGS if SSE2 allowed
6724 if (!Subtarget->hasSSE2()) break;
6726 case 'x': // SSE_REGS if SSE1 allowed
6727 if (!Subtarget->hasSSE1()) break;
6731 // Scalar SSE types.
6734 return std::make_pair(0U, X86::FR32RegisterClass);
6737 return std::make_pair(0U, X86::FR64RegisterClass);
6745 return std::make_pair(0U, X86::VR128RegisterClass);
6751 // Use the default implementation in TargetLowering to convert the register
6752 // constraint into a member of a register class.
6753 std::pair<unsigned, const TargetRegisterClass*> Res;
6754 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6756 // Not found as a standard register?
6757 if (Res.second == 0) {
6758 // GCC calls "st(0)" just plain "st".
6759 if (StringsEqualNoCase("{st}", Constraint)) {
6760 Res.first = X86::ST0;
6761 Res.second = X86::RFP80RegisterClass;
6767 // Otherwise, check to see if this is a register class of the wrong value
6768 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6769 // turn into {ax},{dx}.
6770 if (Res.second->hasType(VT))
6771 return Res; // Correct type already, nothing to do.
6773 // All of the single-register GCC register classes map their values onto
6774 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6775 // really want an 8-bit or 32-bit register, map to the appropriate register
6776 // class and return the appropriate register.
6777 if (Res.second != X86::GR16RegisterClass)
6780 if (VT == MVT::i8) {
6781 unsigned DestReg = 0;
6782 switch (Res.first) {
6784 case X86::AX: DestReg = X86::AL; break;
6785 case X86::DX: DestReg = X86::DL; break;
6786 case X86::CX: DestReg = X86::CL; break;
6787 case X86::BX: DestReg = X86::BL; break;
6790 Res.first = DestReg;
6791 Res.second = Res.second = X86::GR8RegisterClass;
6793 } else if (VT == MVT::i32) {
6794 unsigned DestReg = 0;
6795 switch (Res.first) {
6797 case X86::AX: DestReg = X86::EAX; break;
6798 case X86::DX: DestReg = X86::EDX; break;
6799 case X86::CX: DestReg = X86::ECX; break;
6800 case X86::BX: DestReg = X86::EBX; break;
6801 case X86::SI: DestReg = X86::ESI; break;
6802 case X86::DI: DestReg = X86::EDI; break;
6803 case X86::BP: DestReg = X86::EBP; break;
6804 case X86::SP: DestReg = X86::ESP; break;
6807 Res.first = DestReg;
6808 Res.second = Res.second = X86::GR32RegisterClass;
6810 } else if (VT == MVT::i64) {
6811 unsigned DestReg = 0;
6812 switch (Res.first) {
6814 case X86::AX: DestReg = X86::RAX; break;
6815 case X86::DX: DestReg = X86::RDX; break;
6816 case X86::CX: DestReg = X86::RCX; break;
6817 case X86::BX: DestReg = X86::RBX; break;
6818 case X86::SI: DestReg = X86::RSI; break;
6819 case X86::DI: DestReg = X86::RDI; break;
6820 case X86::BP: DestReg = X86::RBP; break;
6821 case X86::SP: DestReg = X86::RSP; break;
6824 Res.first = DestReg;
6825 Res.second = Res.second = X86::GR64RegisterClass;