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);
533 setOperationAction(ISD::VSETCC, (MVT::ValueType)VT, Expand);
536 if (Subtarget->hasMMX()) {
537 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
538 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
539 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
540 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
542 // FIXME: add MMX packed arithmetics
544 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
545 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
546 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
547 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
549 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
550 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
551 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
552 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
554 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
555 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
557 setOperationAction(ISD::AND, MVT::v8i8, Promote);
558 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
559 setOperationAction(ISD::AND, MVT::v4i16, Promote);
560 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
561 setOperationAction(ISD::AND, MVT::v2i32, Promote);
562 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
563 setOperationAction(ISD::AND, MVT::v1i64, Legal);
565 setOperationAction(ISD::OR, MVT::v8i8, Promote);
566 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
567 setOperationAction(ISD::OR, MVT::v4i16, Promote);
568 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
569 setOperationAction(ISD::OR, MVT::v2i32, Promote);
570 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
571 setOperationAction(ISD::OR, MVT::v1i64, Legal);
573 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
574 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
575 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
576 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
577 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
578 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
579 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
581 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
582 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
583 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
584 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
585 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
586 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
587 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
589 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
590 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
591 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
592 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
594 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
595 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
596 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
597 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
599 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
600 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
601 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
604 if (Subtarget->hasSSE1()) {
605 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
607 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
608 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
609 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
610 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
611 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
612 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
613 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
614 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
615 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
616 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
617 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
618 setOperationAction(ISD::VSETCC, MVT::v4f32, Legal);
621 if (Subtarget->hasSSE2()) {
622 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
623 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
624 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
625 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
626 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
628 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
629 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
630 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
631 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
632 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
633 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
634 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
635 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
636 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
637 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
638 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
639 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
640 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
641 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
642 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
644 setOperationAction(ISD::VSETCC, MVT::v2f64, Legal);
645 setOperationAction(ISD::VSETCC, MVT::v16i8, Legal);
646 setOperationAction(ISD::VSETCC, MVT::v8i16, Legal);
647 setOperationAction(ISD::VSETCC, MVT::v4i32, Legal);
648 setOperationAction(ISD::VSETCC, MVT::v2i64, Legal);
650 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
651 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
652 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
653 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
654 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
656 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
657 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
658 // Do not attempt to custom lower non-power-of-2 vectors
659 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
661 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
662 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
663 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
665 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
666 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
667 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
668 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
669 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
670 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
671 if (Subtarget->is64Bit()) {
672 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
673 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
676 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
677 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
678 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
679 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
680 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
681 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
682 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
683 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
684 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
685 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
686 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
687 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
690 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
692 // Custom lower v2i64 and v2f64 selects.
693 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
694 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
695 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
696 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
700 if (Subtarget->hasSSE41()) {
701 // FIXME: Do we need to handle scalar-to-vector here?
702 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
704 // i8 and i16 vectors are custom , because the source register and source
705 // source memory operand types are not the same width. f32 vectors are
706 // custom since the immediate controlling the insert encodes additional
708 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
709 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
710 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
711 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
713 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
714 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
716 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
718 if (Subtarget->is64Bit()) {
719 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
720 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
724 // We want to custom lower some of our intrinsics.
725 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
727 // We have target-specific dag combine patterns for the following nodes:
728 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
729 setTargetDAGCombine(ISD::BUILD_VECTOR);
730 setTargetDAGCombine(ISD::SELECT);
731 setTargetDAGCombine(ISD::STORE);
733 computeRegisterProperties();
735 // FIXME: These should be based on subtarget info. Plus, the values should
736 // be smaller when we are in optimizing for size mode.
737 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
738 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
739 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
740 allowUnalignedMemoryAccesses = true; // x86 supports it!
741 setPrefLoopAlignment(16);
746 X86TargetLowering::getSetCCResultType(const SDOperand &) const {
751 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
752 /// the desired ByVal argument alignment.
753 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
756 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
757 if (VTy->getBitWidth() == 128)
759 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
760 unsigned EltAlign = 0;
761 getMaxByValAlign(ATy->getElementType(), EltAlign);
762 if (EltAlign > MaxAlign)
764 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
765 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
766 unsigned EltAlign = 0;
767 getMaxByValAlign(STy->getElementType(i), EltAlign);
768 if (EltAlign > MaxAlign)
777 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
778 /// function arguments in the caller parameter area. For X86, aggregates
779 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
780 /// are at 4-byte boundaries.
781 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
782 if (Subtarget->is64Bit())
783 return getTargetData()->getABITypeAlignment(Ty);
785 if (Subtarget->hasSSE1())
786 getMaxByValAlign(Ty, Align);
790 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
792 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
793 SelectionDAG &DAG) const {
794 if (usesGlobalOffsetTable())
795 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
796 if (!Subtarget->isPICStyleRIPRel())
797 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
801 //===----------------------------------------------------------------------===//
802 // Return Value Calling Convention Implementation
803 //===----------------------------------------------------------------------===//
805 #include "X86GenCallingConv.inc"
807 /// LowerRET - Lower an ISD::RET node.
808 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
809 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
811 SmallVector<CCValAssign, 16> RVLocs;
812 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
813 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
814 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
815 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
817 // If this is the first return lowered for this function, add the regs to the
818 // liveout set for the function.
819 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
820 for (unsigned i = 0; i != RVLocs.size(); ++i)
821 if (RVLocs[i].isRegLoc())
822 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
824 SDOperand Chain = Op.getOperand(0);
826 // Handle tail call return.
827 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
828 if (Chain.getOpcode() == X86ISD::TAILCALL) {
829 SDOperand TailCall = Chain;
830 SDOperand TargetAddress = TailCall.getOperand(1);
831 SDOperand StackAdjustment = TailCall.getOperand(2);
832 assert(((TargetAddress.getOpcode() == ISD::Register &&
833 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
834 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
835 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
836 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
837 "Expecting an global address, external symbol, or register");
838 assert(StackAdjustment.getOpcode() == ISD::Constant &&
839 "Expecting a const value");
841 SmallVector<SDOperand,8> Operands;
842 Operands.push_back(Chain.getOperand(0));
843 Operands.push_back(TargetAddress);
844 Operands.push_back(StackAdjustment);
845 // Copy registers used by the call. Last operand is a flag so it is not
847 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
848 Operands.push_back(Chain.getOperand(i));
850 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
857 SmallVector<SDOperand, 6> RetOps;
858 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
859 // Operand #1 = Bytes To Pop
860 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
862 // Copy the result values into the output registers.
863 for (unsigned i = 0; i != RVLocs.size(); ++i) {
864 CCValAssign &VA = RVLocs[i];
865 assert(VA.isRegLoc() && "Can only return in registers!");
866 SDOperand ValToCopy = Op.getOperand(i*2+1);
868 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
869 // the RET instruction and handled by the FP Stackifier.
870 if (RVLocs[i].getLocReg() == X86::ST0 ||
871 RVLocs[i].getLocReg() == X86::ST1) {
872 // If this is a copy from an xmm register to ST(0), use an FPExtend to
873 // change the value to the FP stack register class.
874 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
875 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
876 RetOps.push_back(ValToCopy);
877 // Don't emit a copytoreg.
881 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
882 Flag = Chain.getValue(1);
885 // The x86-64 ABI for returning structs by value requires that we copy
886 // the sret argument into %rax for the return. We saved the argument into
887 // a virtual register in the entry block, so now we copy the value out
889 if (Subtarget->is64Bit() &&
890 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
891 MachineFunction &MF = DAG.getMachineFunction();
892 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
893 unsigned Reg = FuncInfo->getSRetReturnReg();
895 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
896 FuncInfo->setSRetReturnReg(Reg);
898 SDOperand Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
900 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
901 Flag = Chain.getValue(1);
904 RetOps[0] = Chain; // Update chain.
906 // Add the flag if we have it.
908 RetOps.push_back(Flag);
910 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
914 /// LowerCallResult - Lower the result values of an ISD::CALL into the
915 /// appropriate copies out of appropriate physical registers. This assumes that
916 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
917 /// being lowered. The returns a SDNode with the same number of values as the
919 SDNode *X86TargetLowering::
920 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
921 unsigned CallingConv, SelectionDAG &DAG) {
923 // Assign locations to each value returned by this call.
924 SmallVector<CCValAssign, 16> RVLocs;
925 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
926 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
927 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
929 SmallVector<SDOperand, 8> ResultVals;
931 // Copy all of the result registers out of their specified physreg.
932 for (unsigned i = 0; i != RVLocs.size(); ++i) {
933 MVT::ValueType CopyVT = RVLocs[i].getValVT();
935 // If this is a call to a function that returns an fp value on the floating
936 // point stack, but where we prefer to use the value in xmm registers, copy
937 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
938 if (RVLocs[i].getLocReg() == X86::ST0 &&
939 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
943 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
944 CopyVT, InFlag).getValue(1);
945 SDOperand Val = Chain.getValue(0);
946 InFlag = Chain.getValue(2);
948 if (CopyVT != RVLocs[i].getValVT()) {
949 // Round the F80 the right size, which also moves to the appropriate xmm
951 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
952 // This truncation won't change the value.
953 DAG.getIntPtrConstant(1));
956 ResultVals.push_back(Val);
959 // Merge everything together with a MERGE_VALUES node.
960 ResultVals.push_back(Chain);
961 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
962 &ResultVals[0], ResultVals.size()).Val;
966 //===----------------------------------------------------------------------===//
967 // C & StdCall & Fast Calling Convention implementation
968 //===----------------------------------------------------------------------===//
969 // StdCall calling convention seems to be standard for many Windows' API
970 // routines and around. It differs from C calling convention just a little:
971 // callee should clean up the stack, not caller. Symbols should be also
972 // decorated in some fancy way :) It doesn't support any vector arguments.
973 // For info on fast calling convention see Fast Calling Convention (tail call)
974 // implementation LowerX86_32FastCCCallTo.
976 /// AddLiveIn - This helper function adds the specified physical register to the
977 /// MachineFunction as a live in value. It also creates a corresponding virtual
979 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
980 const TargetRegisterClass *RC) {
981 assert(RC->contains(PReg) && "Not the correct regclass!");
982 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
983 MF.getRegInfo().addLiveIn(PReg, VReg);
987 /// CallIsStructReturn - Determines whether a CALL node uses struct return
989 static bool CallIsStructReturn(SDOperand Op) {
990 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
994 return cast<ARG_FLAGSSDNode>(Op.getOperand(6))->getArgFlags().isSRet();
997 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
998 /// return semantics.
999 static bool ArgsAreStructReturn(SDOperand Op) {
1000 unsigned NumArgs = Op.Val->getNumValues() - 1;
1004 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1007 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1008 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1010 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1011 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1015 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1018 case CallingConv::X86_StdCall:
1019 return !Subtarget->is64Bit();
1020 case CallingConv::X86_FastCall:
1021 return !Subtarget->is64Bit();
1022 case CallingConv::Fast:
1023 return PerformTailCallOpt;
1027 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1028 /// FORMAL_ARGUMENTS node.
1029 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1030 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1032 if (Subtarget->is64Bit()) {
1033 if (Subtarget->isTargetWin64())
1034 return CC_X86_Win64_C;
1036 if (CC == CallingConv::Fast && PerformTailCallOpt)
1037 return CC_X86_64_TailCall;
1043 if (CC == CallingConv::X86_FastCall)
1044 return CC_X86_32_FastCall;
1045 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1046 return CC_X86_32_TailCall;
1051 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1052 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1054 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1055 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1056 if (CC == CallingConv::X86_FastCall)
1058 else if (CC == CallingConv::X86_StdCall)
1064 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1065 /// in a register before calling.
1066 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1067 return !IsTailCall && !Is64Bit &&
1068 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1069 Subtarget->isPICStyleGOT();
1072 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1073 /// address to be loaded in a register.
1075 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1076 return !Is64Bit && IsTailCall &&
1077 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1078 Subtarget->isPICStyleGOT();
1081 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1082 /// by "Src" to address "Dst" with size and alignment information specified by
1083 /// the specific parameter attribute. The copy will be passed as a byval
1084 /// function parameter.
1086 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1087 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1088 SDOperand SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1089 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1090 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1093 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1094 const CCValAssign &VA,
1095 MachineFrameInfo *MFI,
1097 SDOperand Root, unsigned i) {
1098 // Create the nodes corresponding to a load from this parameter slot.
1099 ISD::ArgFlagsTy Flags =
1100 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1101 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1102 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1104 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1105 // changed with more analysis.
1106 // In case of tail call optimization mark all arguments mutable. Since they
1107 // could be overwritten by lowering of arguments in case of a tail call.
1108 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1109 VA.getLocMemOffset(), isImmutable);
1110 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1111 if (Flags.isByVal())
1113 return DAG.getLoad(VA.getValVT(), Root, FIN,
1114 PseudoSourceValue::getFixedStack(), FI);
1118 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1119 MachineFunction &MF = DAG.getMachineFunction();
1120 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1122 const Function* Fn = MF.getFunction();
1123 if (Fn->hasExternalLinkage() &&
1124 Subtarget->isTargetCygMing() &&
1125 Fn->getName() == "main")
1126 FuncInfo->setForceFramePointer(true);
1128 // Decorate the function name.
1129 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1131 MachineFrameInfo *MFI = MF.getFrameInfo();
1132 SDOperand Root = Op.getOperand(0);
1133 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1134 unsigned CC = MF.getFunction()->getCallingConv();
1135 bool Is64Bit = Subtarget->is64Bit();
1136 bool IsWin64 = Subtarget->isTargetWin64();
1138 assert(!(isVarArg && CC == CallingConv::Fast) &&
1139 "Var args not supported with calling convention fastcc");
1141 // Assign locations to all of the incoming arguments.
1142 SmallVector<CCValAssign, 16> ArgLocs;
1143 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1144 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1146 SmallVector<SDOperand, 8> ArgValues;
1147 unsigned LastVal = ~0U;
1148 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1149 CCValAssign &VA = ArgLocs[i];
1150 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1152 assert(VA.getValNo() != LastVal &&
1153 "Don't support value assigned to multiple locs yet");
1154 LastVal = VA.getValNo();
1156 if (VA.isRegLoc()) {
1157 MVT::ValueType RegVT = VA.getLocVT();
1158 TargetRegisterClass *RC;
1159 if (RegVT == MVT::i32)
1160 RC = X86::GR32RegisterClass;
1161 else if (Is64Bit && RegVT == MVT::i64)
1162 RC = X86::GR64RegisterClass;
1163 else if (RegVT == MVT::f32)
1164 RC = X86::FR32RegisterClass;
1165 else if (RegVT == MVT::f64)
1166 RC = X86::FR64RegisterClass;
1167 else if (MVT::isVector(RegVT) && MVT::getSizeInBits(RegVT) == 128)
1168 RC = X86::VR128RegisterClass;
1169 else if (MVT::isVector(RegVT)) {
1170 assert(MVT::getSizeInBits(RegVT) == 64);
1172 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1174 // Darwin calling convention passes MMX values in either GPRs or
1175 // XMMs in x86-64. Other targets pass them in memory.
1176 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1177 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1180 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1185 assert(0 && "Unknown argument type!");
1188 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1189 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1191 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1192 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1194 if (VA.getLocInfo() == CCValAssign::SExt)
1195 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1196 DAG.getValueType(VA.getValVT()));
1197 else if (VA.getLocInfo() == CCValAssign::ZExt)
1198 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1199 DAG.getValueType(VA.getValVT()));
1201 if (VA.getLocInfo() != CCValAssign::Full)
1202 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1204 // Handle MMX values passed in GPRs.
1205 if (Is64Bit && RegVT != VA.getLocVT()) {
1206 if (MVT::getSizeInBits(RegVT) == 64 && RC == X86::GR64RegisterClass)
1207 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1208 else if (RC == X86::VR128RegisterClass) {
1209 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1210 DAG.getConstant(0, MVT::i64));
1211 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1215 ArgValues.push_back(ArgValue);
1217 assert(VA.isMemLoc());
1218 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1222 // The x86-64 ABI for returning structs by value requires that we copy
1223 // the sret argument into %rax for the return. Save the argument into
1224 // a virtual register so that we can access it from the return points.
1225 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1226 MachineFunction &MF = DAG.getMachineFunction();
1227 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1228 unsigned Reg = FuncInfo->getSRetReturnReg();
1230 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1231 FuncInfo->setSRetReturnReg(Reg);
1233 SDOperand Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1234 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1237 unsigned StackSize = CCInfo.getNextStackOffset();
1238 // align stack specially for tail calls
1239 if (CC == CallingConv::Fast)
1240 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1242 // If the function takes variable number of arguments, make a frame index for
1243 // the start of the first vararg value... for expansion of llvm.va_start.
1245 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1246 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1249 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1251 // FIXME: We should really autogenerate these arrays
1252 static const unsigned GPR64ArgRegsWin64[] = {
1253 X86::RCX, X86::RDX, X86::R8, X86::R9
1255 static const unsigned XMMArgRegsWin64[] = {
1256 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1258 static const unsigned GPR64ArgRegs64Bit[] = {
1259 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1261 static const unsigned XMMArgRegs64Bit[] = {
1262 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1263 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1265 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1268 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1269 GPR64ArgRegs = GPR64ArgRegsWin64;
1270 XMMArgRegs = XMMArgRegsWin64;
1272 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1273 GPR64ArgRegs = GPR64ArgRegs64Bit;
1274 XMMArgRegs = XMMArgRegs64Bit;
1276 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1278 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1281 // For X86-64, if there are vararg parameters that are passed via
1282 // registers, then we must store them to their spots on the stack so they
1283 // may be loaded by deferencing the result of va_next.
1284 VarArgsGPOffset = NumIntRegs * 8;
1285 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1286 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1287 TotalNumXMMRegs * 16, 16);
1289 // Store the integer parameter registers.
1290 SmallVector<SDOperand, 8> MemOps;
1291 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1292 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1293 DAG.getIntPtrConstant(VarArgsGPOffset));
1294 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1295 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1296 X86::GR64RegisterClass);
1297 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1299 DAG.getStore(Val.getValue(1), Val, FIN,
1300 PseudoSourceValue::getFixedStack(),
1302 MemOps.push_back(Store);
1303 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1304 DAG.getIntPtrConstant(8));
1307 // Now store the XMM (fp + vector) parameter registers.
1308 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1309 DAG.getIntPtrConstant(VarArgsFPOffset));
1310 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1311 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1312 X86::VR128RegisterClass);
1313 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1315 DAG.getStore(Val.getValue(1), Val, FIN,
1316 PseudoSourceValue::getFixedStack(),
1318 MemOps.push_back(Store);
1319 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1320 DAG.getIntPtrConstant(16));
1322 if (!MemOps.empty())
1323 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1324 &MemOps[0], MemOps.size());
1328 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1329 // arguments and the arguments after the retaddr has been pushed are
1331 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1332 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1333 (StackSize & 7) == 0)
1336 ArgValues.push_back(Root);
1338 // Some CCs need callee pop.
1339 if (IsCalleePop(Op)) {
1340 BytesToPopOnReturn = StackSize; // Callee pops everything.
1341 BytesCallerReserves = 0;
1343 BytesToPopOnReturn = 0; // Callee pops nothing.
1344 // If this is an sret function, the return should pop the hidden pointer.
1345 if (!Is64Bit && ArgsAreStructReturn(Op))
1346 BytesToPopOnReturn = 4;
1347 BytesCallerReserves = StackSize;
1351 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1352 if (CC == CallingConv::X86_FastCall)
1353 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1356 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1358 // Return the new list of results.
1359 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1360 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1364 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1365 const SDOperand &StackPtr,
1366 const CCValAssign &VA,
1369 unsigned LocMemOffset = VA.getLocMemOffset();
1370 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1371 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1372 ISD::ArgFlagsTy Flags =
1373 cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->getArgFlags();
1374 if (Flags.isByVal()) {
1375 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1377 return DAG.getStore(Chain, Arg, PtrOff,
1378 PseudoSourceValue::getStack(), LocMemOffset);
1381 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1382 /// optimization is performed and it is required.
1384 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1385 SDOperand &OutRetAddr,
1390 if (!IsTailCall || FPDiff==0) return Chain;
1392 // Adjust the Return address stack slot.
1393 MVT::ValueType VT = getPointerTy();
1394 OutRetAddr = getReturnAddressFrameIndex(DAG);
1395 // Load the "old" Return address.
1396 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1397 return SDOperand(OutRetAddr.Val, 1);
1400 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1401 /// optimization is performed and it is required (FPDiff!=0).
1403 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1404 SDOperand Chain, SDOperand RetAddrFrIdx,
1405 bool Is64Bit, int FPDiff) {
1406 // Store the return address to the appropriate stack slot.
1407 if (!FPDiff) return Chain;
1408 // Calculate the new stack slot for the return address.
1409 int SlotSize = Is64Bit ? 8 : 4;
1410 int NewReturnAddrFI =
1411 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1412 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1413 SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1414 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1415 PseudoSourceValue::getFixedStack(), NewReturnAddrFI);
1419 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1420 MachineFunction &MF = DAG.getMachineFunction();
1421 SDOperand Chain = Op.getOperand(0);
1422 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1423 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1424 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1425 && CC == CallingConv::Fast && PerformTailCallOpt;
1426 SDOperand Callee = Op.getOperand(4);
1427 bool Is64Bit = Subtarget->is64Bit();
1428 bool IsStructRet = CallIsStructReturn(Op);
1430 assert(!(isVarArg && CC == CallingConv::Fast) &&
1431 "Var args not supported with calling convention fastcc");
1433 // Analyze operands of the call, assigning locations to each operand.
1434 SmallVector<CCValAssign, 16> ArgLocs;
1435 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1436 CCInfo.AnalyzeCallOperands(Op.Val, CCAssignFnForNode(Op));
1438 // Get a count of how many bytes are to be pushed on the stack.
1439 unsigned NumBytes = CCInfo.getNextStackOffset();
1440 if (CC == CallingConv::Fast)
1441 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1443 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1444 // arguments and the arguments after the retaddr has been pushed are aligned.
1445 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1446 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1447 (NumBytes & 7) == 0)
1452 // Lower arguments at fp - stackoffset + fpdiff.
1453 unsigned NumBytesCallerPushed =
1454 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1455 FPDiff = NumBytesCallerPushed - NumBytes;
1457 // Set the delta of movement of the returnaddr stackslot.
1458 // But only set if delta is greater than previous delta.
1459 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1460 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1463 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1465 SDOperand RetAddrFrIdx;
1466 // Load return adress for tail calls.
1467 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1470 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1471 SmallVector<SDOperand, 8> MemOpChains;
1474 // Walk the register/memloc assignments, inserting copies/loads. In the case
1475 // of tail call optimization arguments are handle later.
1476 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1477 CCValAssign &VA = ArgLocs[i];
1478 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1479 bool isByVal = cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->
1480 getArgFlags().isByVal();
1482 // Promote the value if needed.
1483 switch (VA.getLocInfo()) {
1484 default: assert(0 && "Unknown loc info!");
1485 case CCValAssign::Full: break;
1486 case CCValAssign::SExt:
1487 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1489 case CCValAssign::ZExt:
1490 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1492 case CCValAssign::AExt:
1493 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1497 if (VA.isRegLoc()) {
1499 MVT::ValueType RegVT = VA.getLocVT();
1500 if (MVT::isVector(RegVT) && MVT::getSizeInBits(RegVT) == 64)
1501 switch (VA.getLocReg()) {
1504 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1506 // Special case: passing MMX values in GPR registers.
1507 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1510 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1511 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1512 // Special case: passing MMX values in XMM registers.
1513 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1514 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1515 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1516 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1517 getMOVLMask(2, DAG));
1522 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1524 if (!IsTailCall || (IsTailCall && isByVal)) {
1525 assert(VA.isMemLoc());
1526 if (StackPtr.Val == 0)
1527 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1529 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1535 if (!MemOpChains.empty())
1536 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1537 &MemOpChains[0], MemOpChains.size());
1539 // Build a sequence of copy-to-reg nodes chained together with token chain
1540 // and flag operands which copy the outgoing args into registers.
1542 // Tail call byval lowering might overwrite argument registers so in case of
1543 // tail call optimization the copies to registers are lowered later.
1545 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1546 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1548 InFlag = Chain.getValue(1);
1551 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1553 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1554 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1555 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1557 InFlag = Chain.getValue(1);
1559 // If we are tail calling and generating PIC/GOT style code load the address
1560 // of the callee into ecx. The value in ecx is used as target of the tail
1561 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1562 // calls on PIC/GOT architectures. Normally we would just put the address of
1563 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1564 // restored (since ebx is callee saved) before jumping to the target@PLT.
1565 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1566 // Note: The actual moving to ecx is done further down.
1567 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1568 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1569 !G->getGlobal()->hasProtectedVisibility())
1570 Callee = LowerGlobalAddress(Callee, DAG);
1571 else if (isa<ExternalSymbolSDNode>(Callee))
1572 Callee = LowerExternalSymbol(Callee,DAG);
1575 if (Is64Bit && isVarArg) {
1576 // From AMD64 ABI document:
1577 // For calls that may call functions that use varargs or stdargs
1578 // (prototype-less calls or calls to functions containing ellipsis (...) in
1579 // the declaration) %al is used as hidden argument to specify the number
1580 // of SSE registers used. The contents of %al do not need to match exactly
1581 // the number of registers, but must be an ubound on the number of SSE
1582 // registers used and is in the range 0 - 8 inclusive.
1584 // FIXME: Verify this on Win64
1585 // Count the number of XMM registers allocated.
1586 static const unsigned XMMArgRegs[] = {
1587 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1588 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1590 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1592 Chain = DAG.getCopyToReg(Chain, X86::AL,
1593 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1594 InFlag = Chain.getValue(1);
1598 // For tail calls lower the arguments to the 'real' stack slot.
1600 SmallVector<SDOperand, 8> MemOpChains2;
1603 // Do not flag preceeding copytoreg stuff together with the following stuff.
1604 InFlag = SDOperand();
1605 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1606 CCValAssign &VA = ArgLocs[i];
1607 if (!VA.isRegLoc()) {
1608 assert(VA.isMemLoc());
1609 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1610 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1611 ISD::ArgFlagsTy Flags =
1612 cast<ARG_FLAGSSDNode>(FlagsOp)->getArgFlags();
1613 // Create frame index.
1614 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1615 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1616 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1617 FIN = DAG.getFrameIndex(FI, getPointerTy());
1619 if (Flags.isByVal()) {
1620 // Copy relative to framepointer.
1621 SDOperand Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1622 if (StackPtr.Val == 0)
1623 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1624 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1626 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1629 // Store relative to framepointer.
1630 MemOpChains2.push_back(
1631 DAG.getStore(Chain, Arg, FIN,
1632 PseudoSourceValue::getFixedStack(), FI));
1637 if (!MemOpChains2.empty())
1638 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1639 &MemOpChains2[0], MemOpChains2.size());
1641 // Copy arguments to their registers.
1642 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1643 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1645 InFlag = Chain.getValue(1);
1647 InFlag =SDOperand();
1649 // Store the return address to the appropriate stack slot.
1650 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1654 // If the callee is a GlobalAddress node (quite common, every direct call is)
1655 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1656 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1657 // We should use extra load for direct calls to dllimported functions in
1659 if ((IsTailCall || !Is64Bit ||
1660 getTargetMachine().getCodeModel() != CodeModel::Large)
1661 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1662 getTargetMachine(), true))
1663 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1664 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1665 if (IsTailCall || !Is64Bit ||
1666 getTargetMachine().getCodeModel() != CodeModel::Large)
1667 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1668 } else if (IsTailCall) {
1669 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1671 Chain = DAG.getCopyToReg(Chain,
1672 DAG.getRegister(Opc, getPointerTy()),
1674 Callee = DAG.getRegister(Opc, getPointerTy());
1675 // Add register as live out.
1676 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1679 // Returns a chain & a flag for retval copy to use.
1680 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1681 SmallVector<SDOperand, 8> Ops;
1684 Ops.push_back(Chain);
1685 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1686 Ops.push_back(DAG.getIntPtrConstant(0));
1688 Ops.push_back(InFlag);
1689 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1690 InFlag = Chain.getValue(1);
1692 // Returns a chain & a flag for retval copy to use.
1693 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1697 Ops.push_back(Chain);
1698 Ops.push_back(Callee);
1701 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1703 // Add argument registers to the end of the list so that they are known live
1705 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1706 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1707 RegsToPass[i].second.getValueType()));
1709 // Add an implicit use GOT pointer in EBX.
1710 if (!IsTailCall && !Is64Bit &&
1711 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1712 Subtarget->isPICStyleGOT())
1713 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1715 // Add an implicit use of AL for x86 vararg functions.
1716 if (Is64Bit && isVarArg)
1717 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1720 Ops.push_back(InFlag);
1723 assert(InFlag.Val &&
1724 "Flag must be set. Depend on flag being set in LowerRET");
1725 Chain = DAG.getNode(X86ISD::TAILCALL,
1726 Op.Val->getVTList(), &Ops[0], Ops.size());
1728 return SDOperand(Chain.Val, Op.ResNo);
1731 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1732 InFlag = Chain.getValue(1);
1734 // Create the CALLSEQ_END node.
1735 unsigned NumBytesForCalleeToPush;
1736 if (IsCalleePop(Op))
1737 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1738 else if (!Is64Bit && IsStructRet)
1739 // If this is is a call to a struct-return function, the callee
1740 // pops the hidden struct pointer, so we have to push it back.
1741 // This is common for Darwin/X86, Linux & Mingw32 targets.
1742 NumBytesForCalleeToPush = 4;
1744 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1746 // Returns a flag for retval copy to use.
1747 Chain = DAG.getCALLSEQ_END(Chain,
1748 DAG.getIntPtrConstant(NumBytes),
1749 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1751 InFlag = Chain.getValue(1);
1753 // Handle result values, copying them out of physregs into vregs that we
1755 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1759 //===----------------------------------------------------------------------===//
1760 // Fast Calling Convention (tail call) implementation
1761 //===----------------------------------------------------------------------===//
1763 // Like std call, callee cleans arguments, convention except that ECX is
1764 // reserved for storing the tail called function address. Only 2 registers are
1765 // free for argument passing (inreg). Tail call optimization is performed
1767 // * tailcallopt is enabled
1768 // * caller/callee are fastcc
1769 // On X86_64 architecture with GOT-style position independent code only local
1770 // (within module) calls are supported at the moment.
1771 // To keep the stack aligned according to platform abi the function
1772 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1773 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1774 // If a tail called function callee has more arguments than the caller the
1775 // caller needs to make sure that there is room to move the RETADDR to. This is
1776 // achieved by reserving an area the size of the argument delta right after the
1777 // original REtADDR, but before the saved framepointer or the spilled registers
1778 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1790 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1791 /// for a 16 byte align requirement.
1792 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1793 SelectionDAG& DAG) {
1794 if (PerformTailCallOpt) {
1795 MachineFunction &MF = DAG.getMachineFunction();
1796 const TargetMachine &TM = MF.getTarget();
1797 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1798 unsigned StackAlignment = TFI.getStackAlignment();
1799 uint64_t AlignMask = StackAlignment - 1;
1800 int64_t Offset = StackSize;
1801 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1802 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1803 // Number smaller than 12 so just add the difference.
1804 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1806 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1807 Offset = ((~AlignMask) & Offset) + StackAlignment +
1808 (StackAlignment-SlotSize);
1815 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1816 /// following the call is a return. A function is eligible if caller/callee
1817 /// calling conventions match, currently only fastcc supports tail calls, and
1818 /// the function CALL is immediatly followed by a RET.
1819 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1821 SelectionDAG& DAG) const {
1822 if (!PerformTailCallOpt)
1825 if (CheckTailCallReturnConstraints(Call, Ret)) {
1826 MachineFunction &MF = DAG.getMachineFunction();
1827 unsigned CallerCC = MF.getFunction()->getCallingConv();
1828 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1829 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1830 SDOperand Callee = Call.getOperand(4);
1831 // On x86/32Bit PIC/GOT tail calls are supported.
1832 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1833 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1836 // Can only do local tail calls (in same module, hidden or protected) on
1837 // x86_64 PIC/GOT at the moment.
1838 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1839 return G->getGlobal()->hasHiddenVisibility()
1840 || G->getGlobal()->hasProtectedVisibility();
1847 //===----------------------------------------------------------------------===//
1848 // Other Lowering Hooks
1849 //===----------------------------------------------------------------------===//
1852 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1853 MachineFunction &MF = DAG.getMachineFunction();
1854 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1855 int ReturnAddrIndex = FuncInfo->getRAIndex();
1857 if (ReturnAddrIndex == 0) {
1858 // Set up a frame object for the return address.
1859 if (Subtarget->is64Bit())
1860 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1862 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1864 FuncInfo->setRAIndex(ReturnAddrIndex);
1867 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1872 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1873 /// specific condition code. It returns a false if it cannot do a direct
1874 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1876 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1877 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1878 SelectionDAG &DAG) {
1879 X86CC = X86::COND_INVALID;
1881 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1882 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1883 // X > -1 -> X == 0, jump !sign.
1884 RHS = DAG.getConstant(0, RHS.getValueType());
1885 X86CC = X86::COND_NS;
1887 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1888 // X < 0 -> X == 0, jump on sign.
1889 X86CC = X86::COND_S;
1891 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1893 RHS = DAG.getConstant(0, RHS.getValueType());
1894 X86CC = X86::COND_LE;
1899 switch (SetCCOpcode) {
1901 case ISD::SETEQ: X86CC = X86::COND_E; break;
1902 case ISD::SETGT: X86CC = X86::COND_G; break;
1903 case ISD::SETGE: X86CC = X86::COND_GE; break;
1904 case ISD::SETLT: X86CC = X86::COND_L; break;
1905 case ISD::SETLE: X86CC = X86::COND_LE; break;
1906 case ISD::SETNE: X86CC = X86::COND_NE; break;
1907 case ISD::SETULT: X86CC = X86::COND_B; break;
1908 case ISD::SETUGT: X86CC = X86::COND_A; break;
1909 case ISD::SETULE: X86CC = X86::COND_BE; break;
1910 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1913 // On a floating point condition, the flags are set as follows:
1915 // 0 | 0 | 0 | X > Y
1916 // 0 | 0 | 1 | X < Y
1917 // 1 | 0 | 0 | X == Y
1918 // 1 | 1 | 1 | unordered
1920 switch (SetCCOpcode) {
1923 case ISD::SETEQ: X86CC = X86::COND_E; break;
1924 case ISD::SETOLT: Flip = true; // Fallthrough
1926 case ISD::SETGT: X86CC = X86::COND_A; break;
1927 case ISD::SETOLE: Flip = true; // Fallthrough
1929 case ISD::SETGE: X86CC = X86::COND_AE; break;
1930 case ISD::SETUGT: Flip = true; // Fallthrough
1932 case ISD::SETLT: X86CC = X86::COND_B; break;
1933 case ISD::SETUGE: Flip = true; // Fallthrough
1935 case ISD::SETLE: X86CC = X86::COND_BE; break;
1937 case ISD::SETNE: X86CC = X86::COND_NE; break;
1938 case ISD::SETUO: X86CC = X86::COND_P; break;
1939 case ISD::SETO: X86CC = X86::COND_NP; break;
1942 std::swap(LHS, RHS);
1945 return X86CC != X86::COND_INVALID;
1948 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1949 /// code. Current x86 isa includes the following FP cmov instructions:
1950 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1951 static bool hasFPCMov(unsigned X86CC) {
1967 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1968 /// true if Op is undef or if its value falls within the specified range (L, H].
1969 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1970 if (Op.getOpcode() == ISD::UNDEF)
1973 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1974 return (Val >= Low && Val < Hi);
1977 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
1978 /// true if Op is undef or if its value equal to the specified value.
1979 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1980 if (Op.getOpcode() == ISD::UNDEF)
1982 return cast<ConstantSDNode>(Op)->getValue() == Val;
1985 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1986 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1987 bool X86::isPSHUFDMask(SDNode *N) {
1988 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1990 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
1993 // Check if the value doesn't reference the second vector.
1994 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1995 SDOperand Arg = N->getOperand(i);
1996 if (Arg.getOpcode() == ISD::UNDEF) continue;
1997 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1998 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2005 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2006 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2007 bool X86::isPSHUFHWMask(SDNode *N) {
2008 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2010 if (N->getNumOperands() != 8)
2013 // Lower quadword copied in order.
2014 for (unsigned i = 0; i != 4; ++i) {
2015 SDOperand Arg = N->getOperand(i);
2016 if (Arg.getOpcode() == ISD::UNDEF) continue;
2017 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2018 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2022 // Upper quadword shuffled.
2023 for (unsigned i = 4; i != 8; ++i) {
2024 SDOperand Arg = N->getOperand(i);
2025 if (Arg.getOpcode() == ISD::UNDEF) continue;
2026 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2027 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2028 if (Val < 4 || Val > 7)
2035 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2036 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2037 bool X86::isPSHUFLWMask(SDNode *N) {
2038 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2040 if (N->getNumOperands() != 8)
2043 // Upper quadword copied in order.
2044 for (unsigned i = 4; i != 8; ++i)
2045 if (!isUndefOrEqual(N->getOperand(i), i))
2048 // Lower quadword shuffled.
2049 for (unsigned i = 0; i != 4; ++i)
2050 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2056 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2057 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2058 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2059 if (NumElems != 2 && NumElems != 4) return false;
2061 unsigned Half = NumElems / 2;
2062 for (unsigned i = 0; i < Half; ++i)
2063 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2065 for (unsigned i = Half; i < NumElems; ++i)
2066 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2072 bool X86::isSHUFPMask(SDNode *N) {
2073 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2074 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2077 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2078 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2079 /// half elements to come from vector 1 (which would equal the dest.) and
2080 /// the upper half to come from vector 2.
2081 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2082 if (NumOps != 2 && NumOps != 4) return false;
2084 unsigned Half = NumOps / 2;
2085 for (unsigned i = 0; i < Half; ++i)
2086 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2088 for (unsigned i = Half; i < NumOps; ++i)
2089 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2094 static bool isCommutedSHUFP(SDNode *N) {
2095 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2096 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2099 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2100 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2101 bool X86::isMOVHLPSMask(SDNode *N) {
2102 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2104 if (N->getNumOperands() != 4)
2107 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2108 return isUndefOrEqual(N->getOperand(0), 6) &&
2109 isUndefOrEqual(N->getOperand(1), 7) &&
2110 isUndefOrEqual(N->getOperand(2), 2) &&
2111 isUndefOrEqual(N->getOperand(3), 3);
2114 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2115 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2117 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2118 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2120 if (N->getNumOperands() != 4)
2123 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2124 return isUndefOrEqual(N->getOperand(0), 2) &&
2125 isUndefOrEqual(N->getOperand(1), 3) &&
2126 isUndefOrEqual(N->getOperand(2), 2) &&
2127 isUndefOrEqual(N->getOperand(3), 3);
2130 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2131 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2132 bool X86::isMOVLPMask(SDNode *N) {
2133 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2135 unsigned NumElems = N->getNumOperands();
2136 if (NumElems != 2 && NumElems != 4)
2139 for (unsigned i = 0; i < NumElems/2; ++i)
2140 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2143 for (unsigned i = NumElems/2; i < NumElems; ++i)
2144 if (!isUndefOrEqual(N->getOperand(i), i))
2150 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2151 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2153 bool X86::isMOVHPMask(SDNode *N) {
2154 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2156 unsigned NumElems = N->getNumOperands();
2157 if (NumElems != 2 && NumElems != 4)
2160 for (unsigned i = 0; i < NumElems/2; ++i)
2161 if (!isUndefOrEqual(N->getOperand(i), i))
2164 for (unsigned i = 0; i < NumElems/2; ++i) {
2165 SDOperand Arg = N->getOperand(i + NumElems/2);
2166 if (!isUndefOrEqual(Arg, i + NumElems))
2173 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2174 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2175 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2176 bool V2IsSplat = false) {
2177 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2180 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2181 SDOperand BitI = Elts[i];
2182 SDOperand BitI1 = Elts[i+1];
2183 if (!isUndefOrEqual(BitI, j))
2186 if (isUndefOrEqual(BitI1, NumElts))
2189 if (!isUndefOrEqual(BitI1, j + NumElts))
2197 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2198 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2199 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2202 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2203 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2204 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2205 bool V2IsSplat = false) {
2206 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2209 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2210 SDOperand BitI = Elts[i];
2211 SDOperand BitI1 = Elts[i+1];
2212 if (!isUndefOrEqual(BitI, j + NumElts/2))
2215 if (isUndefOrEqual(BitI1, NumElts))
2218 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2226 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2227 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2228 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2231 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2232 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2234 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2235 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2237 unsigned NumElems = N->getNumOperands();
2238 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2241 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2242 SDOperand BitI = N->getOperand(i);
2243 SDOperand BitI1 = N->getOperand(i+1);
2245 if (!isUndefOrEqual(BitI, j))
2247 if (!isUndefOrEqual(BitI1, j))
2254 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2255 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2257 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2258 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2260 unsigned NumElems = N->getNumOperands();
2261 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2264 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2265 SDOperand BitI = N->getOperand(i);
2266 SDOperand BitI1 = N->getOperand(i + 1);
2268 if (!isUndefOrEqual(BitI, j))
2270 if (!isUndefOrEqual(BitI1, j))
2277 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2278 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2279 /// MOVSD, and MOVD, i.e. setting the lowest element.
2280 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2281 if (NumElts != 2 && NumElts != 4)
2284 if (!isUndefOrEqual(Elts[0], NumElts))
2287 for (unsigned i = 1; i < NumElts; ++i) {
2288 if (!isUndefOrEqual(Elts[i], i))
2295 bool X86::isMOVLMask(SDNode *N) {
2296 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2297 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2300 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2301 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2302 /// element of vector 2 and the other elements to come from vector 1 in order.
2303 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2304 bool V2IsSplat = false,
2305 bool V2IsUndef = false) {
2306 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2309 if (!isUndefOrEqual(Ops[0], 0))
2312 for (unsigned i = 1; i < NumOps; ++i) {
2313 SDOperand Arg = Ops[i];
2314 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2315 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2316 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2323 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2324 bool V2IsUndef = false) {
2325 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2326 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2327 V2IsSplat, V2IsUndef);
2330 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2331 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2332 bool X86::isMOVSHDUPMask(SDNode *N) {
2333 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2335 if (N->getNumOperands() != 4)
2338 // Expect 1, 1, 3, 3
2339 for (unsigned i = 0; i < 2; ++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 != 1) return false;
2348 for (unsigned i = 2; i < 4; ++i) {
2349 SDOperand Arg = N->getOperand(i);
2350 if (Arg.getOpcode() == ISD::UNDEF) continue;
2351 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2352 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2353 if (Val != 3) return false;
2357 // Don't use movshdup if it can be done with a shufps.
2361 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2362 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2363 bool X86::isMOVSLDUPMask(SDNode *N) {
2364 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2366 if (N->getNumOperands() != 4)
2369 // Expect 0, 0, 2, 2
2370 for (unsigned i = 0; i < 2; ++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 != 0) return false;
2379 for (unsigned i = 2; i < 4; ++i) {
2380 SDOperand Arg = N->getOperand(i);
2381 if (Arg.getOpcode() == ISD::UNDEF) continue;
2382 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2383 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2384 if (Val != 2) return false;
2388 // Don't use movshdup if it can be done with a shufps.
2392 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2393 /// specifies a identity operation on the LHS or RHS.
2394 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2395 unsigned NumElems = N->getNumOperands();
2396 for (unsigned i = 0; i < NumElems; ++i)
2397 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2402 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2403 /// a splat of a single element.
2404 static bool isSplatMask(SDNode *N) {
2405 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2407 // This is a splat operation if each element of the permute is the same, and
2408 // if the value doesn't reference the second vector.
2409 unsigned NumElems = N->getNumOperands();
2410 SDOperand ElementBase;
2412 for (; i != NumElems; ++i) {
2413 SDOperand Elt = N->getOperand(i);
2414 if (isa<ConstantSDNode>(Elt)) {
2420 if (!ElementBase.Val)
2423 for (; i != NumElems; ++i) {
2424 SDOperand Arg = N->getOperand(i);
2425 if (Arg.getOpcode() == ISD::UNDEF) continue;
2426 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2427 if (Arg != ElementBase) return false;
2430 // Make sure it is a splat of the first vector operand.
2431 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2434 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2435 /// a splat of a single element and it's a 2 or 4 element mask.
2436 bool X86::isSplatMask(SDNode *N) {
2437 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2439 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2440 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2442 return ::isSplatMask(N);
2445 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2446 /// specifies a splat of zero element.
2447 bool X86::isSplatLoMask(SDNode *N) {
2448 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2450 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2451 if (!isUndefOrEqual(N->getOperand(i), 0))
2456 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2457 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2459 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2460 unsigned NumOperands = N->getNumOperands();
2461 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2463 for (unsigned i = 0; i < NumOperands; ++i) {
2465 SDOperand Arg = N->getOperand(NumOperands-i-1);
2466 if (Arg.getOpcode() != ISD::UNDEF)
2467 Val = cast<ConstantSDNode>(Arg)->getValue();
2468 if (Val >= NumOperands) Val -= NumOperands;
2470 if (i != NumOperands - 1)
2477 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2478 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2480 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2482 // 8 nodes, but we only care about the last 4.
2483 for (unsigned i = 7; i >= 4; --i) {
2485 SDOperand Arg = N->getOperand(i);
2486 if (Arg.getOpcode() != ISD::UNDEF)
2487 Val = cast<ConstantSDNode>(Arg)->getValue();
2496 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2497 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2499 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2501 // 8 nodes, but we only care about the first 4.
2502 for (int i = 3; i >= 0; --i) {
2504 SDOperand Arg = N->getOperand(i);
2505 if (Arg.getOpcode() != ISD::UNDEF)
2506 Val = cast<ConstantSDNode>(Arg)->getValue();
2515 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2516 /// specifies a 8 element shuffle that can be broken into a pair of
2517 /// PSHUFHW and PSHUFLW.
2518 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2519 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2521 if (N->getNumOperands() != 8)
2524 // Lower quadword shuffled.
2525 for (unsigned i = 0; i != 4; ++i) {
2526 SDOperand Arg = N->getOperand(i);
2527 if (Arg.getOpcode() == ISD::UNDEF) continue;
2528 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2529 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2534 // Upper quadword shuffled.
2535 for (unsigned i = 4; i != 8; ++i) {
2536 SDOperand Arg = N->getOperand(i);
2537 if (Arg.getOpcode() == ISD::UNDEF) continue;
2538 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2539 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2540 if (Val < 4 || Val > 7)
2547 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2548 /// values in ther permute mask.
2549 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2550 SDOperand &V2, SDOperand &Mask,
2551 SelectionDAG &DAG) {
2552 MVT::ValueType VT = Op.getValueType();
2553 MVT::ValueType MaskVT = Mask.getValueType();
2554 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2555 unsigned NumElems = Mask.getNumOperands();
2556 SmallVector<SDOperand, 8> MaskVec;
2558 for (unsigned i = 0; i != NumElems; ++i) {
2559 SDOperand Arg = Mask.getOperand(i);
2560 if (Arg.getOpcode() == ISD::UNDEF) {
2561 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2564 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2565 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2567 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2569 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2573 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2574 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2577 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2578 /// the two vector operands have swapped position.
2580 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2581 MVT::ValueType MaskVT = Mask.getValueType();
2582 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2583 unsigned NumElems = Mask.getNumOperands();
2584 SmallVector<SDOperand, 8> MaskVec;
2585 for (unsigned i = 0; i != NumElems; ++i) {
2586 SDOperand Arg = Mask.getOperand(i);
2587 if (Arg.getOpcode() == ISD::UNDEF) {
2588 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2591 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2592 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2594 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2596 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2598 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2602 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2603 /// match movhlps. The lower half elements should come from upper half of
2604 /// V1 (and in order), and the upper half elements should come from the upper
2605 /// half of V2 (and in order).
2606 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2607 unsigned NumElems = Mask->getNumOperands();
2610 for (unsigned i = 0, e = 2; i != e; ++i)
2611 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2613 for (unsigned i = 2; i != 4; ++i)
2614 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2619 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2620 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2622 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2623 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2624 N = N->getOperand(0).Val;
2625 if (ISD::isNON_EXTLoad(N)) {
2627 *LD = cast<LoadSDNode>(N);
2634 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2635 /// match movlp{s|d}. The lower half elements should come from lower half of
2636 /// V1 (and in order), and the upper half elements should come from the upper
2637 /// half of V2 (and in order). And since V1 will become the source of the
2638 /// MOVLP, it must be either a vector load or a scalar load to vector.
2639 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2640 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2642 // Is V2 is a vector load, don't do this transformation. We will try to use
2643 // load folding shufps op.
2644 if (ISD::isNON_EXTLoad(V2))
2647 unsigned NumElems = Mask->getNumOperands();
2648 if (NumElems != 2 && NumElems != 4)
2650 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2651 if (!isUndefOrEqual(Mask->getOperand(i), i))
2653 for (unsigned i = NumElems/2; i != NumElems; ++i)
2654 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2659 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2661 static bool isSplatVector(SDNode *N) {
2662 if (N->getOpcode() != ISD::BUILD_VECTOR)
2665 SDOperand SplatValue = N->getOperand(0);
2666 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2667 if (N->getOperand(i) != SplatValue)
2672 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2674 static bool isUndefShuffle(SDNode *N) {
2675 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2678 SDOperand V1 = N->getOperand(0);
2679 SDOperand V2 = N->getOperand(1);
2680 SDOperand Mask = N->getOperand(2);
2681 unsigned NumElems = Mask.getNumOperands();
2682 for (unsigned i = 0; i != NumElems; ++i) {
2683 SDOperand Arg = Mask.getOperand(i);
2684 if (Arg.getOpcode() != ISD::UNDEF) {
2685 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2686 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2688 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2695 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2697 static inline bool isZeroNode(SDOperand Elt) {
2698 return ((isa<ConstantSDNode>(Elt) &&
2699 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2700 (isa<ConstantFPSDNode>(Elt) &&
2701 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2704 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2705 /// to an zero vector.
2706 static bool isZeroShuffle(SDNode *N) {
2707 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2710 SDOperand V1 = N->getOperand(0);
2711 SDOperand V2 = N->getOperand(1);
2712 SDOperand Mask = N->getOperand(2);
2713 unsigned NumElems = Mask.getNumOperands();
2714 for (unsigned i = 0; i != NumElems; ++i) {
2715 SDOperand Arg = Mask.getOperand(i);
2716 if (Arg.getOpcode() == ISD::UNDEF)
2719 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2720 if (Idx < NumElems) {
2721 unsigned Opc = V1.Val->getOpcode();
2722 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2724 if (Opc != ISD::BUILD_VECTOR ||
2725 !isZeroNode(V1.Val->getOperand(Idx)))
2727 } else if (Idx >= NumElems) {
2728 unsigned Opc = V2.Val->getOpcode();
2729 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2731 if (Opc != ISD::BUILD_VECTOR ||
2732 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2739 /// getZeroVector - Returns a vector of specified type with all zero elements.
2741 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2742 assert(MVT::isVector(VT) && "Expected a vector type");
2744 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2745 // type. This ensures they get CSE'd.
2746 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2748 if (MVT::getSizeInBits(VT) == 64) // MMX
2749 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2751 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2752 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2755 /// getOnesVector - Returns a vector of specified type with all bits set.
2757 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2758 assert(MVT::isVector(VT) && "Expected a vector type");
2760 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2761 // type. This ensures they get CSE'd.
2762 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2764 if (MVT::getSizeInBits(VT) == 64) // MMX
2765 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2767 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2768 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2772 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2773 /// that point to V2 points to its first element.
2774 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2775 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2777 bool Changed = false;
2778 SmallVector<SDOperand, 8> MaskVec;
2779 unsigned NumElems = Mask.getNumOperands();
2780 for (unsigned i = 0; i != NumElems; ++i) {
2781 SDOperand Arg = Mask.getOperand(i);
2782 if (Arg.getOpcode() != ISD::UNDEF) {
2783 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2784 if (Val > NumElems) {
2785 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2789 MaskVec.push_back(Arg);
2793 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2794 &MaskVec[0], MaskVec.size());
2798 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2799 /// operation of specified width.
2800 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2801 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2802 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2804 SmallVector<SDOperand, 8> MaskVec;
2805 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2806 for (unsigned i = 1; i != NumElems; ++i)
2807 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2808 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2811 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2812 /// of specified width.
2813 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2814 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2815 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2816 SmallVector<SDOperand, 8> MaskVec;
2817 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2818 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2819 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2821 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2824 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2825 /// of specified width.
2826 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2827 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2828 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2829 unsigned Half = NumElems/2;
2830 SmallVector<SDOperand, 8> MaskVec;
2831 for (unsigned i = 0; i != Half; ++i) {
2832 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2833 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2835 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2838 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2839 /// element #0 of a vector with the specified index, leaving the rest of the
2840 /// elements in place.
2841 static SDOperand getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2842 SelectionDAG &DAG) {
2843 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2844 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2845 SmallVector<SDOperand, 8> MaskVec;
2846 // Element #0 of the result gets the elt we are replacing.
2847 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2848 for (unsigned i = 1; i != NumElems; ++i)
2849 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2850 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2853 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2854 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG, bool HasSSE2) {
2855 MVT::ValueType PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2856 MVT::ValueType VT = Op.getValueType();
2859 SDOperand V1 = Op.getOperand(0);
2860 SDOperand Mask = Op.getOperand(2);
2861 unsigned NumElems = Mask.getNumOperands();
2862 // Special handling of v4f32 -> v4i32.
2863 if (VT != MVT::v4f32) {
2864 Mask = getUnpacklMask(NumElems, DAG);
2865 while (NumElems > 4) {
2866 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2869 Mask = getZeroVector(MVT::v4i32, DAG);
2872 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2873 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2874 DAG.getNode(ISD::UNDEF, PVT), Mask);
2875 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2878 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2879 /// vector of zero or undef vector. This produces a shuffle where the low
2880 /// element of V2 is swizzled into the zero/undef vector, landing at element
2881 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2882 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, unsigned Idx,
2883 bool isZero, SelectionDAG &DAG) {
2884 MVT::ValueType VT = V2.getValueType();
2885 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2886 unsigned NumElems = MVT::getVectorNumElements(V2.getValueType());
2887 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2888 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2889 SmallVector<SDOperand, 16> MaskVec;
2890 for (unsigned i = 0; i != NumElems; ++i)
2891 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2892 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2894 MaskVec.push_back(DAG.getConstant(i, EVT));
2895 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2896 &MaskVec[0], MaskVec.size());
2897 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2900 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2902 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2903 unsigned NumNonZero, unsigned NumZero,
2904 SelectionDAG &DAG, TargetLowering &TLI) {
2910 for (unsigned i = 0; i < 16; ++i) {
2911 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2912 if (ThisIsNonZero && First) {
2914 V = getZeroVector(MVT::v8i16, DAG);
2916 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2921 SDOperand ThisElt(0, 0), LastElt(0, 0);
2922 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2923 if (LastIsNonZero) {
2924 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2926 if (ThisIsNonZero) {
2927 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2928 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2929 ThisElt, DAG.getConstant(8, MVT::i8));
2931 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2936 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2937 DAG.getIntPtrConstant(i/2));
2941 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2944 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2946 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2947 unsigned NumNonZero, unsigned NumZero,
2948 SelectionDAG &DAG, TargetLowering &TLI) {
2954 for (unsigned i = 0; i < 8; ++i) {
2955 bool isNonZero = (NonZeros & (1 << i)) != 0;
2959 V = getZeroVector(MVT::v8i16, DAG);
2961 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2964 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2965 DAG.getIntPtrConstant(i));
2973 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2974 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
2975 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
2976 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
2977 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
2978 // eliminated on x86-32 hosts.
2979 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
2982 if (ISD::isBuildVectorAllOnes(Op.Val))
2983 return getOnesVector(Op.getValueType(), DAG);
2984 return getZeroVector(Op.getValueType(), DAG);
2987 MVT::ValueType VT = Op.getValueType();
2988 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2989 unsigned EVTBits = MVT::getSizeInBits(EVT);
2991 unsigned NumElems = Op.getNumOperands();
2992 unsigned NumZero = 0;
2993 unsigned NumNonZero = 0;
2994 unsigned NonZeros = 0;
2995 bool IsAllConstants = true;
2996 SmallSet<SDOperand, 8> Values;
2997 for (unsigned i = 0; i < NumElems; ++i) {
2998 SDOperand Elt = Op.getOperand(i);
2999 if (Elt.getOpcode() == ISD::UNDEF)
3002 if (Elt.getOpcode() != ISD::Constant &&
3003 Elt.getOpcode() != ISD::ConstantFP)
3004 IsAllConstants = false;
3005 if (isZeroNode(Elt))
3008 NonZeros |= (1 << i);
3013 if (NumNonZero == 0) {
3014 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3015 return DAG.getNode(ISD::UNDEF, VT);
3018 // Special case for single non-zero, non-undef, element.
3019 if (NumNonZero == 1 && NumElems <= 4) {
3020 unsigned Idx = CountTrailingZeros_32(NonZeros);
3021 SDOperand Item = Op.getOperand(Idx);
3023 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3024 // the value are obviously zero, truncate the value to i32 and do the
3025 // insertion that way. Only do this if the value is non-constant or if the
3026 // value is a constant being inserted into element 0. It is cheaper to do
3027 // a constant pool load than it is to do a movd + shuffle.
3028 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3029 (!IsAllConstants || Idx == 0)) {
3030 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3031 // Handle MMX and SSE both.
3032 MVT::ValueType VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3033 MVT::ValueType VecElts = VT == MVT::v2i64 ? 4 : 2;
3035 // Truncate the value (which may itself be a constant) to i32, and
3036 // convert it to a vector with movd (S2V+shuffle to zero extend).
3037 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3038 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3039 Item = getShuffleVectorZeroOrUndef(Item, 0, true, DAG);
3041 // Now we have our 32-bit value zero extended in the low element of
3042 // a vector. If Idx != 0, swizzle it into place.
3045 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3046 getSwapEltZeroMask(VecElts, Idx, DAG)
3048 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3050 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3054 // If we have a constant or non-constant insertion into the low element of
3055 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3056 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3057 // depending on what the source datatype is. Because we can only get here
3058 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3060 // Don't do this for i64 values on x86-32.
3061 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3062 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3063 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3064 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3067 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3070 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3071 // is a non-constant being inserted into an element other than the low one,
3072 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3073 // movd/movss) to move this into the low element, then shuffle it into
3075 if (EVTBits == 32) {
3076 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3078 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3079 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3080 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3081 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3082 SmallVector<SDOperand, 8> MaskVec;
3083 for (unsigned i = 0; i < NumElems; i++)
3084 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3085 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3086 &MaskVec[0], MaskVec.size());
3087 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3088 DAG.getNode(ISD::UNDEF, VT), Mask);
3092 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3093 if (Values.size() == 1)
3096 // A vector full of immediates; various special cases are already
3097 // handled, so this is best done with a single constant-pool load.
3101 // Let legalizer expand 2-wide build_vectors.
3102 if (EVTBits == 64) {
3103 if (NumNonZero == 1) {
3104 // One half is zero or undef.
3105 unsigned Idx = CountTrailingZeros_32(NonZeros);
3106 SDOperand V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3107 Op.getOperand(Idx));
3108 return getShuffleVectorZeroOrUndef(V2, Idx, true, DAG);
3113 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3114 if (EVTBits == 8 && NumElems == 16) {
3115 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3117 if (V.Val) return V;
3120 if (EVTBits == 16 && NumElems == 8) {
3121 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3123 if (V.Val) return V;
3126 // If element VT is == 32 bits, turn it into a number of shuffles.
3127 SmallVector<SDOperand, 8> V;
3129 if (NumElems == 4 && NumZero > 0) {
3130 for (unsigned i = 0; i < 4; ++i) {
3131 bool isZero = !(NonZeros & (1 << i));
3133 V[i] = getZeroVector(VT, DAG);
3135 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3138 for (unsigned i = 0; i < 2; ++i) {
3139 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3142 V[i] = V[i*2]; // Must be a zero vector.
3145 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3146 getMOVLMask(NumElems, DAG));
3149 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3150 getMOVLMask(NumElems, DAG));
3153 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3154 getUnpacklMask(NumElems, DAG));
3159 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3160 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3161 SmallVector<SDOperand, 8> MaskVec;
3162 bool Reverse = (NonZeros & 0x3) == 2;
3163 for (unsigned i = 0; i < 2; ++i)
3165 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3167 MaskVec.push_back(DAG.getConstant(i, EVT));
3168 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3169 for (unsigned i = 0; i < 2; ++i)
3171 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3173 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3174 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3175 &MaskVec[0], MaskVec.size());
3176 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3179 if (Values.size() > 2) {
3180 // Expand into a number of unpckl*.
3182 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3183 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3184 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3185 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3186 for (unsigned i = 0; i < NumElems; ++i)
3187 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3189 while (NumElems != 0) {
3190 for (unsigned i = 0; i < NumElems; ++i)
3191 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3202 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3203 SDOperand PermMask, SelectionDAG &DAG,
3204 TargetLowering &TLI) {
3206 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3207 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3208 MVT::ValueType PtrVT = TLI.getPointerTy();
3209 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3210 PermMask.Val->op_end());
3212 // First record which half of which vector the low elements come from.
3213 SmallVector<unsigned, 4> LowQuad(4);
3214 for (unsigned i = 0; i < 4; ++i) {
3215 SDOperand Elt = MaskElts[i];
3216 if (Elt.getOpcode() == ISD::UNDEF)
3218 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3219 int QuadIdx = EltIdx / 4;
3222 int BestLowQuad = -1;
3223 unsigned MaxQuad = 1;
3224 for (unsigned i = 0; i < 4; ++i) {
3225 if (LowQuad[i] > MaxQuad) {
3227 MaxQuad = LowQuad[i];
3231 // Record which half of which vector the high elements come from.
3232 SmallVector<unsigned, 4> HighQuad(4);
3233 for (unsigned i = 4; i < 8; ++i) {
3234 SDOperand Elt = MaskElts[i];
3235 if (Elt.getOpcode() == ISD::UNDEF)
3237 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3238 int QuadIdx = EltIdx / 4;
3239 ++HighQuad[QuadIdx];
3241 int BestHighQuad = -1;
3243 for (unsigned i = 0; i < 4; ++i) {
3244 if (HighQuad[i] > MaxQuad) {
3246 MaxQuad = HighQuad[i];
3250 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3251 if (BestLowQuad != -1 || BestHighQuad != -1) {
3252 // First sort the 4 chunks in order using shufpd.
3253 SmallVector<SDOperand, 8> MaskVec;
3254 if (BestLowQuad != -1)
3255 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3257 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3258 if (BestHighQuad != -1)
3259 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3261 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3262 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3263 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3264 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3265 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3266 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3268 // Now sort high and low parts separately.
3269 BitVector InOrder(8);
3270 if (BestLowQuad != -1) {
3271 // Sort lower half in order using PSHUFLW.
3273 bool AnyOutOrder = false;
3274 for (unsigned i = 0; i != 4; ++i) {
3275 SDOperand Elt = MaskElts[i];
3276 if (Elt.getOpcode() == ISD::UNDEF) {
3277 MaskVec.push_back(Elt);
3280 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3283 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3284 // If this element is in the right place after this shuffle, then
3286 if ((int)(EltIdx / 4) == BestLowQuad)
3291 for (unsigned i = 4; i != 8; ++i)
3292 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3293 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3294 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3298 if (BestHighQuad != -1) {
3299 // Sort high half in order using PSHUFHW if possible.
3301 for (unsigned i = 0; i != 4; ++i)
3302 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3303 bool AnyOutOrder = false;
3304 for (unsigned i = 4; i != 8; ++i) {
3305 SDOperand Elt = MaskElts[i];
3306 if (Elt.getOpcode() == ISD::UNDEF) {
3307 MaskVec.push_back(Elt);
3310 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3313 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3314 // If this element is in the right place after this shuffle, then
3316 if ((int)(EltIdx / 4) == BestHighQuad)
3321 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3322 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3326 // The other elements are put in the right place using pextrw and pinsrw.
3327 for (unsigned i = 0; i != 8; ++i) {
3330 SDOperand Elt = MaskElts[i];
3331 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3334 SDOperand ExtOp = (EltIdx < 8)
3335 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3336 DAG.getConstant(EltIdx, PtrVT))
3337 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3338 DAG.getConstant(EltIdx - 8, PtrVT));
3339 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3340 DAG.getConstant(i, PtrVT));
3345 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3346 ///as few as possible.
3347 // First, let's find out how many elements are already in the right order.
3348 unsigned V1InOrder = 0;
3349 unsigned V1FromV1 = 0;
3350 unsigned V2InOrder = 0;
3351 unsigned V2FromV2 = 0;
3352 SmallVector<SDOperand, 8> V1Elts;
3353 SmallVector<SDOperand, 8> V2Elts;
3354 for (unsigned i = 0; i < 8; ++i) {
3355 SDOperand Elt = MaskElts[i];
3356 if (Elt.getOpcode() == ISD::UNDEF) {
3357 V1Elts.push_back(Elt);
3358 V2Elts.push_back(Elt);
3363 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3365 V1Elts.push_back(Elt);
3366 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3368 } else if (EltIdx == i+8) {
3369 V1Elts.push_back(Elt);
3370 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3372 } else if (EltIdx < 8) {
3373 V1Elts.push_back(Elt);
3376 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3381 if (V2InOrder > V1InOrder) {
3382 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3384 std::swap(V1Elts, V2Elts);
3385 std::swap(V1FromV1, V2FromV2);
3388 if ((V1FromV1 + V1InOrder) != 8) {
3389 // Some elements are from V2.
3391 // If there are elements that are from V1 but out of place,
3392 // then first sort them in place
3393 SmallVector<SDOperand, 8> MaskVec;
3394 for (unsigned i = 0; i < 8; ++i) {
3395 SDOperand Elt = V1Elts[i];
3396 if (Elt.getOpcode() == ISD::UNDEF) {
3397 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3400 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3402 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3404 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3406 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3407 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3411 for (unsigned i = 0; i < 8; ++i) {
3412 SDOperand Elt = V1Elts[i];
3413 if (Elt.getOpcode() == ISD::UNDEF)
3415 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3418 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3419 DAG.getConstant(EltIdx - 8, PtrVT));
3420 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3421 DAG.getConstant(i, PtrVT));
3425 // All elements are from V1.
3427 for (unsigned i = 0; i < 8; ++i) {
3428 SDOperand Elt = V1Elts[i];
3429 if (Elt.getOpcode() == ISD::UNDEF)
3431 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3432 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3433 DAG.getConstant(EltIdx, PtrVT));
3434 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3435 DAG.getConstant(i, PtrVT));
3441 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3442 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3443 /// done when every pair / quad of shuffle mask elements point to elements in
3444 /// the right sequence. e.g.
3445 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3447 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3449 SDOperand PermMask, SelectionDAG &DAG,
3450 TargetLowering &TLI) {
3451 unsigned NumElems = PermMask.getNumOperands();
3452 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3453 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3454 MVT::ValueType NewVT = MaskVT;
3456 case MVT::v4f32: NewVT = MVT::v2f64; break;
3457 case MVT::v4i32: NewVT = MVT::v2i64; break;
3458 case MVT::v8i16: NewVT = MVT::v4i32; break;
3459 case MVT::v16i8: NewVT = MVT::v4i32; break;
3460 default: assert(false && "Unexpected!");
3463 if (NewWidth == 2) {
3464 if (MVT::isInteger(VT))
3469 unsigned Scale = NumElems / NewWidth;
3470 SmallVector<SDOperand, 8> MaskVec;
3471 for (unsigned i = 0; i < NumElems; i += Scale) {
3472 unsigned StartIdx = ~0U;
3473 for (unsigned j = 0; j < Scale; ++j) {
3474 SDOperand Elt = PermMask.getOperand(i+j);
3475 if (Elt.getOpcode() == ISD::UNDEF)
3477 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3478 if (StartIdx == ~0U)
3479 StartIdx = EltIdx - (EltIdx % Scale);
3480 if (EltIdx != StartIdx + j)
3483 if (StartIdx == ~0U)
3484 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3486 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3489 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3490 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3491 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3492 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3493 &MaskVec[0], MaskVec.size()));
3496 /// getVZextMovL - Return a zero-extending vector move low node.
3498 static SDOperand getVZextMovL(MVT::ValueType VT, MVT::ValueType OpVT,
3499 SDOperand SrcOp, SelectionDAG &DAG,
3500 const X86Subtarget *Subtarget) {
3501 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3502 LoadSDNode *LD = NULL;
3503 if (!isScalarLoadToVector(SrcOp.Val, &LD))
3504 LD = dyn_cast<LoadSDNode>(SrcOp);
3506 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3508 MVT::ValueType EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3509 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3510 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3511 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3512 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3514 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3515 return DAG.getNode(ISD::BIT_CONVERT, VT,
3516 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3517 DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3518 SrcOp.getOperand(0).getOperand(0))));
3523 return DAG.getNode(ISD::BIT_CONVERT, VT,
3524 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3525 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3529 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3530 SDOperand V1 = Op.getOperand(0);
3531 SDOperand V2 = Op.getOperand(1);
3532 SDOperand PermMask = Op.getOperand(2);
3533 MVT::ValueType VT = Op.getValueType();
3534 unsigned NumElems = PermMask.getNumOperands();
3535 bool isMMX = MVT::getSizeInBits(VT) == 64;
3536 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3537 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3538 bool V1IsSplat = false;
3539 bool V2IsSplat = false;
3541 if (isUndefShuffle(Op.Val))
3542 return DAG.getNode(ISD::UNDEF, VT);
3544 if (isZeroShuffle(Op.Val))
3545 return getZeroVector(VT, DAG);
3547 if (isIdentityMask(PermMask.Val))
3549 else if (isIdentityMask(PermMask.Val, true))
3552 if (isSplatMask(PermMask.Val)) {
3553 if (isMMX || NumElems < 4) return Op;
3554 // Promote it to a v4{if}32 splat.
3555 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3558 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3560 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3561 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3563 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3564 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3565 // FIXME: Figure out a cleaner way to do this.
3566 // Try to make use of movq to zero out the top part.
3567 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3568 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3571 SDOperand NewV1 = NewOp.getOperand(0);
3572 SDOperand NewV2 = NewOp.getOperand(1);
3573 SDOperand NewMask = NewOp.getOperand(2);
3574 if (isCommutedMOVL(NewMask.Val, true, false)) {
3575 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3576 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
3579 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3580 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3582 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3583 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3588 if (X86::isMOVLMask(PermMask.Val)) {
3591 if (ISD::isBuildVectorAllZeros(V1.Val))
3592 return getVZextMovL(VT, VT, V2, DAG, Subtarget);
3596 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3597 X86::isMOVSLDUPMask(PermMask.Val) ||
3598 X86::isMOVHLPSMask(PermMask.Val) ||
3599 X86::isMOVHPMask(PermMask.Val) ||
3600 X86::isMOVLPMask(PermMask.Val))
3603 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3604 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3605 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3607 bool Commuted = false;
3608 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3609 // 1,1,1,1 -> v8i16 though.
3610 V1IsSplat = isSplatVector(V1.Val);
3611 V2IsSplat = isSplatVector(V2.Val);
3613 // Canonicalize the splat or undef, if present, to be on the RHS.
3614 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3615 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3616 std::swap(V1IsSplat, V2IsSplat);
3617 std::swap(V1IsUndef, V2IsUndef);
3621 // FIXME: Figure out a cleaner way to do this.
3622 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3623 if (V2IsUndef) return V1;
3624 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3626 // V2 is a splat, so the mask may be malformed. That is, it may point
3627 // to any V2 element. The instruction selectior won't like this. Get
3628 // a corrected mask and commute to form a proper MOVS{S|D}.
3629 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3630 if (NewMask.Val != PermMask.Val)
3631 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3636 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3637 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3638 X86::isUNPCKLMask(PermMask.Val) ||
3639 X86::isUNPCKHMask(PermMask.Val))
3643 // Normalize mask so all entries that point to V2 points to its first
3644 // element then try to match unpck{h|l} again. If match, return a
3645 // new vector_shuffle with the corrected mask.
3646 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3647 if (NewMask.Val != PermMask.Val) {
3648 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3649 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3650 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3651 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3652 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3653 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3658 // Normalize the node to match x86 shuffle ops if needed
3659 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3660 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3663 // Commute is back and try unpck* again.
3664 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3665 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3666 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3667 X86::isUNPCKLMask(PermMask.Val) ||
3668 X86::isUNPCKHMask(PermMask.Val))
3672 // Try PSHUF* first, then SHUFP*.
3673 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
3674 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3675 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.Val)) {
3676 if (V2.getOpcode() != ISD::UNDEF)
3677 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3678 DAG.getNode(ISD::UNDEF, VT), PermMask);
3683 if (Subtarget->hasSSE2() &&
3684 (X86::isPSHUFDMask(PermMask.Val) ||
3685 X86::isPSHUFHWMask(PermMask.Val) ||
3686 X86::isPSHUFLWMask(PermMask.Val))) {
3687 MVT::ValueType RVT = VT;
3688 if (VT == MVT::v4f32) {
3690 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
3691 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
3692 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3693 } else if (V2.getOpcode() != ISD::UNDEF)
3694 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
3695 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3697 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
3701 // Binary or unary shufps.
3702 if (X86::isSHUFPMask(PermMask.Val) ||
3703 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.Val)))
3707 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3708 if (VT == MVT::v8i16) {
3709 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3714 // Handle all 4 wide cases with a number of shuffles.
3715 if (NumElems == 4 && !isMMX) {
3716 // Don't do this for MMX.
3717 MVT::ValueType MaskVT = PermMask.getValueType();
3718 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3719 SmallVector<std::pair<int, int>, 8> Locs;
3720 Locs.reserve(NumElems);
3721 SmallVector<SDOperand, 8> Mask1(NumElems,
3722 DAG.getNode(ISD::UNDEF, MaskEVT));
3723 SmallVector<SDOperand, 8> Mask2(NumElems,
3724 DAG.getNode(ISD::UNDEF, MaskEVT));
3727 // If no more than two elements come from either vector. This can be
3728 // implemented with two shuffles. First shuffle gather the elements.
3729 // The second shuffle, which takes the first shuffle as both of its
3730 // vector operands, put the elements into the right order.
3731 for (unsigned i = 0; i != NumElems; ++i) {
3732 SDOperand Elt = PermMask.getOperand(i);
3733 if (Elt.getOpcode() == ISD::UNDEF) {
3734 Locs[i] = std::make_pair(-1, -1);
3736 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3737 if (Val < NumElems) {
3738 Locs[i] = std::make_pair(0, NumLo);
3742 Locs[i] = std::make_pair(1, NumHi);
3743 if (2+NumHi < NumElems)
3744 Mask1[2+NumHi] = Elt;
3749 if (NumLo <= 2 && NumHi <= 2) {
3750 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3751 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3752 &Mask1[0], Mask1.size()));
3753 for (unsigned i = 0; i != NumElems; ++i) {
3754 if (Locs[i].first == -1)
3757 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3758 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3759 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3763 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3764 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3765 &Mask2[0], Mask2.size()));
3768 // Break it into (shuffle shuffle_hi, shuffle_lo).
3770 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3771 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3772 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3773 unsigned MaskIdx = 0;
3775 unsigned HiIdx = NumElems/2;
3776 for (unsigned i = 0; i != NumElems; ++i) {
3777 if (i == NumElems/2) {
3783 SDOperand Elt = PermMask.getOperand(i);
3784 if (Elt.getOpcode() == ISD::UNDEF) {
3785 Locs[i] = std::make_pair(-1, -1);
3786 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3787 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3788 (*MaskPtr)[LoIdx] = Elt;
3791 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3792 (*MaskPtr)[HiIdx] = Elt;
3797 SDOperand LoShuffle =
3798 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3799 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3800 &LoMask[0], LoMask.size()));
3801 SDOperand HiShuffle =
3802 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3803 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3804 &HiMask[0], HiMask.size()));
3805 SmallVector<SDOperand, 8> MaskOps;
3806 for (unsigned i = 0; i != NumElems; ++i) {
3807 if (Locs[i].first == -1) {
3808 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3810 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3811 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3814 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3815 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3816 &MaskOps[0], MaskOps.size()));
3823 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3824 SelectionDAG &DAG) {
3825 MVT::ValueType VT = Op.getValueType();
3826 if (MVT::getSizeInBits(VT) == 8) {
3827 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3828 Op.getOperand(0), Op.getOperand(1));
3829 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3830 DAG.getValueType(VT));
3831 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3832 } else if (MVT::getSizeInBits(VT) == 16) {
3833 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3834 Op.getOperand(0), Op.getOperand(1));
3835 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3836 DAG.getValueType(VT));
3837 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3838 } else if (VT == MVT::f32) {
3839 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
3840 // the result back to FR32 register. It's only worth matching if the
3841 // result has a single use which is a store or a bitcast to i32.
3842 if (!Op.hasOneUse())
3844 SDNode *User = Op.Val->use_begin()->getUser();
3845 if (User->getOpcode() != ISD::STORE &&
3846 (User->getOpcode() != ISD::BIT_CONVERT ||
3847 User->getValueType(0) != MVT::i32))
3849 SDOperand Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3850 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
3852 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
3859 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3860 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3863 if (Subtarget->hasSSE41()) {
3864 SDOperand Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3869 MVT::ValueType VT = Op.getValueType();
3870 // TODO: handle v16i8.
3871 if (MVT::getSizeInBits(VT) == 16) {
3872 SDOperand Vec = Op.getOperand(0);
3873 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3875 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3876 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3877 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3879 // Transform it so it match pextrw which produces a 32-bit result.
3880 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3881 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3882 Op.getOperand(0), Op.getOperand(1));
3883 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3884 DAG.getValueType(VT));
3885 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3886 } else if (MVT::getSizeInBits(VT) == 32) {
3887 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3890 // SHUFPS the element to the lowest double word, then movss.
3891 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3892 SmallVector<SDOperand, 8> IdxVec;
3894 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3896 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3898 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3900 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3901 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3902 &IdxVec[0], IdxVec.size());
3903 SDOperand Vec = Op.getOperand(0);
3904 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3905 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3906 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3907 DAG.getIntPtrConstant(0));
3908 } else if (MVT::getSizeInBits(VT) == 64) {
3909 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3910 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3911 // to match extract_elt for f64.
3912 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3916 // UNPCKHPD the element to the lowest double word, then movsd.
3917 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3918 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3919 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3920 SmallVector<SDOperand, 8> IdxVec;
3921 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3923 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3924 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3925 &IdxVec[0], IdxVec.size());
3926 SDOperand Vec = Op.getOperand(0);
3927 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3928 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3929 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3930 DAG.getIntPtrConstant(0));
3937 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3938 MVT::ValueType VT = Op.getValueType();
3939 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3941 SDOperand N0 = Op.getOperand(0);
3942 SDOperand N1 = Op.getOperand(1);
3943 SDOperand N2 = Op.getOperand(2);
3945 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3946 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3948 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3950 if (N1.getValueType() != MVT::i32)
3951 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3952 if (N2.getValueType() != MVT::i32)
3953 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3954 return DAG.getNode(Opc, VT, N0, N1, N2);
3955 } else if (EVT == MVT::f32) {
3956 // Bits [7:6] of the constant are the source select. This will always be
3957 // zero here. The DAG Combiner may combine an extract_elt index into these
3958 // bits. For example (insert (extract, 3), 2) could be matched by putting
3959 // the '3' into bits [7:6] of X86ISD::INSERTPS.
3960 // Bits [5:4] of the constant are the destination select. This is the
3961 // value of the incoming immediate.
3962 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
3963 // combine either bitwise AND or insert of float 0.0 to set these bits.
3964 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3965 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3971 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3972 MVT::ValueType VT = Op.getValueType();
3973 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3975 if (Subtarget->hasSSE41())
3976 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3981 SDOperand N0 = Op.getOperand(0);
3982 SDOperand N1 = Op.getOperand(1);
3983 SDOperand N2 = Op.getOperand(2);
3985 if (MVT::getSizeInBits(EVT) == 16) {
3986 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3987 // as its second argument.
3988 if (N1.getValueType() != MVT::i32)
3989 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3990 if (N2.getValueType() != MVT::i32)
3991 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3992 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3998 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3999 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4000 MVT::ValueType VT = MVT::v2i32;
4001 switch (Op.getValueType()) {
4008 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4009 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4012 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4013 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4014 // one of the above mentioned nodes. It has to be wrapped because otherwise
4015 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4016 // be used to form addressing mode. These wrapped nodes will be selected
4019 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
4020 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4021 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
4023 CP->getAlignment());
4024 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4025 // With PIC, the address is actually $g + Offset.
4026 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4027 !Subtarget->isPICStyleRIPRel()) {
4028 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4029 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4037 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4038 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4039 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4040 // If it's a debug information descriptor, don't mess with it.
4041 if (DAG.isVerifiedDebugInfoDesc(Op))
4043 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4044 // With PIC, the address is actually $g + Offset.
4045 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4046 !Subtarget->isPICStyleRIPRel()) {
4047 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4048 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4052 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4053 // load the value at address GV, not the value of GV itself. This means that
4054 // the GlobalAddress must be in the base or index register of the address, not
4055 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4056 // The same applies for external symbols during PIC codegen
4057 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4058 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4059 PseudoSourceValue::getGOT(), 0);
4064 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4066 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4067 const MVT::ValueType PtrVT) {
4069 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4070 DAG.getNode(X86ISD::GlobalBaseReg,
4072 InFlag = Chain.getValue(1);
4074 // emit leal symbol@TLSGD(,%ebx,1), %eax
4075 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4076 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4077 GA->getValueType(0),
4079 SDOperand Ops[] = { Chain, TGA, InFlag };
4080 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4081 InFlag = Result.getValue(2);
4082 Chain = Result.getValue(1);
4084 // call ___tls_get_addr. This function receives its argument in
4085 // the register EAX.
4086 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4087 InFlag = Chain.getValue(1);
4089 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4090 SDOperand Ops1[] = { Chain,
4091 DAG.getTargetExternalSymbol("___tls_get_addr",
4093 DAG.getRegister(X86::EAX, PtrVT),
4094 DAG.getRegister(X86::EBX, PtrVT),
4096 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4097 InFlag = Chain.getValue(1);
4099 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4102 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4104 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4105 const MVT::ValueType PtrVT) {
4106 SDOperand InFlag, Chain;
4108 // emit leaq symbol@TLSGD(%rip), %rdi
4109 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4110 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4111 GA->getValueType(0),
4113 SDOperand Ops[] = { DAG.getEntryNode(), TGA};
4114 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4115 Chain = Result.getValue(1);
4116 InFlag = Result.getValue(2);
4118 // call ___tls_get_addr. This function receives its argument in
4119 // the register RDI.
4120 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4121 InFlag = Chain.getValue(1);
4123 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4124 SDOperand Ops1[] = { Chain,
4125 DAG.getTargetExternalSymbol("___tls_get_addr",
4127 DAG.getRegister(X86::RDI, PtrVT),
4129 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4130 InFlag = Chain.getValue(1);
4132 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4135 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4136 // "local exec" model.
4138 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4139 const MVT::ValueType PtrVT) {
4140 // Get the Thread Pointer
4141 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4142 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4144 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4145 GA->getValueType(0),
4147 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4149 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4150 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4151 PseudoSourceValue::getGOT(), 0);
4153 // The address of the thread local variable is the add of the thread
4154 // pointer with the offset of the variable.
4155 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4159 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4160 // TODO: implement the "local dynamic" model
4161 // TODO: implement the "initial exec"model for pic executables
4162 assert(Subtarget->isTargetELF() &&
4163 "TLS not implemented for non-ELF targets");
4164 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4165 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4166 // otherwise use the "Local Exec"TLS Model
4167 if (Subtarget->is64Bit()) {
4168 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4170 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4171 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4173 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4178 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4179 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4180 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4181 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4182 // With PIC, the address is actually $g + Offset.
4183 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4184 !Subtarget->isPICStyleRIPRel()) {
4185 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4186 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4193 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4194 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4195 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4196 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4197 // With PIC, the address is actually $g + Offset.
4198 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4199 !Subtarget->isPICStyleRIPRel()) {
4200 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4201 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4208 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4209 /// take a 2 x i32 value to shift plus a shift amount.
4210 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4211 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4212 MVT::ValueType VT = Op.getValueType();
4213 unsigned VTBits = MVT::getSizeInBits(VT);
4214 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4215 SDOperand ShOpLo = Op.getOperand(0);
4216 SDOperand ShOpHi = Op.getOperand(1);
4217 SDOperand ShAmt = Op.getOperand(2);
4218 SDOperand Tmp1 = isSRA ?
4219 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4220 DAG.getConstant(0, VT);
4222 SDOperand Tmp2, Tmp3;
4223 if (Op.getOpcode() == ISD::SHL_PARTS) {
4224 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4225 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4227 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4228 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4231 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4232 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4233 DAG.getConstant(VTBits, MVT::i8));
4234 SDOperand Cond = DAG.getNode(X86ISD::CMP, VT,
4235 AndNode, DAG.getConstant(0, MVT::i8));
4238 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4239 VTs = DAG.getNodeValueTypes(VT, MVT::Flag);
4240 SmallVector<SDOperand, 4> Ops;
4241 if (Op.getOpcode() == ISD::SHL_PARTS) {
4242 Ops.push_back(Tmp2);
4243 Ops.push_back(Tmp3);
4245 Ops.push_back(Cond);
4246 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4249 Ops.push_back(Tmp3);
4250 Ops.push_back(Tmp1);
4252 Ops.push_back(Cond);
4253 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4255 Ops.push_back(Tmp2);
4256 Ops.push_back(Tmp3);
4258 Ops.push_back(Cond);
4259 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4262 Ops.push_back(Tmp3);
4263 Ops.push_back(Tmp1);
4265 Ops.push_back(Cond);
4266 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4269 VTs = DAG.getNodeValueTypes(VT, VT);
4273 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4276 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4277 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4278 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
4279 "Unknown SINT_TO_FP to lower!");
4281 // These are really Legal; caller falls through into that case.
4282 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4284 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4285 Subtarget->is64Bit())
4288 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4289 MachineFunction &MF = DAG.getMachineFunction();
4290 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4291 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4292 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4294 PseudoSourceValue::getFixedStack(),
4299 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4301 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4303 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4304 SmallVector<SDOperand, 8> Ops;
4305 Ops.push_back(Chain);
4306 Ops.push_back(StackSlot);
4307 Ops.push_back(DAG.getValueType(SrcVT));
4308 SDOperand Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4309 Tys, &Ops[0], Ops.size());
4312 Chain = Result.getValue(1);
4313 SDOperand InFlag = Result.getValue(2);
4315 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4316 // shouldn't be necessary except that RFP cannot be live across
4317 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4318 MachineFunction &MF = DAG.getMachineFunction();
4319 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4320 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4321 Tys = DAG.getVTList(MVT::Other);
4322 SmallVector<SDOperand, 8> Ops;
4323 Ops.push_back(Chain);
4324 Ops.push_back(Result);
4325 Ops.push_back(StackSlot);
4326 Ops.push_back(DAG.getValueType(Op.getValueType()));
4327 Ops.push_back(InFlag);
4328 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4329 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4330 PseudoSourceValue::getFixedStack(), SSFI);
4336 std::pair<SDOperand,SDOperand> X86TargetLowering::
4337 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4338 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4339 "Unknown FP_TO_SINT to lower!");
4341 // These are really Legal.
4342 if (Op.getValueType() == MVT::i32 &&
4343 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4344 return std::make_pair(SDOperand(), SDOperand());
4345 if (Subtarget->is64Bit() &&
4346 Op.getValueType() == MVT::i64 &&
4347 Op.getOperand(0).getValueType() != MVT::f80)
4348 return std::make_pair(SDOperand(), SDOperand());
4350 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4352 MachineFunction &MF = DAG.getMachineFunction();
4353 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4354 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4355 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4357 switch (Op.getValueType()) {
4358 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4359 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4360 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4361 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4364 SDOperand Chain = DAG.getEntryNode();
4365 SDOperand Value = Op.getOperand(0);
4366 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4367 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4368 Chain = DAG.getStore(Chain, Value, StackSlot,
4369 PseudoSourceValue::getFixedStack(), SSFI);
4370 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4372 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4374 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4375 Chain = Value.getValue(1);
4376 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4377 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4380 // Build the FP_TO_INT*_IN_MEM
4381 SDOperand Ops[] = { Chain, Value, StackSlot };
4382 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4384 return std::make_pair(FIST, StackSlot);
4387 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4388 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4389 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4390 if (FIST.Val == 0) return SDOperand();
4393 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4396 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4397 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4398 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4399 if (FIST.Val == 0) return 0;
4401 // Return an i64 load from the stack slot.
4402 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4404 // Use a MERGE_VALUES node to drop the chain result value.
4405 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4408 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4409 MVT::ValueType VT = Op.getValueType();
4410 MVT::ValueType EltVT = VT;
4411 if (MVT::isVector(VT))
4412 EltVT = MVT::getVectorElementType(VT);
4413 std::vector<Constant*> CV;
4414 if (EltVT == MVT::f64) {
4415 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4419 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4425 Constant *C = ConstantVector::get(CV);
4426 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4427 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4428 PseudoSourceValue::getConstantPool(), 0,
4430 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4433 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4434 MVT::ValueType VT = Op.getValueType();
4435 MVT::ValueType EltVT = VT;
4436 unsigned EltNum = 1;
4437 if (MVT::isVector(VT)) {
4438 EltVT = MVT::getVectorElementType(VT);
4439 EltNum = MVT::getVectorNumElements(VT);
4441 std::vector<Constant*> CV;
4442 if (EltVT == MVT::f64) {
4443 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4447 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4453 Constant *C = ConstantVector::get(CV);
4454 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4455 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4456 PseudoSourceValue::getConstantPool(), 0,
4458 if (MVT::isVector(VT)) {
4459 return DAG.getNode(ISD::BIT_CONVERT, VT,
4460 DAG.getNode(ISD::XOR, MVT::v2i64,
4461 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4462 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4464 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4468 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4469 SDOperand Op0 = Op.getOperand(0);
4470 SDOperand Op1 = Op.getOperand(1);
4471 MVT::ValueType VT = Op.getValueType();
4472 MVT::ValueType SrcVT = Op1.getValueType();
4474 // If second operand is smaller, extend it first.
4475 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4476 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4479 // And if it is bigger, shrink it first.
4480 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4481 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4485 // At this point the operands and the result should have the same
4486 // type, and that won't be f80 since that is not custom lowered.
4488 // First get the sign bit of second operand.
4489 std::vector<Constant*> CV;
4490 if (SrcVT == MVT::f64) {
4491 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4492 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4494 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4495 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4496 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4497 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4499 Constant *C = ConstantVector::get(CV);
4500 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4501 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4502 PseudoSourceValue::getConstantPool(), 0,
4504 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4506 // Shift sign bit right or left if the two operands have different types.
4507 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4508 // Op0 is MVT::f32, Op1 is MVT::f64.
4509 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4510 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4511 DAG.getConstant(32, MVT::i32));
4512 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4513 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4514 DAG.getIntPtrConstant(0));
4517 // Clear first operand sign bit.
4519 if (VT == MVT::f64) {
4520 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4521 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4523 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4524 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4525 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4526 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4528 C = ConstantVector::get(CV);
4529 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4530 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4531 PseudoSourceValue::getConstantPool(), 0,
4533 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4535 // Or the value with the sign bit.
4536 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4539 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4540 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4542 SDOperand Op0 = Op.getOperand(0);
4543 SDOperand Op1 = Op.getOperand(1);
4544 SDOperand CC = Op.getOperand(2);
4545 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4546 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4549 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4551 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4552 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4553 DAG.getConstant(X86CC, MVT::i8), Cond);
4556 assert(isFP && "Illegal integer SetCC!");
4558 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4559 switch (SetCCOpcode) {
4560 default: assert(false && "Illegal floating point SetCC!");
4561 case ISD::SETOEQ: { // !PF & ZF
4562 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4563 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4564 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4565 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4566 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4568 case ISD::SETUNE: { // PF | !ZF
4569 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4570 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4571 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4572 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4573 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4579 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4580 bool addTest = true;
4581 SDOperand Cond = Op.getOperand(0);
4584 if (Cond.getOpcode() == ISD::SETCC)
4585 Cond = LowerSETCC(Cond, DAG);
4587 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4588 // setting operand in place of the X86ISD::SETCC.
4589 if (Cond.getOpcode() == X86ISD::SETCC) {
4590 CC = Cond.getOperand(0);
4592 SDOperand Cmp = Cond.getOperand(1);
4593 unsigned Opc = Cmp.getOpcode();
4594 MVT::ValueType VT = Op.getValueType();
4596 bool IllegalFPCMov = false;
4597 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4598 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4599 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4601 if ((Opc == X86ISD::CMP ||
4602 Opc == X86ISD::COMI ||
4603 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4610 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4611 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4614 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4616 SmallVector<SDOperand, 4> Ops;
4617 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4618 // condition is true.
4619 Ops.push_back(Op.getOperand(2));
4620 Ops.push_back(Op.getOperand(1));
4622 Ops.push_back(Cond);
4623 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4626 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4627 bool addTest = true;
4628 SDOperand Chain = Op.getOperand(0);
4629 SDOperand Cond = Op.getOperand(1);
4630 SDOperand Dest = Op.getOperand(2);
4633 if (Cond.getOpcode() == ISD::SETCC)
4634 Cond = LowerSETCC(Cond, DAG);
4636 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4637 // setting operand in place of the X86ISD::SETCC.
4638 if (Cond.getOpcode() == X86ISD::SETCC) {
4639 CC = Cond.getOperand(0);
4641 SDOperand Cmp = Cond.getOperand(1);
4642 unsigned Opc = Cmp.getOpcode();
4643 if (Opc == X86ISD::CMP ||
4644 Opc == X86ISD::COMI ||
4645 Opc == X86ISD::UCOMI) {
4652 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4653 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4655 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4656 Chain, Op.getOperand(2), CC, Cond);
4660 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4661 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4662 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4663 // that the guard pages used by the OS virtual memory manager are allocated in
4664 // correct sequence.
4666 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4667 SelectionDAG &DAG) {
4668 assert(Subtarget->isTargetCygMing() &&
4669 "This should be used only on Cygwin/Mingw targets");
4672 SDOperand Chain = Op.getOperand(0);
4673 SDOperand Size = Op.getOperand(1);
4674 // FIXME: Ensure alignment here
4678 MVT::ValueType IntPtr = getPointerTy();
4679 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4681 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4682 Flag = Chain.getValue(1);
4684 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4685 SDOperand Ops[] = { Chain,
4686 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4687 DAG.getRegister(X86::EAX, IntPtr),
4689 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4690 Flag = Chain.getValue(1);
4692 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4694 std::vector<MVT::ValueType> Tys;
4695 Tys.push_back(SPTy);
4696 Tys.push_back(MVT::Other);
4697 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4698 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4702 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
4704 SDOperand Dst, SDOperand Src,
4705 SDOperand Size, unsigned Align,
4706 const Value *DstSV, uint64_t DstSVOff) {
4707 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4709 /// If not DWORD aligned or size is more than the threshold, call the library.
4710 /// The libc version is likely to be faster for these cases. It can use the
4711 /// address value and run time information about the CPU.
4712 if ((Align & 3) == 0 ||
4714 ConstantSize->getValue() > getSubtarget()->getMaxInlineSizeThreshold()) {
4715 SDOperand InFlag(0, 0);
4717 // Check to see if there is a specialized entry-point for memory zeroing.
4718 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
4719 if (const char *bzeroEntry =
4720 V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
4721 MVT::ValueType IntPtr = getPointerTy();
4722 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4723 TargetLowering::ArgListTy Args;
4724 TargetLowering::ArgListEntry Entry;
4726 Entry.Ty = IntPtrTy;
4727 Args.push_back(Entry);
4729 Args.push_back(Entry);
4730 std::pair<SDOperand,SDOperand> CallResult =
4731 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4732 false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
4734 return CallResult.second;
4737 // Otherwise have the target-independent code call memset.
4741 uint64_t SizeVal = ConstantSize->getValue();
4742 SDOperand InFlag(0, 0);
4745 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
4746 unsigned BytesLeft = 0;
4747 bool TwoRepStos = false;
4750 uint64_t Val = ValC->getValue() & 255;
4752 // If the value is a constant, then we can potentially use larger sets.
4753 switch (Align & 3) {
4754 case 2: // WORD aligned
4757 Val = (Val << 8) | Val;
4759 case 0: // DWORD aligned
4762 Val = (Val << 8) | Val;
4763 Val = (Val << 16) | Val;
4764 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
4767 Val = (Val << 32) | Val;
4770 default: // Byte aligned
4773 Count = DAG.getIntPtrConstant(SizeVal);
4777 if (AVT > MVT::i8) {
4778 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4779 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
4780 BytesLeft = SizeVal % UBytes;
4783 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4785 InFlag = Chain.getValue(1);
4788 Count = DAG.getIntPtrConstant(SizeVal);
4789 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
4790 InFlag = Chain.getValue(1);
4793 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4795 InFlag = Chain.getValue(1);
4796 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4798 InFlag = Chain.getValue(1);
4800 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4801 SmallVector<SDOperand, 8> Ops;
4802 Ops.push_back(Chain);
4803 Ops.push_back(DAG.getValueType(AVT));
4804 Ops.push_back(InFlag);
4805 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4808 InFlag = Chain.getValue(1);
4810 MVT::ValueType CVT = Count.getValueType();
4811 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4812 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4813 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4815 InFlag = Chain.getValue(1);
4816 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4818 Ops.push_back(Chain);
4819 Ops.push_back(DAG.getValueType(MVT::i8));
4820 Ops.push_back(InFlag);
4821 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4822 } else if (BytesLeft) {
4823 // Handle the last 1 - 7 bytes.
4824 unsigned Offset = SizeVal - BytesLeft;
4825 MVT::ValueType AddrVT = Dst.getValueType();
4826 MVT::ValueType SizeVT = Size.getValueType();
4828 Chain = DAG.getMemset(Chain,
4829 DAG.getNode(ISD::ADD, AddrVT, Dst,
4830 DAG.getConstant(Offset, AddrVT)),
4832 DAG.getConstant(BytesLeft, SizeVT),
4833 Align, DstSV, DstSVOff + Offset);
4836 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
4841 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
4843 SDOperand Dst, SDOperand Src,
4844 SDOperand Size, unsigned Align,
4846 const Value *DstSV, uint64_t DstSVOff,
4847 const Value *SrcSV, uint64_t SrcSVOff){
4849 // This requires the copy size to be a constant, preferrably
4850 // within a subtarget-specific limit.
4851 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4854 uint64_t SizeVal = ConstantSize->getValue();
4855 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
4859 unsigned BytesLeft = 0;
4860 if (Align >= 8 && Subtarget->is64Bit())
4862 else if (Align >= 4)
4864 else if (Align >= 2)
4869 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4870 unsigned CountVal = SizeVal / UBytes;
4871 SDOperand Count = DAG.getIntPtrConstant(CountVal);
4872 BytesLeft = SizeVal % UBytes;
4874 SDOperand InFlag(0, 0);
4875 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4877 InFlag = Chain.getValue(1);
4878 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4880 InFlag = Chain.getValue(1);
4881 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4883 InFlag = Chain.getValue(1);
4885 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4886 SmallVector<SDOperand, 8> Ops;
4887 Ops.push_back(Chain);
4888 Ops.push_back(DAG.getValueType(AVT));
4889 Ops.push_back(InFlag);
4890 SDOperand RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4892 SmallVector<SDOperand, 4> Results;
4893 Results.push_back(RepMovs);
4895 // Handle the last 1 - 7 bytes.
4896 unsigned Offset = SizeVal - BytesLeft;
4897 MVT::ValueType DstVT = Dst.getValueType();
4898 MVT::ValueType SrcVT = Src.getValueType();
4899 MVT::ValueType SizeVT = Size.getValueType();
4900 Results.push_back(DAG.getMemcpy(Chain,
4901 DAG.getNode(ISD::ADD, DstVT, Dst,
4902 DAG.getConstant(Offset, DstVT)),
4903 DAG.getNode(ISD::ADD, SrcVT, Src,
4904 DAG.getConstant(Offset, SrcVT)),
4905 DAG.getConstant(BytesLeft, SizeVT),
4906 Align, AlwaysInline,
4907 DstSV, DstSVOff + Offset,
4908 SrcSV, SrcSVOff + Offset));
4911 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
4914 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4915 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4916 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4917 SDOperand TheChain = N->getOperand(0);
4918 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4919 if (Subtarget->is64Bit()) {
4920 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4921 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4922 MVT::i64, rax.getValue(2));
4923 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4924 DAG.getConstant(32, MVT::i8));
4926 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4929 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4930 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4933 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4934 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4935 MVT::i32, eax.getValue(2));
4936 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4937 SDOperand Ops[] = { eax, edx };
4938 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4940 // Use a MERGE_VALUES to return the value and chain.
4941 Ops[1] = edx.getValue(1);
4942 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4943 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4946 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4947 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4949 if (!Subtarget->is64Bit()) {
4950 // vastart just stores the address of the VarArgsFrameIndex slot into the
4951 // memory location argument.
4952 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4953 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4957 // gp_offset (0 - 6 * 8)
4958 // fp_offset (48 - 48 + 8 * 16)
4959 // overflow_arg_area (point to parameters coming in memory).
4961 SmallVector<SDOperand, 8> MemOps;
4962 SDOperand FIN = Op.getOperand(1);
4964 SDOperand Store = DAG.getStore(Op.getOperand(0),
4965 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4967 MemOps.push_back(Store);
4970 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4971 Store = DAG.getStore(Op.getOperand(0),
4972 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4974 MemOps.push_back(Store);
4976 // Store ptr to overflow_arg_area
4977 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4978 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4979 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4980 MemOps.push_back(Store);
4982 // Store ptr to reg_save_area.
4983 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4984 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4985 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4986 MemOps.push_back(Store);
4987 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4990 SDOperand X86TargetLowering::LowerVAARG(SDOperand Op, SelectionDAG &DAG) {
4991 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4992 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
4993 SDOperand Chain = Op.getOperand(0);
4994 SDOperand SrcPtr = Op.getOperand(1);
4995 SDOperand SrcSV = Op.getOperand(2);
4997 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5002 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
5003 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5004 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5005 SDOperand Chain = Op.getOperand(0);
5006 SDOperand DstPtr = Op.getOperand(1);
5007 SDOperand SrcPtr = Op.getOperand(2);
5008 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5009 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5011 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5012 DAG.getIntPtrConstant(24), 8, false,
5013 DstSV, 0, SrcSV, 0);
5017 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5018 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5020 default: return SDOperand(); // Don't custom lower most intrinsics.
5021 // Comparison intrinsics.
5022 case Intrinsic::x86_sse_comieq_ss:
5023 case Intrinsic::x86_sse_comilt_ss:
5024 case Intrinsic::x86_sse_comile_ss:
5025 case Intrinsic::x86_sse_comigt_ss:
5026 case Intrinsic::x86_sse_comige_ss:
5027 case Intrinsic::x86_sse_comineq_ss:
5028 case Intrinsic::x86_sse_ucomieq_ss:
5029 case Intrinsic::x86_sse_ucomilt_ss:
5030 case Intrinsic::x86_sse_ucomile_ss:
5031 case Intrinsic::x86_sse_ucomigt_ss:
5032 case Intrinsic::x86_sse_ucomige_ss:
5033 case Intrinsic::x86_sse_ucomineq_ss:
5034 case Intrinsic::x86_sse2_comieq_sd:
5035 case Intrinsic::x86_sse2_comilt_sd:
5036 case Intrinsic::x86_sse2_comile_sd:
5037 case Intrinsic::x86_sse2_comigt_sd:
5038 case Intrinsic::x86_sse2_comige_sd:
5039 case Intrinsic::x86_sse2_comineq_sd:
5040 case Intrinsic::x86_sse2_ucomieq_sd:
5041 case Intrinsic::x86_sse2_ucomilt_sd:
5042 case Intrinsic::x86_sse2_ucomile_sd:
5043 case Intrinsic::x86_sse2_ucomigt_sd:
5044 case Intrinsic::x86_sse2_ucomige_sd:
5045 case Intrinsic::x86_sse2_ucomineq_sd: {
5047 ISD::CondCode CC = ISD::SETCC_INVALID;
5050 case Intrinsic::x86_sse_comieq_ss:
5051 case Intrinsic::x86_sse2_comieq_sd:
5055 case Intrinsic::x86_sse_comilt_ss:
5056 case Intrinsic::x86_sse2_comilt_sd:
5060 case Intrinsic::x86_sse_comile_ss:
5061 case Intrinsic::x86_sse2_comile_sd:
5065 case Intrinsic::x86_sse_comigt_ss:
5066 case Intrinsic::x86_sse2_comigt_sd:
5070 case Intrinsic::x86_sse_comige_ss:
5071 case Intrinsic::x86_sse2_comige_sd:
5075 case Intrinsic::x86_sse_comineq_ss:
5076 case Intrinsic::x86_sse2_comineq_sd:
5080 case Intrinsic::x86_sse_ucomieq_ss:
5081 case Intrinsic::x86_sse2_ucomieq_sd:
5082 Opc = X86ISD::UCOMI;
5085 case Intrinsic::x86_sse_ucomilt_ss:
5086 case Intrinsic::x86_sse2_ucomilt_sd:
5087 Opc = X86ISD::UCOMI;
5090 case Intrinsic::x86_sse_ucomile_ss:
5091 case Intrinsic::x86_sse2_ucomile_sd:
5092 Opc = X86ISD::UCOMI;
5095 case Intrinsic::x86_sse_ucomigt_ss:
5096 case Intrinsic::x86_sse2_ucomigt_sd:
5097 Opc = X86ISD::UCOMI;
5100 case Intrinsic::x86_sse_ucomige_ss:
5101 case Intrinsic::x86_sse2_ucomige_sd:
5102 Opc = X86ISD::UCOMI;
5105 case Intrinsic::x86_sse_ucomineq_ss:
5106 case Intrinsic::x86_sse2_ucomineq_sd:
5107 Opc = X86ISD::UCOMI;
5113 SDOperand LHS = Op.getOperand(1);
5114 SDOperand RHS = Op.getOperand(2);
5115 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5117 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5118 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5119 DAG.getConstant(X86CC, MVT::i8), Cond);
5120 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5123 // Fix vector shift instructions where the last operand is a non-immediate
5125 case Intrinsic::x86_sse2_pslli_w:
5126 case Intrinsic::x86_sse2_pslli_d:
5127 case Intrinsic::x86_sse2_pslli_q:
5128 case Intrinsic::x86_sse2_psrli_w:
5129 case Intrinsic::x86_sse2_psrli_d:
5130 case Intrinsic::x86_sse2_psrli_q:
5131 case Intrinsic::x86_sse2_psrai_w:
5132 case Intrinsic::x86_sse2_psrai_d:
5133 case Intrinsic::x86_mmx_pslli_w:
5134 case Intrinsic::x86_mmx_pslli_d:
5135 case Intrinsic::x86_mmx_pslli_q:
5136 case Intrinsic::x86_mmx_psrli_w:
5137 case Intrinsic::x86_mmx_psrli_d:
5138 case Intrinsic::x86_mmx_psrli_q:
5139 case Intrinsic::x86_mmx_psrai_w:
5140 case Intrinsic::x86_mmx_psrai_d: {
5141 SDOperand ShAmt = Op.getOperand(2);
5142 if (isa<ConstantSDNode>(ShAmt))
5145 unsigned NewIntNo = 0;
5146 MVT::ValueType ShAmtVT = MVT::v4i32;
5148 case Intrinsic::x86_sse2_pslli_w:
5149 NewIntNo = Intrinsic::x86_sse2_psll_w;
5151 case Intrinsic::x86_sse2_pslli_d:
5152 NewIntNo = Intrinsic::x86_sse2_psll_d;
5154 case Intrinsic::x86_sse2_pslli_q:
5155 NewIntNo = Intrinsic::x86_sse2_psll_q;
5157 case Intrinsic::x86_sse2_psrli_w:
5158 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5160 case Intrinsic::x86_sse2_psrli_d:
5161 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5163 case Intrinsic::x86_sse2_psrli_q:
5164 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5166 case Intrinsic::x86_sse2_psrai_w:
5167 NewIntNo = Intrinsic::x86_sse2_psra_w;
5169 case Intrinsic::x86_sse2_psrai_d:
5170 NewIntNo = Intrinsic::x86_sse2_psra_d;
5173 ShAmtVT = MVT::v2i32;
5175 case Intrinsic::x86_mmx_pslli_w:
5176 NewIntNo = Intrinsic::x86_mmx_psll_w;
5178 case Intrinsic::x86_mmx_pslli_d:
5179 NewIntNo = Intrinsic::x86_mmx_psll_d;
5181 case Intrinsic::x86_mmx_pslli_q:
5182 NewIntNo = Intrinsic::x86_mmx_psll_q;
5184 case Intrinsic::x86_mmx_psrli_w:
5185 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5187 case Intrinsic::x86_mmx_psrli_d:
5188 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5190 case Intrinsic::x86_mmx_psrli_q:
5191 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5193 case Intrinsic::x86_mmx_psrai_w:
5194 NewIntNo = Intrinsic::x86_mmx_psra_w;
5196 case Intrinsic::x86_mmx_psrai_d:
5197 NewIntNo = Intrinsic::x86_mmx_psra_d;
5199 default: abort(); // Can't reach here.
5204 MVT::ValueType VT = Op.getValueType();
5205 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5206 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5207 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5208 DAG.getConstant(NewIntNo, MVT::i32),
5209 Op.getOperand(1), ShAmt);
5214 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5215 // Depths > 0 not supported yet!
5216 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5219 // Just load the return address
5220 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5221 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5224 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5225 // Depths > 0 not supported yet!
5226 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5229 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5230 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5231 DAG.getIntPtrConstant(4));
5234 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5235 SelectionDAG &DAG) {
5236 // Is not yet supported on x86-64
5237 if (Subtarget->is64Bit())
5240 return DAG.getIntPtrConstant(8);
5243 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5245 assert(!Subtarget->is64Bit() &&
5246 "Lowering of eh_return builtin is not supported yet on x86-64");
5248 MachineFunction &MF = DAG.getMachineFunction();
5249 SDOperand Chain = Op.getOperand(0);
5250 SDOperand Offset = Op.getOperand(1);
5251 SDOperand Handler = Op.getOperand(2);
5253 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5256 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5257 DAG.getIntPtrConstant(-4UL));
5258 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5259 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5260 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5261 MF.getRegInfo().addLiveOut(X86::ECX);
5263 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5264 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5267 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5268 SelectionDAG &DAG) {
5269 SDOperand Root = Op.getOperand(0);
5270 SDOperand Trmp = Op.getOperand(1); // trampoline
5271 SDOperand FPtr = Op.getOperand(2); // nested function
5272 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5274 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5276 const X86InstrInfo *TII =
5277 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5279 if (Subtarget->is64Bit()) {
5280 SDOperand OutChains[6];
5282 // Large code-model.
5284 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5285 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5287 const unsigned char N86R10 =
5288 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5289 const unsigned char N86R11 =
5290 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5292 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5294 // Load the pointer to the nested function into R11.
5295 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5296 SDOperand Addr = Trmp;
5297 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5300 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5301 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5303 // Load the 'nest' parameter value into R10.
5304 // R10 is specified in X86CallingConv.td
5305 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5306 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5307 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5310 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5311 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5313 // Jump to the nested function.
5314 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5315 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5316 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5319 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5320 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5321 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5325 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5326 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5328 const Function *Func =
5329 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5330 unsigned CC = Func->getCallingConv();
5335 assert(0 && "Unsupported calling convention");
5336 case CallingConv::C:
5337 case CallingConv::X86_StdCall: {
5338 // Pass 'nest' parameter in ECX.
5339 // Must be kept in sync with X86CallingConv.td
5342 // Check that ECX wasn't needed by an 'inreg' parameter.
5343 const FunctionType *FTy = Func->getFunctionType();
5344 const PAListPtr &Attrs = Func->getParamAttrs();
5346 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5347 unsigned InRegCount = 0;
5350 for (FunctionType::param_iterator I = FTy->param_begin(),
5351 E = FTy->param_end(); I != E; ++I, ++Idx)
5352 if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5353 // FIXME: should only count parameters that are lowered to integers.
5354 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5356 if (InRegCount > 2) {
5357 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5363 case CallingConv::X86_FastCall:
5364 // Pass 'nest' parameter in EAX.
5365 // Must be kept in sync with X86CallingConv.td
5370 SDOperand OutChains[4];
5371 SDOperand Addr, Disp;
5373 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5374 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5376 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5377 const unsigned char N86Reg =
5378 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5379 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5382 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5383 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5385 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5386 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5387 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5388 TrmpAddr, 5, false, 1);
5390 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5391 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5394 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5395 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5399 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5401 The rounding mode is in bits 11:10 of FPSR, and has the following
5408 FLT_ROUNDS, on the other hand, expects the following:
5415 To perform the conversion, we do:
5416 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5419 MachineFunction &MF = DAG.getMachineFunction();
5420 const TargetMachine &TM = MF.getTarget();
5421 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5422 unsigned StackAlignment = TFI.getStackAlignment();
5423 MVT::ValueType VT = Op.getValueType();
5425 // Save FP Control Word to stack slot
5426 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5427 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5429 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5430 DAG.getEntryNode(), StackSlot);
5432 // Load FP Control Word from stack slot
5433 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5435 // Transform as necessary
5437 DAG.getNode(ISD::SRL, MVT::i16,
5438 DAG.getNode(ISD::AND, MVT::i16,
5439 CWD, DAG.getConstant(0x800, MVT::i16)),
5440 DAG.getConstant(11, MVT::i8));
5442 DAG.getNode(ISD::SRL, MVT::i16,
5443 DAG.getNode(ISD::AND, MVT::i16,
5444 CWD, DAG.getConstant(0x400, MVT::i16)),
5445 DAG.getConstant(9, MVT::i8));
5448 DAG.getNode(ISD::AND, MVT::i16,
5449 DAG.getNode(ISD::ADD, MVT::i16,
5450 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5451 DAG.getConstant(1, MVT::i16)),
5452 DAG.getConstant(3, MVT::i16));
5455 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5456 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5459 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5460 MVT::ValueType VT = Op.getValueType();
5461 MVT::ValueType OpVT = VT;
5462 unsigned NumBits = MVT::getSizeInBits(VT);
5464 Op = Op.getOperand(0);
5465 if (VT == MVT::i8) {
5466 // Zero extend to i32 since there is not an i8 bsr.
5468 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5471 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5472 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5473 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5475 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5476 SmallVector<SDOperand, 4> Ops;
5478 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5479 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5480 Ops.push_back(Op.getValue(1));
5481 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5483 // Finally xor with NumBits-1.
5484 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5487 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5491 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5492 MVT::ValueType VT = Op.getValueType();
5493 MVT::ValueType OpVT = VT;
5494 unsigned NumBits = MVT::getSizeInBits(VT);
5496 Op = Op.getOperand(0);
5497 if (VT == MVT::i8) {
5499 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5502 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5503 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5504 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5506 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5507 SmallVector<SDOperand, 4> Ops;
5509 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5510 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5511 Ops.push_back(Op.getValue(1));
5512 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5515 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5519 SDOperand X86TargetLowering::LowerLCS(SDOperand Op, SelectionDAG &DAG) {
5520 MVT::ValueType T = cast<AtomicSDNode>(Op.Val)->getVT();
5524 case MVT::i8: Reg = X86::AL; size = 1; break;
5525 case MVT::i16: Reg = X86::AX; size = 2; break;
5526 case MVT::i32: Reg = X86::EAX; size = 4; break;
5528 if (Subtarget->is64Bit()) {
5529 Reg = X86::RAX; size = 8;
5530 } else //Should go away when LowerType stuff lands
5531 return SDOperand(ExpandATOMIC_LCS(Op.Val, DAG), 0);
5534 SDOperand cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5535 Op.getOperand(3), SDOperand());
5536 SDOperand Ops[] = { cpIn.getValue(0),
5539 DAG.getTargetConstant(size, MVT::i8),
5541 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5542 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5544 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5548 SDNode* X86TargetLowering::ExpandATOMIC_LCS(SDNode* Op, SelectionDAG &DAG) {
5549 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5550 assert (T == MVT::i64 && "Only know how to expand i64 CAS");
5551 SDOperand cpInL, cpInH;
5552 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5553 DAG.getConstant(0, MVT::i32));
5554 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5555 DAG.getConstant(1, MVT::i32));
5556 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5557 cpInL, SDOperand());
5558 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5559 cpInH, cpInL.getValue(1));
5560 SDOperand swapInL, swapInH;
5561 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5562 DAG.getConstant(0, MVT::i32));
5563 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5564 DAG.getConstant(1, MVT::i32));
5565 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5566 swapInL, cpInH.getValue(1));
5567 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5568 swapInH, swapInL.getValue(1));
5569 SDOperand Ops[] = { swapInH.getValue(0),
5571 swapInH.getValue(1)};
5572 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5573 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5574 SDOperand cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5575 Result.getValue(1));
5576 SDOperand cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5577 cpOutL.getValue(2));
5578 SDOperand OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5579 SDOperand ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5580 Tys = DAG.getVTList(MVT::i64, MVT::Other);
5581 return DAG.getNode(ISD::MERGE_VALUES, Tys, ResultVal, cpOutH.getValue(1)).Val;
5584 SDNode* X86TargetLowering::ExpandATOMIC_LSS(SDNode* Op, SelectionDAG &DAG) {
5585 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5586 assert (T == MVT::i32 && "Only know how to expand i32 LSS");
5587 SDOperand negOp = DAG.getNode(ISD::SUB, T,
5588 DAG.getConstant(0, T), Op->getOperand(2));
5589 return DAG.getAtomic(ISD::ATOMIC_LAS, Op->getOperand(0),
5590 Op->getOperand(1), negOp, T).Val;
5593 /// LowerOperation - Provide custom lowering hooks for some operations.
5595 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5596 switch (Op.getOpcode()) {
5597 default: assert(0 && "Should not custom lower this!");
5598 case ISD::ATOMIC_LCS: return LowerLCS(Op,DAG);
5599 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5600 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5601 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5602 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5603 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5604 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5605 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5606 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5607 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5608 case ISD::SHL_PARTS:
5609 case ISD::SRA_PARTS:
5610 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5611 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5612 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5613 case ISD::FABS: return LowerFABS(Op, DAG);
5614 case ISD::FNEG: return LowerFNEG(Op, DAG);
5615 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5616 case ISD::SETCC: return LowerSETCC(Op, DAG);
5617 case ISD::SELECT: return LowerSELECT(Op, DAG);
5618 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5619 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5620 case ISD::CALL: return LowerCALL(Op, DAG);
5621 case ISD::RET: return LowerRET(Op, DAG);
5622 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5623 case ISD::VASTART: return LowerVASTART(Op, DAG);
5624 case ISD::VAARG: return LowerVAARG(Op, DAG);
5625 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5626 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5627 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5628 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5629 case ISD::FRAME_TO_ARGS_OFFSET:
5630 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5631 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5632 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5633 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5634 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5635 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5636 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5638 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5639 case ISD::READCYCLECOUNTER:
5640 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5644 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5645 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5646 switch (N->getOpcode()) {
5647 default: assert(0 && "Should not custom lower this!");
5648 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5649 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5650 case ISD::ATOMIC_LCS: return ExpandATOMIC_LCS(N, DAG);
5651 case ISD::ATOMIC_LSS: return ExpandATOMIC_LSS(N,DAG);
5655 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5657 default: return NULL;
5658 case X86ISD::BSF: return "X86ISD::BSF";
5659 case X86ISD::BSR: return "X86ISD::BSR";
5660 case X86ISD::SHLD: return "X86ISD::SHLD";
5661 case X86ISD::SHRD: return "X86ISD::SHRD";
5662 case X86ISD::FAND: return "X86ISD::FAND";
5663 case X86ISD::FOR: return "X86ISD::FOR";
5664 case X86ISD::FXOR: return "X86ISD::FXOR";
5665 case X86ISD::FSRL: return "X86ISD::FSRL";
5666 case X86ISD::FILD: return "X86ISD::FILD";
5667 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5668 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5669 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5670 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5671 case X86ISD::FLD: return "X86ISD::FLD";
5672 case X86ISD::FST: return "X86ISD::FST";
5673 case X86ISD::CALL: return "X86ISD::CALL";
5674 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5675 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5676 case X86ISD::CMP: return "X86ISD::CMP";
5677 case X86ISD::COMI: return "X86ISD::COMI";
5678 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5679 case X86ISD::SETCC: return "X86ISD::SETCC";
5680 case X86ISD::CMOV: return "X86ISD::CMOV";
5681 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5682 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5683 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5684 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5685 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5686 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5687 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5688 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5689 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5690 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5691 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5692 case X86ISD::FMAX: return "X86ISD::FMAX";
5693 case X86ISD::FMIN: return "X86ISD::FMIN";
5694 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5695 case X86ISD::FRCP: return "X86ISD::FRCP";
5696 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5697 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5698 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5699 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5700 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5701 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
5702 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
5703 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
5704 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
5708 // isLegalAddressingMode - Return true if the addressing mode represented
5709 // by AM is legal for this target, for a load/store of the specified type.
5710 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5711 const Type *Ty) const {
5712 // X86 supports extremely general addressing modes.
5714 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5715 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5719 // We can only fold this if we don't need an extra load.
5720 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5723 // X86-64 only supports addr of globals in small code model.
5724 if (Subtarget->is64Bit()) {
5725 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5727 // If lower 4G is not available, then we must use rip-relative addressing.
5728 if (AM.BaseOffs || AM.Scale > 1)
5739 // These scales always work.
5744 // These scales are formed with basereg+scalereg. Only accept if there is
5749 default: // Other stuff never works.
5757 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5758 if (!Ty1->isInteger() || !Ty2->isInteger())
5760 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5761 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5762 if (NumBits1 <= NumBits2)
5764 return Subtarget->is64Bit() || NumBits1 < 64;
5767 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5768 MVT::ValueType VT2) const {
5769 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5771 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5772 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5773 if (NumBits1 <= NumBits2)
5775 return Subtarget->is64Bit() || NumBits1 < 64;
5778 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5779 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5780 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5781 /// are assumed to be legal.
5783 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5784 // Only do shuffles on 128-bit vector types for now.
5785 if (MVT::getSizeInBits(VT) == 64) return false;
5786 return (Mask.Val->getNumOperands() <= 4 ||
5787 isIdentityMask(Mask.Val) ||
5788 isIdentityMask(Mask.Val, true) ||
5789 isSplatMask(Mask.Val) ||
5790 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5791 X86::isUNPCKLMask(Mask.Val) ||
5792 X86::isUNPCKHMask(Mask.Val) ||
5793 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5794 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5798 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDOperand> &BVOps,
5800 SelectionDAG &DAG) const {
5801 unsigned NumElts = BVOps.size();
5802 // Only do shuffles on 128-bit vector types for now.
5803 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5804 if (NumElts == 2) return true;
5806 return (isMOVLMask(&BVOps[0], 4) ||
5807 isCommutedMOVL(&BVOps[0], 4, true) ||
5808 isSHUFPMask(&BVOps[0], 4) ||
5809 isCommutedSHUFP(&BVOps[0], 4));
5814 //===----------------------------------------------------------------------===//
5815 // X86 Scheduler Hooks
5816 //===----------------------------------------------------------------------===//
5818 // private utility function
5820 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
5821 MachineBasicBlock *MBB,
5824 // For the atomic bitwise operator, we generate
5827 // ld t1 = [bitinstr.addr]
5828 // op t2 = t1, [bitinstr.val]
5830 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
5832 // fallthrough -->nextMBB
5833 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5834 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
5835 ilist<MachineBasicBlock>::iterator MBBIter = MBB;
5838 /// First build the CFG
5839 MachineFunction *F = MBB->getParent();
5840 MachineBasicBlock *thisMBB = MBB;
5841 MachineBasicBlock *newMBB = new MachineBasicBlock(LLVM_BB);
5842 MachineBasicBlock *nextMBB = new MachineBasicBlock(LLVM_BB);
5843 F->getBasicBlockList().insert(MBBIter, newMBB);
5844 F->getBasicBlockList().insert(MBBIter, nextMBB);
5846 // Move all successors to thisMBB to nextMBB
5847 nextMBB->transferSuccessors(thisMBB);
5849 // Update thisMBB to fall through to newMBB
5850 thisMBB->addSuccessor(newMBB);
5852 // newMBB jumps to itself and fall through to nextMBB
5853 newMBB->addSuccessor(nextMBB);
5854 newMBB->addSuccessor(newMBB);
5856 // Insert instructions into newMBB based on incoming instruction
5857 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
5858 MachineOperand& destOper = bInstr->getOperand(0);
5859 MachineOperand* argOpers[6];
5860 int numArgs = bInstr->getNumOperands() - 1;
5861 for (int i=0; i < numArgs; ++i)
5862 argOpers[i] = &bInstr->getOperand(i+1);
5864 // x86 address has 4 operands: base, index, scale, and displacement
5865 int lastAddrIndx = 3; // [0,3]
5868 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5869 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
5870 for (int i=0; i <= lastAddrIndx; ++i)
5871 (*MIB).addOperand(*argOpers[i]);
5873 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5874 assert( (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
5875 && "invalid operand");
5876 if (argOpers[valArgIndx]->isReg())
5877 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
5879 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
5881 (*MIB).addOperand(*argOpers[valArgIndx]);
5883 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
5886 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
5887 for (int i=0; i <= lastAddrIndx; ++i)
5888 (*MIB).addOperand(*argOpers[i]);
5891 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
5892 MIB.addReg(X86::EAX);
5895 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
5897 delete bInstr; // The pseudo instruction is gone now.
5901 // private utility function
5903 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
5904 MachineBasicBlock *MBB,
5906 // For the atomic min/max operator, we generate
5909 // ld t1 = [min/max.addr]
5910 // mov t2 = [min/max.val]
5912 // cmov[cond] t2 = t1
5914 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
5916 // fallthrough -->nextMBB
5918 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5919 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
5920 ilist<MachineBasicBlock>::iterator MBBIter = MBB;
5923 /// First build the CFG
5924 MachineFunction *F = MBB->getParent();
5925 MachineBasicBlock *thisMBB = MBB;
5926 MachineBasicBlock *newMBB = new MachineBasicBlock(LLVM_BB);
5927 MachineBasicBlock *nextMBB = new MachineBasicBlock(LLVM_BB);
5928 F->getBasicBlockList().insert(MBBIter, newMBB);
5929 F->getBasicBlockList().insert(MBBIter, nextMBB);
5931 // Move all successors to thisMBB to nextMBB
5932 nextMBB->transferSuccessors(thisMBB);
5934 // Update thisMBB to fall through to newMBB
5935 thisMBB->addSuccessor(newMBB);
5937 // newMBB jumps to newMBB and fall through to nextMBB
5938 newMBB->addSuccessor(nextMBB);
5939 newMBB->addSuccessor(newMBB);
5941 // Insert instructions into newMBB based on incoming instruction
5942 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
5943 MachineOperand& destOper = mInstr->getOperand(0);
5944 MachineOperand* argOpers[6];
5945 int numArgs = mInstr->getNumOperands() - 1;
5946 for (int i=0; i < numArgs; ++i)
5947 argOpers[i] = &mInstr->getOperand(i+1);
5949 // x86 address has 4 operands: base, index, scale, and displacement
5950 int lastAddrIndx = 3; // [0,3]
5953 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5954 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
5955 for (int i=0; i <= lastAddrIndx; ++i)
5956 (*MIB).addOperand(*argOpers[i]);
5958 // We only support register and immediate values
5959 assert( (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
5960 && "invalid operand");
5962 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5963 if (argOpers[valArgIndx]->isReg())
5964 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
5966 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
5967 (*MIB).addOperand(*argOpers[valArgIndx]);
5969 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
5972 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
5977 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
5978 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
5982 // Cmp and exchange if none has modified the memory location
5983 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
5984 for (int i=0; i <= lastAddrIndx; ++i)
5985 (*MIB).addOperand(*argOpers[i]);
5988 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
5989 MIB.addReg(X86::EAX);
5992 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
5994 delete mInstr; // The pseudo instruction is gone now.
6000 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6001 MachineBasicBlock *BB) {
6002 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6003 switch (MI->getOpcode()) {
6004 default: assert(false && "Unexpected instr type to insert");
6005 case X86::CMOV_FR32:
6006 case X86::CMOV_FR64:
6007 case X86::CMOV_V4F32:
6008 case X86::CMOV_V2F64:
6009 case X86::CMOV_V2I64: {
6010 // To "insert" a SELECT_CC instruction, we actually have to insert the
6011 // diamond control-flow pattern. The incoming instruction knows the
6012 // destination vreg to set, the condition code register to branch on, the
6013 // true/false values to select between, and a branch opcode to use.
6014 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6015 ilist<MachineBasicBlock>::iterator It = BB;
6021 // cmpTY ccX, r1, r2
6023 // fallthrough --> copy0MBB
6024 MachineBasicBlock *thisMBB = BB;
6025 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
6026 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
6028 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6029 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6030 MachineFunction *F = BB->getParent();
6031 F->getBasicBlockList().insert(It, copy0MBB);
6032 F->getBasicBlockList().insert(It, sinkMBB);
6033 // Update machine-CFG edges by transferring all successors of the current
6034 // block to the new block which will contain the Phi node for the select.
6035 sinkMBB->transferSuccessors(BB);
6037 // Add the true and fallthrough blocks as its successors.
6038 BB->addSuccessor(copy0MBB);
6039 BB->addSuccessor(sinkMBB);
6042 // %FalseValue = ...
6043 // # fallthrough to sinkMBB
6046 // Update machine-CFG edges
6047 BB->addSuccessor(sinkMBB);
6050 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6053 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6054 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6055 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6057 delete MI; // The pseudo instruction is gone now.
6061 case X86::FP32_TO_INT16_IN_MEM:
6062 case X86::FP32_TO_INT32_IN_MEM:
6063 case X86::FP32_TO_INT64_IN_MEM:
6064 case X86::FP64_TO_INT16_IN_MEM:
6065 case X86::FP64_TO_INT32_IN_MEM:
6066 case X86::FP64_TO_INT64_IN_MEM:
6067 case X86::FP80_TO_INT16_IN_MEM:
6068 case X86::FP80_TO_INT32_IN_MEM:
6069 case X86::FP80_TO_INT64_IN_MEM: {
6070 // Change the floating point control register to use "round towards zero"
6071 // mode when truncating to an integer value.
6072 MachineFunction *F = BB->getParent();
6073 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6074 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6076 // Load the old value of the high byte of the control word...
6078 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6079 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6081 // Set the high part to be round to zero...
6082 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6085 // Reload the modified control word now...
6086 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6088 // Restore the memory image of control word to original value
6089 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6092 // Get the X86 opcode to use.
6094 switch (MI->getOpcode()) {
6095 default: assert(0 && "illegal opcode!");
6096 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6097 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6098 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6099 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6100 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6101 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6102 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6103 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6104 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6108 MachineOperand &Op = MI->getOperand(0);
6109 if (Op.isRegister()) {
6110 AM.BaseType = X86AddressMode::RegBase;
6111 AM.Base.Reg = Op.getReg();
6113 AM.BaseType = X86AddressMode::FrameIndexBase;
6114 AM.Base.FrameIndex = Op.getIndex();
6116 Op = MI->getOperand(1);
6117 if (Op.isImmediate())
6118 AM.Scale = Op.getImm();
6119 Op = MI->getOperand(2);
6120 if (Op.isImmediate())
6121 AM.IndexReg = Op.getImm();
6122 Op = MI->getOperand(3);
6123 if (Op.isGlobalAddress()) {
6124 AM.GV = Op.getGlobal();
6126 AM.Disp = Op.getImm();
6128 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6129 .addReg(MI->getOperand(4).getReg());
6131 // Reload the original control word now.
6132 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6134 delete MI; // The pseudo instruction is gone now.
6137 case X86::ATOMAND32:
6138 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6141 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
6143 case X86::ATOMXOR32:
6144 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
6146 case X86::ATOMMIN32:
6147 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
6148 case X86::ATOMMAX32:
6149 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
6150 case X86::ATOMUMIN32:
6151 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
6152 case X86::ATOMUMAX32:
6153 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
6157 //===----------------------------------------------------------------------===//
6158 // X86 Optimization Hooks
6159 //===----------------------------------------------------------------------===//
6161 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
6165 const SelectionDAG &DAG,
6166 unsigned Depth) const {
6167 unsigned Opc = Op.getOpcode();
6168 assert((Opc >= ISD::BUILTIN_OP_END ||
6169 Opc == ISD::INTRINSIC_WO_CHAIN ||
6170 Opc == ISD::INTRINSIC_W_CHAIN ||
6171 Opc == ISD::INTRINSIC_VOID) &&
6172 "Should use MaskedValueIsZero if you don't know whether Op"
6173 " is a target node!");
6175 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
6179 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
6180 Mask.getBitWidth() - 1);
6185 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
6186 /// node is a GlobalAddress + offset.
6187 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
6188 GlobalValue* &GA, int64_t &Offset) const{
6189 if (N->getOpcode() == X86ISD::Wrapper) {
6190 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
6191 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
6195 return TargetLowering::isGAPlusOffset(N, GA, Offset);
6198 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
6199 const TargetLowering &TLI) {
6202 if (TLI.isGAPlusOffset(Base, GV, Offset))
6203 return (GV->getAlignment() >= N && (Offset % N) == 0);
6204 // DAG combine handles the stack object case.
6208 static bool EltsFromConsecutiveLoads(SDNode *N, SDOperand PermMask,
6209 unsigned NumElems, MVT::ValueType EVT,
6211 SelectionDAG &DAG, MachineFrameInfo *MFI,
6212 const TargetLowering &TLI) {
6214 for (unsigned i = 0; i < NumElems; ++i) {
6215 SDOperand Idx = PermMask.getOperand(i);
6216 if (Idx.getOpcode() == ISD::UNDEF) {
6222 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
6223 SDOperand Elt = DAG.getShuffleScalarElt(N, Index);
6225 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.Val)))
6229 if (Base->getOpcode() == ISD::UNDEF)
6233 if (Elt.getOpcode() == ISD::UNDEF)
6236 if (!TLI.isConsecutiveLoad(Elt.Val, Base,
6237 MVT::getSizeInBits(EVT)/8, i, MFI))
6243 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6244 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6245 /// if the load addresses are consecutive, non-overlapping, and in the right
6247 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6248 const TargetLowering &TLI) {
6249 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6250 MVT::ValueType VT = N->getValueType(0);
6251 MVT::ValueType EVT = MVT::getVectorElementType(VT);
6252 SDOperand PermMask = N->getOperand(2);
6253 unsigned NumElems = PermMask.getNumOperands();
6254 SDNode *Base = NULL;
6255 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
6259 LoadSDNode *LD = cast<LoadSDNode>(Base);
6260 if (isBaseAlignmentOfN(16, Base->getOperand(1).Val, TLI))
6261 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6262 LD->getSrcValueOffset(), LD->isVolatile());
6263 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6264 LD->getSrcValueOffset(), LD->isVolatile(),
6265 LD->getAlignment());
6268 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
6269 static SDOperand PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
6270 const X86Subtarget *Subtarget,
6271 const TargetLowering &TLI) {
6272 // Ignore single operand BUILD_VECTOR.
6273 if (N->getNumOperands() == 1)
6276 MVT::ValueType VT = N->getValueType(0);
6277 MVT::ValueType EVT = MVT::getVectorElementType(VT);
6278 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
6279 // We are looking for load i64 and zero extend. We want to transform
6280 // it before legalizer has a chance to expand it. Also look for i64
6281 // BUILD_PAIR bit casted to f64.
6283 // This must be an insertion into a zero vector.
6284 SDOperand HighElt = N->getOperand(1);
6285 if (!isZeroNode(HighElt))
6288 // Value must be a load.
6289 SDNode *Base = N->getOperand(0).Val;
6290 if (!isa<LoadSDNode>(Base)) {
6291 if (Base->getOpcode() != ISD::BIT_CONVERT)
6293 Base = Base->getOperand(0).Val;
6294 if (!isa<LoadSDNode>(Base))
6298 // Transform it into VZEXT_LOAD addr.
6299 LoadSDNode *LD = cast<LoadSDNode>(Base);
6300 return DAG.getNode(X86ISD::VZEXT_LOAD, VT, LD->getChain(), LD->getBasePtr());
6303 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6304 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6305 const X86Subtarget *Subtarget) {
6306 SDOperand Cond = N->getOperand(0);
6308 // If we have SSE[12] support, try to form min/max nodes.
6309 if (Subtarget->hasSSE2() &&
6310 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6311 if (Cond.getOpcode() == ISD::SETCC) {
6312 // Get the LHS/RHS of the select.
6313 SDOperand LHS = N->getOperand(1);
6314 SDOperand RHS = N->getOperand(2);
6315 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6317 unsigned Opcode = 0;
6318 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6321 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6324 if (!UnsafeFPMath) break;
6326 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6328 Opcode = X86ISD::FMIN;
6331 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6334 if (!UnsafeFPMath) break;
6336 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6338 Opcode = X86ISD::FMAX;
6341 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6344 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6347 if (!UnsafeFPMath) break;
6349 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6351 Opcode = X86ISD::FMIN;
6354 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6357 if (!UnsafeFPMath) break;
6359 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6361 Opcode = X86ISD::FMAX;
6367 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6375 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6376 static SDOperand PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
6377 const X86Subtarget *Subtarget) {
6378 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
6379 // the FP state in cases where an emms may be missing.
6380 // A preferable solution to the general problem is to figure out the right
6381 // places to insert EMMS. This qualifies as a quick hack.
6382 StoreSDNode *St = cast<StoreSDNode>(N);
6383 if (MVT::isVector(St->getValue().getValueType()) &&
6384 MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
6385 isa<LoadSDNode>(St->getValue()) &&
6386 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6387 St->getChain().hasOneUse() && !St->isVolatile()) {
6388 SDNode* LdVal = St->getValue().Val;
6390 int TokenFactorIndex = -1;
6391 SmallVector<SDOperand, 8> Ops;
6392 SDNode* ChainVal = St->getChain().Val;
6393 // Must be a store of a load. We currently handle two cases: the load
6394 // is a direct child, and it's under an intervening TokenFactor. It is
6395 // possible to dig deeper under nested TokenFactors.
6396 if (ChainVal == LdVal)
6397 Ld = cast<LoadSDNode>(St->getChain());
6398 else if (St->getValue().hasOneUse() &&
6399 ChainVal->getOpcode() == ISD::TokenFactor) {
6400 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6401 if (ChainVal->getOperand(i).Val == LdVal) {
6402 TokenFactorIndex = i;
6403 Ld = cast<LoadSDNode>(St->getValue());
6405 Ops.push_back(ChainVal->getOperand(i));
6409 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6410 if (Subtarget->is64Bit()) {
6411 SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6412 Ld->getBasePtr(), Ld->getSrcValue(),
6413 Ld->getSrcValueOffset(), Ld->isVolatile(),
6414 Ld->getAlignment());
6415 SDOperand NewChain = NewLd.getValue(1);
6416 if (TokenFactorIndex != -1) {
6417 Ops.push_back(NewChain);
6418 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6421 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6422 St->getSrcValue(), St->getSrcValueOffset(),
6423 St->isVolatile(), St->getAlignment());
6426 // Otherwise, lower to two 32-bit copies.
6427 SDOperand LoAddr = Ld->getBasePtr();
6428 SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6429 DAG.getConstant(MVT::i32, 4));
6431 SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6432 Ld->getSrcValue(), Ld->getSrcValueOffset(),
6433 Ld->isVolatile(), Ld->getAlignment());
6434 SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6435 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6437 MinAlign(Ld->getAlignment(), 4));
6439 SDOperand NewChain = LoLd.getValue(1);
6440 if (TokenFactorIndex != -1) {
6441 Ops.push_back(LoLd);
6442 Ops.push_back(HiLd);
6443 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6447 LoAddr = St->getBasePtr();
6448 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6449 DAG.getConstant(MVT::i32, 4));
6451 SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6452 St->getSrcValue(), St->getSrcValueOffset(),
6453 St->isVolatile(), St->getAlignment());
6454 SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6455 St->getSrcValue(), St->getSrcValueOffset()+4,
6457 MinAlign(St->getAlignment(), 4));
6458 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6464 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6465 /// X86ISD::FXOR nodes.
6466 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6467 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6468 // F[X]OR(0.0, x) -> x
6469 // F[X]OR(x, 0.0) -> x
6470 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6471 if (C->getValueAPF().isPosZero())
6472 return N->getOperand(1);
6473 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6474 if (C->getValueAPF().isPosZero())
6475 return N->getOperand(0);
6479 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6480 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6481 // FAND(0.0, x) -> 0.0
6482 // FAND(x, 0.0) -> 0.0
6483 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6484 if (C->getValueAPF().isPosZero())
6485 return N->getOperand(0);
6486 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6487 if (C->getValueAPF().isPosZero())
6488 return N->getOperand(1);
6493 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6494 DAGCombinerInfo &DCI) const {
6495 SelectionDAG &DAG = DCI.DAG;
6496 switch (N->getOpcode()) {
6498 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
6499 case ISD::BUILD_VECTOR:
6500 return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
6501 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6502 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
6504 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6505 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6511 //===----------------------------------------------------------------------===//
6512 // X86 Inline Assembly Support
6513 //===----------------------------------------------------------------------===//
6515 /// getConstraintType - Given a constraint letter, return the type of
6516 /// constraint it is for this target.
6517 X86TargetLowering::ConstraintType
6518 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6519 if (Constraint.size() == 1) {
6520 switch (Constraint[0]) {
6531 return C_RegisterClass;
6536 return TargetLowering::getConstraintType(Constraint);
6539 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6540 /// with another that has more specific requirements based on the type of the
6541 /// corresponding operand.
6542 const char *X86TargetLowering::
6543 LowerXConstraint(MVT::ValueType ConstraintVT) const {
6544 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
6545 // 'f' like normal targets.
6546 if (MVT::isFloatingPoint(ConstraintVT)) {
6547 if (Subtarget->hasSSE2())
6549 if (Subtarget->hasSSE1())
6553 return TargetLowering::LowerXConstraint(ConstraintVT);
6556 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6557 /// vector. If it is invalid, don't add anything to Ops.
6558 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6560 std::vector<SDOperand>&Ops,
6561 SelectionDAG &DAG) const {
6562 SDOperand Result(0, 0);
6564 switch (Constraint) {
6567 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6568 if (C->getValue() <= 31) {
6569 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6575 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6576 if (C->getValue() <= 255) {
6577 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6583 // Literal immediates are always ok.
6584 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6585 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6589 // If we are in non-pic codegen mode, we allow the address of a global (with
6590 // an optional displacement) to be used with 'i'.
6591 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6594 // Match either (GA) or (GA+C)
6596 Offset = GA->getOffset();
6597 } else if (Op.getOpcode() == ISD::ADD) {
6598 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6599 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6601 Offset = GA->getOffset()+C->getValue();
6603 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6604 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6606 Offset = GA->getOffset()+C->getValue();
6613 // If addressing this global requires a load (e.g. in PIC mode), we can't
6615 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6619 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6625 // Otherwise, not valid for this mode.
6631 Ops.push_back(Result);
6634 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6637 std::vector<unsigned> X86TargetLowering::
6638 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6639 MVT::ValueType VT) const {
6640 if (Constraint.size() == 1) {
6641 // FIXME: not handling fp-stack yet!
6642 switch (Constraint[0]) { // GCC X86 Constraint Letters
6643 default: break; // Unknown constraint letter
6644 case 'A': // EAX/EDX
6645 if (VT == MVT::i32 || VT == MVT::i64)
6646 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6648 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6651 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6652 else if (VT == MVT::i16)
6653 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6654 else if (VT == MVT::i8)
6655 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6656 else if (VT == MVT::i64)
6657 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6662 return std::vector<unsigned>();
6665 std::pair<unsigned, const TargetRegisterClass*>
6666 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6667 MVT::ValueType VT) const {
6668 // First, see if this is a constraint that directly corresponds to an LLVM
6670 if (Constraint.size() == 1) {
6671 // GCC Constraint Letters
6672 switch (Constraint[0]) {
6674 case 'r': // GENERAL_REGS
6675 case 'R': // LEGACY_REGS
6676 case 'l': // INDEX_REGS
6677 if (VT == MVT::i64 && Subtarget->is64Bit())
6678 return std::make_pair(0U, X86::GR64RegisterClass);
6680 return std::make_pair(0U, X86::GR32RegisterClass);
6681 else if (VT == MVT::i16)
6682 return std::make_pair(0U, X86::GR16RegisterClass);
6683 else if (VT == MVT::i8)
6684 return std::make_pair(0U, X86::GR8RegisterClass);
6686 case 'f': // FP Stack registers.
6687 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
6688 // value to the correct fpstack register class.
6689 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
6690 return std::make_pair(0U, X86::RFP32RegisterClass);
6691 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
6692 return std::make_pair(0U, X86::RFP64RegisterClass);
6693 return std::make_pair(0U, X86::RFP80RegisterClass);
6694 case 'y': // MMX_REGS if MMX allowed.
6695 if (!Subtarget->hasMMX()) break;
6696 return std::make_pair(0U, X86::VR64RegisterClass);
6698 case 'Y': // SSE_REGS if SSE2 allowed
6699 if (!Subtarget->hasSSE2()) break;
6701 case 'x': // SSE_REGS if SSE1 allowed
6702 if (!Subtarget->hasSSE1()) break;
6706 // Scalar SSE types.
6709 return std::make_pair(0U, X86::FR32RegisterClass);
6712 return std::make_pair(0U, X86::FR64RegisterClass);
6720 return std::make_pair(0U, X86::VR128RegisterClass);
6726 // Use the default implementation in TargetLowering to convert the register
6727 // constraint into a member of a register class.
6728 std::pair<unsigned, const TargetRegisterClass*> Res;
6729 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6731 // Not found as a standard register?
6732 if (Res.second == 0) {
6733 // GCC calls "st(0)" just plain "st".
6734 if (StringsEqualNoCase("{st}", Constraint)) {
6735 Res.first = X86::ST0;
6736 Res.second = X86::RFP80RegisterClass;
6742 // Otherwise, check to see if this is a register class of the wrong value
6743 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6744 // turn into {ax},{dx}.
6745 if (Res.second->hasType(VT))
6746 return Res; // Correct type already, nothing to do.
6748 // All of the single-register GCC register classes map their values onto
6749 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6750 // really want an 8-bit or 32-bit register, map to the appropriate register
6751 // class and return the appropriate register.
6752 if (Res.second != X86::GR16RegisterClass)
6755 if (VT == MVT::i8) {
6756 unsigned DestReg = 0;
6757 switch (Res.first) {
6759 case X86::AX: DestReg = X86::AL; break;
6760 case X86::DX: DestReg = X86::DL; break;
6761 case X86::CX: DestReg = X86::CL; break;
6762 case X86::BX: DestReg = X86::BL; break;
6765 Res.first = DestReg;
6766 Res.second = Res.second = X86::GR8RegisterClass;
6768 } else if (VT == MVT::i32) {
6769 unsigned DestReg = 0;
6770 switch (Res.first) {
6772 case X86::AX: DestReg = X86::EAX; break;
6773 case X86::DX: DestReg = X86::EDX; break;
6774 case X86::CX: DestReg = X86::ECX; break;
6775 case X86::BX: DestReg = X86::EBX; break;
6776 case X86::SI: DestReg = X86::ESI; break;
6777 case X86::DI: DestReg = X86::EDI; break;
6778 case X86::BP: DestReg = X86::EBP; break;
6779 case X86::SP: DestReg = X86::ESP; break;
6782 Res.first = DestReg;
6783 Res.second = Res.second = X86::GR32RegisterClass;
6785 } else if (VT == MVT::i64) {
6786 unsigned DestReg = 0;
6787 switch (Res.first) {
6789 case X86::AX: DestReg = X86::RAX; break;
6790 case X86::DX: DestReg = X86::RDX; break;
6791 case X86::CX: DestReg = X86::RCX; break;
6792 case X86::BX: DestReg = X86::RBX; break;
6793 case X86::SI: DestReg = X86::RSI; break;
6794 case X86::DI: DestReg = X86::RDI; break;
6795 case X86::BP: DestReg = X86::RBP; break;
6796 case X86::SP: DestReg = X86::RSP; break;
6799 Res.first = DestReg;
6800 Res.second = Res.second = X86::GR64RegisterClass;