1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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/VectorExtras.h"
27 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/SSARegMap.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ParameterAttributes.h"
42 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
43 : TargetLowering(TM) {
44 Subtarget = &TM.getSubtarget<X86Subtarget>();
45 X86ScalarSSEf64 = Subtarget->hasSSE2();
46 X86ScalarSSEf32 = Subtarget->hasSSE1();
47 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
50 RegInfo = TM.getRegisterInfo();
52 // Set up the TargetLowering object.
54 // X86 is weird, it always uses i8 for shift amounts and setcc results.
55 setShiftAmountType(MVT::i8);
56 setSetCCResultType(MVT::i8);
57 setSetCCResultContents(ZeroOrOneSetCCResult);
58 setSchedulingPreference(SchedulingForRegPressure);
59 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
60 setStackPointerRegisterToSaveRestore(X86StackPtr);
62 if (Subtarget->isTargetDarwin()) {
63 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
64 setUseUnderscoreSetJmp(false);
65 setUseUnderscoreLongJmp(false);
66 } else if (Subtarget->isTargetMingw()) {
67 // MS runtime is weird: it exports _setjmp, but longjmp!
68 setUseUnderscoreSetJmp(true);
69 setUseUnderscoreLongJmp(false);
71 setUseUnderscoreSetJmp(true);
72 setUseUnderscoreLongJmp(true);
75 // Set up the register classes.
76 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
77 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
78 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
79 if (Subtarget->is64Bit())
80 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
82 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
84 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
86 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
87 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
88 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
90 if (Subtarget->is64Bit()) {
91 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
92 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
95 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
96 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
98 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
101 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
103 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
104 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
105 // SSE has no i16 to fp conversion, only i32
106 if (X86ScalarSSEf32) {
107 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
108 // f32 and f64 cases are Legal, f80 case is not
109 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
111 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
112 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
115 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
116 // are Legal, f80 is custom lowered.
117 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
118 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
120 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
122 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
123 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
125 if (X86ScalarSSEf32) {
126 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
127 // f32 and f64 cases are Legal, f80 case is not
128 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
130 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
131 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
134 // Handle FP_TO_UINT by promoting the destination to a larger signed
136 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
137 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
138 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
140 if (Subtarget->is64Bit()) {
141 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
142 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
144 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
145 // Expand FP_TO_UINT into a select.
146 // FIXME: We would like to use a Custom expander here eventually to do
147 // the optimal thing for SSE vs. the default expansion in the legalizer.
148 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
150 // With SSE3 we can use fisttpll to convert to a signed i64.
151 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
154 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
155 if (!X86ScalarSSEf64) {
156 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
157 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
160 // Scalar integer multiply, multiply-high, divide, and remainder are
161 // lowered to use operations that produce two results, to match the
162 // available instructions. This exposes the two-result form to trivial
163 // CSE, which is able to combine x/y and x%y into a single instruction,
164 // for example. The single-result multiply instructions are introduced
165 // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
167 setOperationAction(ISD::MUL , MVT::i8 , Expand);
168 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
169 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
170 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
171 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
172 setOperationAction(ISD::SREM , MVT::i8 , Expand);
173 setOperationAction(ISD::UREM , MVT::i8 , Expand);
174 setOperationAction(ISD::MUL , MVT::i16 , Expand);
175 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
176 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
177 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
178 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
179 setOperationAction(ISD::SREM , MVT::i16 , Expand);
180 setOperationAction(ISD::UREM , MVT::i16 , Expand);
181 setOperationAction(ISD::MUL , MVT::i32 , Expand);
182 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
183 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
184 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
185 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
186 setOperationAction(ISD::SREM , MVT::i32 , Expand);
187 setOperationAction(ISD::UREM , MVT::i32 , Expand);
188 setOperationAction(ISD::MUL , MVT::i64 , Expand);
189 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
190 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
191 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
192 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
193 setOperationAction(ISD::SREM , MVT::i64 , Expand);
194 setOperationAction(ISD::UREM , MVT::i64 , Expand);
196 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
197 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
198 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
199 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
200 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
201 if (Subtarget->is64Bit())
202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
206 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
207 setOperationAction(ISD::FREM , MVT::f64 , Expand);
209 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i8 , Expand);
211 setOperationAction(ISD::CTLZ , MVT::i8 , Expand);
212 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
213 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
214 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
215 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
216 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
217 setOperationAction(ISD::CTLZ , MVT::i32 , Expand);
218 if (Subtarget->is64Bit()) {
219 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
220 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
221 setOperationAction(ISD::CTLZ , MVT::i64 , Expand);
224 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
225 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
227 // These should be promoted to a larger select which is supported.
228 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
229 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
230 // X86 wants to expand cmov itself.
231 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
232 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
233 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
234 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
235 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
236 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
237 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
238 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
239 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
240 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
241 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
242 if (Subtarget->is64Bit()) {
243 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
244 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
246 // X86 ret instruction may pop stack.
247 setOperationAction(ISD::RET , MVT::Other, Custom);
248 if (!Subtarget->is64Bit())
249 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
252 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
253 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
254 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
255 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
256 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
257 if (Subtarget->is64Bit()) {
258 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
259 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
260 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
261 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
263 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
264 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
265 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
266 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
267 // X86 wants to expand memset / memcpy itself.
268 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
269 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
271 // Use the default ISD::LOCATION expansion.
272 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
273 // FIXME - use subtarget debug flags
274 if (!Subtarget->isTargetDarwin() &&
275 !Subtarget->isTargetELF() &&
276 !Subtarget->isTargetCygMing())
277 setOperationAction(ISD::LABEL, MVT::Other, Expand);
279 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
280 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
281 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
282 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
283 if (Subtarget->is64Bit()) {
285 setExceptionPointerRegister(X86::RAX);
286 setExceptionSelectorRegister(X86::RDX);
288 setExceptionPointerRegister(X86::EAX);
289 setExceptionSelectorRegister(X86::EDX);
291 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
293 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
295 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
296 setOperationAction(ISD::VASTART , MVT::Other, Custom);
297 setOperationAction(ISD::VAARG , MVT::Other, Expand);
298 setOperationAction(ISD::VAEND , MVT::Other, Expand);
299 if (Subtarget->is64Bit())
300 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
302 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
304 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
305 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
306 if (Subtarget->is64Bit())
307 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
308 if (Subtarget->isTargetCygMing())
309 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
311 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
313 if (X86ScalarSSEf64) {
314 // f32 and f64 use SSE.
315 // Set up the FP register classes.
316 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
317 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
319 // Use ANDPD to simulate FABS.
320 setOperationAction(ISD::FABS , MVT::f64, Custom);
321 setOperationAction(ISD::FABS , MVT::f32, Custom);
323 // Use XORP to simulate FNEG.
324 setOperationAction(ISD::FNEG , MVT::f64, Custom);
325 setOperationAction(ISD::FNEG , MVT::f32, Custom);
327 // Use ANDPD and ORPD to simulate FCOPYSIGN.
328 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
329 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
331 // We don't support sin/cos/fmod
332 setOperationAction(ISD::FSIN , MVT::f64, Expand);
333 setOperationAction(ISD::FCOS , MVT::f64, Expand);
334 setOperationAction(ISD::FREM , MVT::f64, Expand);
335 setOperationAction(ISD::FSIN , MVT::f32, Expand);
336 setOperationAction(ISD::FCOS , MVT::f32, Expand);
337 setOperationAction(ISD::FREM , MVT::f32, Expand);
339 // Expand FP immediates into loads from the stack, except for the special
341 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
342 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
343 addLegalFPImmediate(APFloat(+0.0)); // xorpd
344 addLegalFPImmediate(APFloat(+0.0f)); // xorps
346 // Conversions to long double (in X87) go through memory.
347 setConvertAction(MVT::f32, MVT::f80, Expand);
348 setConvertAction(MVT::f64, MVT::f80, Expand);
350 // Conversions from long double (in X87) go through memory.
351 setConvertAction(MVT::f80, MVT::f32, Expand);
352 setConvertAction(MVT::f80, MVT::f64, Expand);
353 } else if (X86ScalarSSEf32) {
354 // Use SSE for f32, x87 for f64.
355 // Set up the FP register classes.
356 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
357 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
359 // Use ANDPS to simulate FABS.
360 setOperationAction(ISD::FABS , MVT::f32, Custom);
362 // Use XORP to simulate FNEG.
363 setOperationAction(ISD::FNEG , MVT::f32, Custom);
365 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
367 // Use ANDPS and ORPS to simulate FCOPYSIGN.
368 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
369 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
371 // We don't support sin/cos/fmod
372 setOperationAction(ISD::FSIN , MVT::f32, Expand);
373 setOperationAction(ISD::FCOS , MVT::f32, Expand);
374 setOperationAction(ISD::FREM , MVT::f32, Expand);
376 // Expand FP immediates into loads from the stack, except for the special
378 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
379 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
380 addLegalFPImmediate(APFloat(+0.0f)); // xorps
381 addLegalFPImmediate(APFloat(+0.0)); // FLD0
382 addLegalFPImmediate(APFloat(+1.0)); // FLD1
383 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
384 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
386 // SSE->x87 conversions go through memory.
387 setConvertAction(MVT::f32, MVT::f64, Expand);
388 setConvertAction(MVT::f32, MVT::f80, Expand);
390 // x87->SSE truncations need to go through memory.
391 setConvertAction(MVT::f80, MVT::f32, Expand);
392 setConvertAction(MVT::f64, MVT::f32, Expand);
393 // And x87->x87 truncations also.
394 setConvertAction(MVT::f80, MVT::f64, Expand);
397 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
398 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
401 // f32 and f64 in x87.
402 // Set up the FP register classes.
403 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
404 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
406 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
407 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
408 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
409 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
411 // Floating truncations need to go through memory.
412 setConvertAction(MVT::f80, MVT::f32, Expand);
413 setConvertAction(MVT::f64, MVT::f32, Expand);
414 setConvertAction(MVT::f80, MVT::f64, Expand);
417 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
418 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
421 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
422 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
423 addLegalFPImmediate(APFloat(+0.0)); // FLD0
424 addLegalFPImmediate(APFloat(+1.0)); // FLD1
425 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
426 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
427 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
428 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
429 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
430 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
433 // Long double always uses X87.
434 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
435 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
436 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
437 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
439 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
440 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
443 // Always use a library call for pow.
444 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
445 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
446 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
448 // First set operation action for all vector types to expand. Then we
449 // will selectively turn on ones that can be effectively codegen'd.
450 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
451 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
452 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
453 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
454 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
455 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
456 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
457 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
458 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
459 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
460 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
461 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
462 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
463 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
464 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
465 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
466 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
467 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
468 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
469 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
470 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
471 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
472 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
473 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
474 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
475 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
476 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
477 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
478 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
479 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
482 if (Subtarget->hasMMX()) {
483 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
484 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
485 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
486 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
488 // FIXME: add MMX packed arithmetics
490 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
491 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
492 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
493 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
495 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
496 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
497 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
499 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
500 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
502 setOperationAction(ISD::AND, MVT::v8i8, Promote);
503 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
504 setOperationAction(ISD::AND, MVT::v4i16, Promote);
505 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
506 setOperationAction(ISD::AND, MVT::v2i32, Promote);
507 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
508 setOperationAction(ISD::AND, MVT::v1i64, Legal);
510 setOperationAction(ISD::OR, MVT::v8i8, Promote);
511 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
512 setOperationAction(ISD::OR, MVT::v4i16, Promote);
513 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
514 setOperationAction(ISD::OR, MVT::v2i32, Promote);
515 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
516 setOperationAction(ISD::OR, MVT::v1i64, Legal);
518 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
519 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
520 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
521 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
522 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
523 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
524 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
526 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
527 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
528 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
529 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
530 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
531 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
532 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
534 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
535 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
536 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
537 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
539 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
540 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
541 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
542 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
544 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
545 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
546 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
547 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
550 if (Subtarget->hasSSE1()) {
551 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
553 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
554 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
555 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
556 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
557 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
558 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
559 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
560 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
561 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
562 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
563 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
566 if (Subtarget->hasSSE2()) {
567 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
568 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
569 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
570 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
571 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
573 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
574 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
575 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
576 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
577 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
578 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
579 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
580 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
581 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
582 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
583 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
584 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
585 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
586 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
587 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
589 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
590 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
591 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
592 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
593 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
594 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
596 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
597 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
598 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
599 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
600 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
602 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
603 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
604 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
605 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
606 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
607 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
609 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
610 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
611 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
612 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
613 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
614 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
615 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
616 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
617 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
618 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
619 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
620 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
623 // Custom lower v2i64 and v2f64 selects.
624 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
625 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
626 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
627 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
630 // We want to custom lower some of our intrinsics.
631 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
633 // We have target-specific dag combine patterns for the following nodes:
634 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
635 setTargetDAGCombine(ISD::SELECT);
637 computeRegisterProperties();
639 // FIXME: These should be based on subtarget info. Plus, the values should
640 // be smaller when we are in optimizing for size mode.
641 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
642 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
643 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
644 allowUnalignedMemoryAccesses = true; // x86 supports it!
648 //===----------------------------------------------------------------------===//
649 // Return Value Calling Convention Implementation
650 //===----------------------------------------------------------------------===//
652 #include "X86GenCallingConv.inc"
654 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
655 /// exists skip possible ISD:TokenFactor.
656 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
657 if (Chain.getOpcode()==X86ISD::TAILCALL) {
659 } else if (Chain.getOpcode()==ISD::TokenFactor) {
660 if (Chain.getNumOperands() &&
661 Chain.getOperand(0).getOpcode()==X86ISD::TAILCALL)
662 return Chain.getOperand(0);
667 /// LowerRET - Lower an ISD::RET node.
668 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
669 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
671 SmallVector<CCValAssign, 16> RVLocs;
672 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
673 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
674 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
675 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
677 // If this is the first return lowered for this function, add the regs to the
678 // liveout set for the function.
679 if (DAG.getMachineFunction().liveout_empty()) {
680 for (unsigned i = 0; i != RVLocs.size(); ++i)
681 if (RVLocs[i].isRegLoc())
682 DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
684 SDOperand Chain = Op.getOperand(0);
686 // Handle tail call return.
687 Chain = GetPossiblePreceedingTailCall(Chain);
688 if (Chain.getOpcode() == X86ISD::TAILCALL) {
689 SDOperand TailCall = Chain;
690 SDOperand TargetAddress = TailCall.getOperand(1);
691 SDOperand StackAdjustment = TailCall.getOperand(2);
692 assert ( ((TargetAddress.getOpcode() == ISD::Register &&
693 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
694 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
695 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
696 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
697 "Expecting an global address, external symbol, or register");
698 assert( StackAdjustment.getOpcode() == ISD::Constant &&
699 "Expecting a const value");
701 SmallVector<SDOperand,8> Operands;
702 Operands.push_back(Chain.getOperand(0));
703 Operands.push_back(TargetAddress);
704 Operands.push_back(StackAdjustment);
705 // Copy registers used by the call. Last operand is a flag so it is not
707 for(unsigned i=3; i < TailCall.getNumOperands()-1;i++) {
708 Operands.push_back(Chain.getOperand(i));
710 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0], Operands.size());
716 // Copy the result values into the output registers.
717 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
718 RVLocs[0].getLocReg() != X86::ST0) {
719 for (unsigned i = 0; i != RVLocs.size(); ++i) {
720 CCValAssign &VA = RVLocs[i];
721 assert(VA.isRegLoc() && "Can only return in registers!");
722 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
724 Flag = Chain.getValue(1);
727 // We need to handle a destination of ST0 specially, because it isn't really
729 SDOperand Value = Op.getOperand(1);
731 // If this is an FP return with ScalarSSE, we need to move the value from
732 // an XMM register onto the fp-stack.
733 if ((X86ScalarSSEf32 && RVLocs[0].getValVT()==MVT::f32) ||
734 (X86ScalarSSEf64 && RVLocs[0].getValVT()==MVT::f64)) {
737 // If this is a load into a scalarsse value, don't store the loaded value
738 // back to the stack, only to reload it: just replace the scalar-sse load.
739 if (ISD::isNON_EXTLoad(Value.Val) &&
740 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
741 Chain = Value.getOperand(0);
742 MemLoc = Value.getOperand(1);
744 // Spill the value to memory and reload it into top of stack.
745 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
746 MachineFunction &MF = DAG.getMachineFunction();
747 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
748 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
749 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
751 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
752 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
753 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
754 Chain = Value.getValue(1);
757 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
758 SDOperand Ops[] = { Chain, Value };
759 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
760 Flag = Chain.getValue(1);
763 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
765 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
767 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
771 /// LowerCallResult - Lower the result values of an ISD::CALL into the
772 /// appropriate copies out of appropriate physical registers. This assumes that
773 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
774 /// being lowered. The returns a SDNode with the same number of values as the
776 SDNode *X86TargetLowering::
777 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
778 unsigned CallingConv, SelectionDAG &DAG) {
780 // Assign locations to each value returned by this call.
781 SmallVector<CCValAssign, 16> RVLocs;
782 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
783 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
784 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
787 SmallVector<SDOperand, 8> ResultVals;
789 // Copy all of the result registers out of their specified physreg.
790 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
791 for (unsigned i = 0; i != RVLocs.size(); ++i) {
792 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
793 RVLocs[i].getValVT(), InFlag).getValue(1);
794 InFlag = Chain.getValue(2);
795 ResultVals.push_back(Chain.getValue(0));
798 // Copies from the FP stack are special, as ST0 isn't a valid register
799 // before the fp stackifier runs.
801 // Copy ST0 into an RFP register with FP_GET_RESULT.
802 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
803 SDOperand GROps[] = { Chain, InFlag };
804 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
805 Chain = RetVal.getValue(1);
806 InFlag = RetVal.getValue(2);
808 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
810 if ((X86ScalarSSEf32 && RVLocs[0].getValVT() == MVT::f32) ||
811 (X86ScalarSSEf64 && RVLocs[0].getValVT() == MVT::f64)) {
812 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
813 // shouldn't be necessary except that RFP cannot be live across
814 // multiple blocks. When stackifier is fixed, they can be uncoupled.
815 MachineFunction &MF = DAG.getMachineFunction();
816 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
817 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
819 Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
821 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
822 RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
823 Chain = RetVal.getValue(1);
825 ResultVals.push_back(RetVal);
828 // Merge everything together with a MERGE_VALUES node.
829 ResultVals.push_back(Chain);
830 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
831 &ResultVals[0], ResultVals.size()).Val;
835 //===----------------------------------------------------------------------===//
836 // C & StdCall & Fast Calling Convention implementation
837 //===----------------------------------------------------------------------===//
838 // StdCall calling convention seems to be standard for many Windows' API
839 // routines and around. It differs from C calling convention just a little:
840 // callee should clean up the stack, not caller. Symbols should be also
841 // decorated in some fancy way :) It doesn't support any vector arguments.
842 // For info on fast calling convention see Fast Calling Convention (tail call)
843 // implementation LowerX86_32FastCCCallTo.
845 /// AddLiveIn - This helper function adds the specified physical register to the
846 /// MachineFunction as a live in value. It also creates a corresponding virtual
848 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
849 const TargetRegisterClass *RC) {
850 assert(RC->contains(PReg) && "Not the correct regclass!");
851 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
852 MF.addLiveIn(PReg, VReg);
856 // align stack arguments according to platform alignment needed for tail calls
857 unsigned GetAlignedArgumentStackSize(unsigned StackSize, SelectionDAG& DAG);
859 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
860 const CCValAssign &VA,
861 MachineFrameInfo *MFI,
862 SDOperand Root, unsigned i) {
863 // Create the nodes corresponding to a load from this parameter slot.
864 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
865 VA.getLocMemOffset());
866 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
868 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
870 if (Flags & ISD::ParamFlags::ByVal)
873 return DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0);
876 SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
878 unsigned NumArgs = Op.Val->getNumValues() - 1;
879 MachineFunction &MF = DAG.getMachineFunction();
880 MachineFrameInfo *MFI = MF.getFrameInfo();
881 SDOperand Root = Op.getOperand(0);
882 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
883 unsigned CC = MF.getFunction()->getCallingConv();
884 // Assign locations to all of the incoming arguments.
885 SmallVector<CCValAssign, 16> ArgLocs;
886 CCState CCInfo(CC, isVarArg,
887 getTargetMachine(), ArgLocs);
888 // Check for possible tail call calling convention.
889 if (CC == CallingConv::Fast && PerformTailCallOpt)
890 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_TailCall);
892 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
894 SmallVector<SDOperand, 8> ArgValues;
895 unsigned LastVal = ~0U;
896 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
897 CCValAssign &VA = ArgLocs[i];
898 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
900 assert(VA.getValNo() != LastVal &&
901 "Don't support value assigned to multiple locs yet");
902 LastVal = VA.getValNo();
905 MVT::ValueType RegVT = VA.getLocVT();
906 TargetRegisterClass *RC;
907 if (RegVT == MVT::i32)
908 RC = X86::GR32RegisterClass;
910 assert(MVT::isVector(RegVT));
911 RC = X86::VR128RegisterClass;
914 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
915 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
917 // If this is an 8 or 16-bit value, it is really passed promoted to 32
918 // bits. Insert an assert[sz]ext to capture this, then truncate to the
920 if (VA.getLocInfo() == CCValAssign::SExt)
921 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
922 DAG.getValueType(VA.getValVT()));
923 else if (VA.getLocInfo() == CCValAssign::ZExt)
924 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
925 DAG.getValueType(VA.getValVT()));
927 if (VA.getLocInfo() != CCValAssign::Full)
928 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
930 ArgValues.push_back(ArgValue);
932 assert(VA.isMemLoc());
933 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
937 unsigned StackSize = CCInfo.getNextStackOffset();
938 // align stack specially for tail calls
939 if (CC==CallingConv::Fast)
940 StackSize = GetAlignedArgumentStackSize(StackSize,DAG);
942 ArgValues.push_back(Root);
944 // If the function takes variable number of arguments, make a frame index for
945 // the start of the first vararg value... for expansion of llvm.va_start.
947 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
949 // Tail call calling convention (CallingConv::Fast) does not support varargs.
950 assert( !(isVarArg && CC == CallingConv::Fast) &&
951 "CallingConv::Fast does not support varargs.");
953 if (isStdCall && !isVarArg &&
954 (CC==CallingConv::Fast && PerformTailCallOpt || CC!=CallingConv::Fast)) {
955 BytesToPopOnReturn = StackSize; // Callee pops everything..
956 BytesCallerReserves = 0;
958 BytesToPopOnReturn = 0; // Callee pops nothing.
960 // If this is an sret function, the return should pop the hidden pointer.
962 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
963 ISD::ParamFlags::StructReturn))
964 BytesToPopOnReturn = 4;
966 BytesCallerReserves = StackSize;
969 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
971 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
972 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
974 // Return the new list of results.
975 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
976 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
979 SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
981 SDOperand Chain = Op.getOperand(0);
982 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
983 SDOperand Callee = Op.getOperand(4);
984 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
986 // Analyze operands of the call, assigning locations to each operand.
987 SmallVector<CCValAssign, 16> ArgLocs;
988 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
989 if(CC==CallingConv::Fast && PerformTailCallOpt)
990 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
992 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
994 // Get a count of how many bytes are to be pushed on the stack.
995 unsigned NumBytes = CCInfo.getNextStackOffset();
996 if (CC==CallingConv::Fast)
997 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
999 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1001 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1002 SmallVector<SDOperand, 8> MemOpChains;
1006 // Walk the register/memloc assignments, inserting copies/loads.
1007 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1008 CCValAssign &VA = ArgLocs[i];
1009 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1011 // Promote the value if needed.
1012 switch (VA.getLocInfo()) {
1013 default: assert(0 && "Unknown loc info!");
1014 case CCValAssign::Full: break;
1015 case CCValAssign::SExt:
1016 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1018 case CCValAssign::ZExt:
1019 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1021 case CCValAssign::AExt:
1022 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1026 if (VA.isRegLoc()) {
1027 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1029 assert(VA.isMemLoc());
1030 if (StackPtr.Val == 0)
1031 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1033 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1038 // If the first argument is an sret pointer, remember it.
1039 bool isSRet = NumOps &&
1040 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
1041 ISD::ParamFlags::StructReturn);
1043 if (!MemOpChains.empty())
1044 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1045 &MemOpChains[0], MemOpChains.size());
1047 // Build a sequence of copy-to-reg nodes chained together with token chain
1048 // and flag operands which copy the outgoing args into registers.
1050 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1051 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1053 InFlag = Chain.getValue(1);
1056 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1058 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1059 Subtarget->isPICStyleGOT()) {
1060 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1061 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1063 InFlag = Chain.getValue(1);
1066 // If the callee is a GlobalAddress node (quite common, every direct call is)
1067 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1068 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1069 // We should use extra load for direct calls to dllimported functions in
1071 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1072 getTargetMachine(), true))
1073 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1074 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1075 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1077 // Returns a chain & a flag for retval copy to use.
1078 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1079 SmallVector<SDOperand, 8> Ops;
1080 Ops.push_back(Chain);
1081 Ops.push_back(Callee);
1083 // Add argument registers to the end of the list so that they are known live
1085 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1086 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1087 RegsToPass[i].second.getValueType()));
1089 // Add an implicit use GOT pointer in EBX.
1090 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1091 Subtarget->isPICStyleGOT())
1092 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1095 Ops.push_back(InFlag);
1097 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1098 InFlag = Chain.getValue(1);
1100 // Create the CALLSEQ_END node.
1101 unsigned NumBytesForCalleeToPush = 0;
1103 if (CC == CallingConv::X86_StdCall ||
1104 (CC == CallingConv::Fast && PerformTailCallOpt)) {
1106 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1108 NumBytesForCalleeToPush = NumBytes;
1109 assert(!(isVarArg && CC==CallingConv::Fast) &&
1110 "CallingConv::Fast does not support varargs.");
1112 // If this is is a call to a struct-return function, the callee
1113 // pops the hidden struct pointer, so we have to push it back.
1114 // This is common for Darwin/X86, Linux & Mingw32 targets.
1115 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1118 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1120 Ops.push_back(Chain);
1121 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1122 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
1123 Ops.push_back(InFlag);
1124 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1125 InFlag = Chain.getValue(1);
1127 // Handle result values, copying them out of physregs into vregs that we
1129 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1133 //===----------------------------------------------------------------------===//
1134 // FastCall Calling Convention implementation
1135 //===----------------------------------------------------------------------===//
1137 // The X86 'fastcall' calling convention passes up to two integer arguments in
1138 // registers (an appropriate portion of ECX/EDX), passes arguments in C order,
1139 // and requires that the callee pop its arguments off the stack (allowing proper
1140 // tail calls), and has the same return value conventions as C calling convs.
1142 // This calling convention always arranges for the callee pop value to be 8n+4
1143 // bytes, which is needed for tail recursion elimination and stack alignment
1146 X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
1147 MachineFunction &MF = DAG.getMachineFunction();
1148 MachineFrameInfo *MFI = MF.getFrameInfo();
1149 SDOperand Root = Op.getOperand(0);
1150 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1152 // Assign locations to all of the incoming arguments.
1153 SmallVector<CCValAssign, 16> ArgLocs;
1154 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
1155 getTargetMachine(), ArgLocs);
1156 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
1158 SmallVector<SDOperand, 8> ArgValues;
1159 unsigned LastVal = ~0U;
1160 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1161 CCValAssign &VA = ArgLocs[i];
1162 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1164 assert(VA.getValNo() != LastVal &&
1165 "Don't support value assigned to multiple locs yet");
1166 LastVal = VA.getValNo();
1168 if (VA.isRegLoc()) {
1169 MVT::ValueType RegVT = VA.getLocVT();
1170 TargetRegisterClass *RC;
1171 if (RegVT == MVT::i32)
1172 RC = X86::GR32RegisterClass;
1174 assert(MVT::isVector(RegVT));
1175 RC = X86::VR128RegisterClass;
1178 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1179 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1181 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1182 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1184 if (VA.getLocInfo() == CCValAssign::SExt)
1185 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1186 DAG.getValueType(VA.getValVT()));
1187 else if (VA.getLocInfo() == CCValAssign::ZExt)
1188 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1189 DAG.getValueType(VA.getValVT()));
1191 if (VA.getLocInfo() != CCValAssign::Full)
1192 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1194 ArgValues.push_back(ArgValue);
1196 assert(VA.isMemLoc());
1197 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1201 ArgValues.push_back(Root);
1203 unsigned StackSize = CCInfo.getNextStackOffset();
1205 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1206 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1207 // arguments and the arguments after the retaddr has been pushed are
1209 if ((StackSize & 7) == 0)
1213 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1214 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
1215 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
1216 BytesCallerReserves = 0;
1218 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1219 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1221 // Return the new list of results.
1222 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1223 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1227 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1228 const SDOperand &StackPtr,
1229 const CCValAssign &VA,
1232 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1233 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1234 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1235 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1236 if (Flags & ISD::ParamFlags::ByVal) {
1237 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1238 ISD::ParamFlags::ByValAlignOffs);
1240 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1241 ISD::ParamFlags::ByValSizeOffs;
1243 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1244 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1246 return DAG.getNode(ISD::MEMCPY, MVT::Other, Chain, PtrOff, Arg, SizeNode,
1249 return DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1253 SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1255 SDOperand Chain = Op.getOperand(0);
1256 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1257 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1258 SDOperand Callee = Op.getOperand(4);
1260 // Analyze operands of the call, assigning locations to each operand.
1261 SmallVector<CCValAssign, 16> ArgLocs;
1262 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1263 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1265 // Get a count of how many bytes are to be pushed on the stack.
1266 unsigned NumBytes = CCInfo.getNextStackOffset();
1268 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1269 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1270 // arguments and the arguments after the retaddr has been pushed are
1272 if ((NumBytes & 7) == 0)
1276 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1278 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1279 SmallVector<SDOperand, 8> MemOpChains;
1283 // Walk the register/memloc assignments, inserting copies/loads.
1284 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1285 CCValAssign &VA = ArgLocs[i];
1286 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1288 // Promote the value if needed.
1289 switch (VA.getLocInfo()) {
1290 default: assert(0 && "Unknown loc info!");
1291 case CCValAssign::Full: break;
1292 case CCValAssign::SExt:
1293 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1295 case CCValAssign::ZExt:
1296 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1298 case CCValAssign::AExt:
1299 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1303 if (VA.isRegLoc()) {
1304 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1306 assert(VA.isMemLoc());
1307 if (StackPtr.Val == 0)
1308 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1310 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1315 if (!MemOpChains.empty())
1316 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1317 &MemOpChains[0], MemOpChains.size());
1319 // Build a sequence of copy-to-reg nodes chained together with token chain
1320 // and flag operands which copy the outgoing args into registers.
1322 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1323 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1325 InFlag = Chain.getValue(1);
1328 // If the callee is a GlobalAddress node (quite common, every direct call is)
1329 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1330 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1331 // We should use extra load for direct calls to dllimported functions in
1333 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1334 getTargetMachine(), true))
1335 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1336 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1337 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1339 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1341 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1342 Subtarget->isPICStyleGOT()) {
1343 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1344 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1346 InFlag = Chain.getValue(1);
1349 // Returns a chain & a flag for retval copy to use.
1350 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1351 SmallVector<SDOperand, 8> Ops;
1352 Ops.push_back(Chain);
1353 Ops.push_back(Callee);
1355 // Add argument registers to the end of the list so that they are known live
1357 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1358 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1359 RegsToPass[i].second.getValueType()));
1361 // Add an implicit use GOT pointer in EBX.
1362 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1363 Subtarget->isPICStyleGOT())
1364 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1367 Ops.push_back(InFlag);
1369 assert(isTailCall==false && "no tail call here");
1370 Chain = DAG.getNode(X86ISD::CALL,
1371 NodeTys, &Ops[0], Ops.size());
1372 InFlag = Chain.getValue(1);
1374 // Returns a flag for retval copy to use.
1375 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1377 Ops.push_back(Chain);
1378 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1379 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1380 Ops.push_back(InFlag);
1381 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1382 InFlag = Chain.getValue(1);
1384 // Handle result values, copying them out of physregs into vregs that we
1386 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1389 //===----------------------------------------------------------------------===//
1390 // Fast Calling Convention (tail call) implementation
1391 //===----------------------------------------------------------------------===//
1393 // Like std call, callee cleans arguments, convention except that ECX is
1394 // reserved for storing the tail called function address. Only 2 registers are
1395 // free for argument passing (inreg). Tail call optimization is performed
1397 // * tailcallopt is enabled
1398 // * caller/callee are fastcc
1399 // * elf/pic is disabled OR
1400 // * elf/pic enabled + callee is in module + callee has
1401 // visibility protected or hidden
1402 // To ensure the stack is aligned according to platform abi pass
1403 // tail-call-align-stack. This makes sure that argument delta is always
1404 // multiples of stack alignment. (Dynamic linkers need this - darwin's dyld for
1406 // If a tail called function callee has more arguments than the caller the
1407 // caller needs to make sure that there is room to move the RETADDR to. This is
1408 // achived by reserving an area the size of the argument delta right after the
1409 // original REtADDR, but before the saved framepointer or the spilled registers
1410 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1422 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1423 /// for a 16 byte align requirement.
1424 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1425 SelectionDAG& DAG) {
1426 if (PerformTailCallOpt) {
1427 MachineFunction &MF = DAG.getMachineFunction();
1428 const TargetMachine &TM = MF.getTarget();
1429 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1430 unsigned StackAlignment = TFI.getStackAlignment();
1431 uint64_t AlignMask = StackAlignment - 1;
1432 int64_t Offset = StackSize;
1433 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1434 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1435 // Number smaller than 12 so just add the difference.
1436 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1438 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1439 Offset = ((~AlignMask) & Offset) + StackAlignment +
1440 (StackAlignment-SlotSize);
1447 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1448 // following the call is a return. A function is eligible if caller/callee
1449 // calling conventions match, currently only fastcc supports tail calls, and the
1450 // function CALL is immediatly followed by a RET.
1451 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1453 SelectionDAG& DAG) const {
1454 bool IsEligible = false;
1456 // Check whether CALL node immediatly preceeds the RET node and whether the
1457 // return uses the result of the node or is a void return.
1458 if ((Ret.getNumOperands() == 1 &&
1459 (Ret.getOperand(0)== SDOperand(Call.Val,1) ||
1460 Ret.getOperand(0)== SDOperand(Call.Val,0))) ||
1461 (Ret.getOperand(0)== SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1462 Ret.getOperand(1)== SDOperand(Call.Val,0))) {
1463 MachineFunction &MF = DAG.getMachineFunction();
1464 unsigned CallerCC = MF.getFunction()->getCallingConv();
1465 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1466 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1467 SDOperand Callee = Call.getOperand(4);
1468 // On elf/pic %ebx needs to be livein.
1469 if(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1470 Subtarget->isPICStyleGOT()) {
1471 // Can only do local tail calls with PIC.
1472 GlobalValue * GV = 0;
1473 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1475 (GV = G->getGlobal()) &&
1476 (GV->hasHiddenVisibility() || GV->hasProtectedVisibility()))
1486 SDOperand X86TargetLowering::LowerX86_TailCallTo(SDOperand Op,
1489 SDOperand Chain = Op.getOperand(0);
1490 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1491 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1492 SDOperand Callee = Op.getOperand(4);
1493 bool is64Bit = Subtarget->is64Bit();
1495 assert(isTailCall && PerformTailCallOpt && "Should only emit tail calls.");
1497 // Analyze operands of the call, assigning locations to each operand.
1498 SmallVector<CCValAssign, 16> ArgLocs;
1499 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1501 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1503 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1506 // Lower arguments at fp - stackoffset + fpdiff.
1507 MachineFunction &MF = DAG.getMachineFunction();
1509 unsigned NumBytesToBePushed =
1510 GetAlignedArgumentStackSize(CCInfo.getNextStackOffset(), DAG);
1512 unsigned NumBytesCallerPushed =
1513 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1514 int FPDiff = NumBytesCallerPushed - NumBytesToBePushed;
1516 // Set the delta of movement of the returnaddr stackslot.
1517 // But only set if delta is greater than previous delta.
1518 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1519 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1521 // Adjust the ret address stack slot.
1523 MVT::ValueType VT = is64Bit ? MVT::i64 : MVT::i32;
1524 SDOperand RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1526 DAG.getLoad(VT, DAG.getEntryNode(),RetAddrFrIdx, NULL, 0);
1527 // Emit a store of the saved ret value to the new location.
1528 int SlotSize = is64Bit ? 8 : 4;
1529 int NewReturnAddrFI =
1530 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1531 SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1532 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1536 getCALLSEQ_START(Chain, DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1538 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1539 SmallVector<SDOperand, 8> MemOpChains;
1540 SmallVector<SDOperand, 8> MemOpChains2;
1541 SDOperand FramePtr, StackPtr;
1546 // Walk the register/memloc assignments, inserting copies/loads. Lower
1547 // arguments first to the stack slot where they would normally - in case of a
1548 // normal function call - be.
1549 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1550 CCValAssign &VA = ArgLocs[i];
1551 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1553 // Promote the value if needed.
1554 switch (VA.getLocInfo()) {
1555 default: assert(0 && "Unknown loc info!");
1556 case CCValAssign::Full: break;
1557 case CCValAssign::SExt:
1558 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1560 case CCValAssign::ZExt:
1561 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1563 case CCValAssign::AExt:
1564 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1568 if (VA.isRegLoc()) {
1569 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1571 assert(VA.isMemLoc());
1572 if (StackPtr.Val == 0)
1573 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1575 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1580 if (!MemOpChains.empty())
1581 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1582 &MemOpChains[0], MemOpChains.size());
1584 // Build a sequence of copy-to-reg nodes chained together with token chain
1585 // and flag operands which copy the outgoing args into registers.
1587 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1588 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1590 InFlag = Chain.getValue(1);
1592 InFlag = SDOperand();
1593 // Copy from stack slots to stack slot of a tail called function. This needs
1594 // to be done because if we would lower the arguments directly to their real
1595 // stack slot we might end up overwriting each other.
1596 // TODO: To make this more efficient (sometimes saving a store/load) we could
1597 // analyse the arguments and emit this store/load/store sequence only for
1598 // arguments which would be overwritten otherwise.
1599 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1600 CCValAssign &VA = ArgLocs[i];
1601 if (!VA.isRegLoc()) {
1602 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1603 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1605 // Get source stack slot.
1606 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1607 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1608 // Create frame index.
1609 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1610 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1611 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1612 FIN = DAG.getFrameIndex(FI, MVT::i32);
1613 if (Flags & ISD::ParamFlags::ByVal) {
1614 // Copy relative to framepointer.
1615 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1616 ISD::ParamFlags::ByValAlignOffs);
1618 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1619 ISD::ParamFlags::ByValSizeOffs;
1621 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1622 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1623 // Copy relative to framepointer.
1624 MemOpChains2.push_back(DAG.getNode(ISD::MEMCPY, MVT::Other, Chain, FIN,
1625 PtrOff, SizeNode, AlignNode));
1627 SDOperand LoadedArg = DAG.getLoad(VA.getValVT(), Chain, PtrOff, NULL,0);
1628 // Store relative to framepointer.
1629 MemOpChains2.push_back(DAG.getStore(Chain, LoadedArg, FIN, NULL, 0));
1634 if (!MemOpChains2.empty())
1635 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1636 &MemOpChains2[0], MemOpChains.size());
1638 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1640 // Does not work with tail call since ebx is not restored correctly by
1641 // tailcaller. TODO: at least for x86 - verify for x86-64
1643 // If the callee is a GlobalAddress node (quite common, every direct call is)
1644 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1645 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1646 // We should use extra load for direct calls to dllimported functions in
1648 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1649 getTargetMachine(), true))
1650 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1651 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1652 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1654 assert(Callee.getOpcode() == ISD::LOAD &&
1655 "Function destination must be loaded into virtual register");
1656 unsigned Opc = is64Bit ? X86::R9 : X86::ECX;
1658 Chain = DAG.getCopyToReg(Chain,
1659 DAG.getRegister(Opc, getPointerTy()) ,
1661 Callee = DAG.getRegister(Opc, getPointerTy());
1662 // Add register as live out.
1663 DAG.getMachineFunction().addLiveOut(Opc);
1666 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1667 SmallVector<SDOperand, 8> Ops;
1669 Ops.push_back(Chain);
1670 Ops.push_back(DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1671 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1673 Ops.push_back(InFlag);
1674 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1675 InFlag = Chain.getValue(1);
1677 // Returns a chain & a flag for retval copy to use.
1678 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1680 Ops.push_back(Chain);
1681 Ops.push_back(Callee);
1682 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1683 // Add argument registers to the end of the list so that they are known live
1685 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1686 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1687 RegsToPass[i].second.getValueType()));
1689 Ops.push_back(InFlag);
1690 assert(InFlag.Val &&
1691 "Flag must be set. Depend on flag being set in LowerRET");
1692 Chain = DAG.getNode(X86ISD::TAILCALL,
1693 Op.Val->getVTList(), &Ops[0], Ops.size());
1695 return SDOperand(Chain.Val, Op.ResNo);
1698 //===----------------------------------------------------------------------===//
1699 // X86-64 C Calling Convention implementation
1700 //===----------------------------------------------------------------------===//
1703 X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1704 MachineFunction &MF = DAG.getMachineFunction();
1705 MachineFrameInfo *MFI = MF.getFrameInfo();
1706 SDOperand Root = Op.getOperand(0);
1707 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1708 unsigned CC= MF.getFunction()->getCallingConv();
1710 static const unsigned GPR64ArgRegs[] = {
1711 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1713 static const unsigned XMMArgRegs[] = {
1714 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1715 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1719 // Assign locations to all of the incoming arguments.
1720 SmallVector<CCValAssign, 16> ArgLocs;
1721 CCState CCInfo(CC, isVarArg,
1722 getTargetMachine(), ArgLocs);
1723 if (CC == CallingConv::Fast && PerformTailCallOpt)
1724 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_TailCall);
1726 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
1728 SmallVector<SDOperand, 8> ArgValues;
1729 unsigned LastVal = ~0U;
1730 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1731 CCValAssign &VA = ArgLocs[i];
1732 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1734 assert(VA.getValNo() != LastVal &&
1735 "Don't support value assigned to multiple locs yet");
1736 LastVal = VA.getValNo();
1738 if (VA.isRegLoc()) {
1739 MVT::ValueType RegVT = VA.getLocVT();
1740 TargetRegisterClass *RC;
1741 if (RegVT == MVT::i32)
1742 RC = X86::GR32RegisterClass;
1743 else if (RegVT == MVT::i64)
1744 RC = X86::GR64RegisterClass;
1745 else if (RegVT == MVT::f32)
1746 RC = X86::FR32RegisterClass;
1747 else if (RegVT == MVT::f64)
1748 RC = X86::FR64RegisterClass;
1750 assert(MVT::isVector(RegVT));
1751 if (MVT::getSizeInBits(RegVT) == 64) {
1752 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1755 RC = X86::VR128RegisterClass;
1758 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1759 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1761 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1762 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1764 if (VA.getLocInfo() == CCValAssign::SExt)
1765 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1766 DAG.getValueType(VA.getValVT()));
1767 else if (VA.getLocInfo() == CCValAssign::ZExt)
1768 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1769 DAG.getValueType(VA.getValVT()));
1771 if (VA.getLocInfo() != CCValAssign::Full)
1772 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1774 // Handle MMX values passed in GPRs.
1775 if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1776 MVT::getSizeInBits(RegVT) == 64)
1777 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1779 ArgValues.push_back(ArgValue);
1781 assert(VA.isMemLoc());
1782 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1786 unsigned StackSize = CCInfo.getNextStackOffset();
1787 if (CC==CallingConv::Fast)
1788 StackSize =GetAlignedArgumentStackSize(StackSize, DAG);
1790 // If the function takes variable number of arguments, make a frame index for
1791 // the start of the first vararg value... for expansion of llvm.va_start.
1793 assert(CC!=CallingConv::Fast
1794 && "Var arg not supported with calling convention fastcc");
1795 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1796 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1798 // For X86-64, if there are vararg parameters that are passed via
1799 // registers, then we must store them to their spots on the stack so they
1800 // may be loaded by deferencing the result of va_next.
1801 VarArgsGPOffset = NumIntRegs * 8;
1802 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1803 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1804 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1806 // Store the integer parameter registers.
1807 SmallVector<SDOperand, 8> MemOps;
1808 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1809 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1810 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1811 for (; NumIntRegs != 6; ++NumIntRegs) {
1812 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1813 X86::GR64RegisterClass);
1814 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1815 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1816 MemOps.push_back(Store);
1817 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1818 DAG.getConstant(8, getPointerTy()));
1821 // Now store the XMM (fp + vector) parameter registers.
1822 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1823 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1824 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1825 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1826 X86::VR128RegisterClass);
1827 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1828 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1829 MemOps.push_back(Store);
1830 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1831 DAG.getConstant(16, getPointerTy()));
1833 if (!MemOps.empty())
1834 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1835 &MemOps[0], MemOps.size());
1838 ArgValues.push_back(Root);
1839 // Tail call convention (fastcc) needs callee pop.
1840 if (CC == CallingConv::Fast && PerformTailCallOpt){
1841 BytesToPopOnReturn = StackSize; // Callee pops everything.
1842 BytesCallerReserves = 0;
1844 BytesToPopOnReturn = 0; // Callee pops nothing.
1845 BytesCallerReserves = StackSize;
1847 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1848 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1850 // Return the new list of results.
1851 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1852 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1856 X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1858 SDOperand Chain = Op.getOperand(0);
1859 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1860 SDOperand Callee = Op.getOperand(4);
1862 // Analyze operands of the call, assigning locations to each operand.
1863 SmallVector<CCValAssign, 16> ArgLocs;
1864 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1865 if (CC==CallingConv::Fast)
1866 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1868 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
1870 // Get a count of how many bytes are to be pushed on the stack.
1871 unsigned NumBytes = CCInfo.getNextStackOffset();
1872 if (CC == CallingConv::Fast)
1873 NumBytes = GetAlignedArgumentStackSize(NumBytes,DAG);
1875 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1877 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1878 SmallVector<SDOperand, 8> MemOpChains;
1882 // Walk the register/memloc assignments, inserting copies/loads.
1883 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1884 CCValAssign &VA = ArgLocs[i];
1885 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1887 // Promote the value if needed.
1888 switch (VA.getLocInfo()) {
1889 default: assert(0 && "Unknown loc info!");
1890 case CCValAssign::Full: break;
1891 case CCValAssign::SExt:
1892 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1894 case CCValAssign::ZExt:
1895 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1897 case CCValAssign::AExt:
1898 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1902 if (VA.isRegLoc()) {
1903 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1905 assert(VA.isMemLoc());
1906 if (StackPtr.Val == 0)
1907 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1909 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1914 if (!MemOpChains.empty())
1915 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1916 &MemOpChains[0], MemOpChains.size());
1918 // Build a sequence of copy-to-reg nodes chained together with token chain
1919 // and flag operands which copy the outgoing args into registers.
1921 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1922 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1924 InFlag = Chain.getValue(1);
1928 assert ( CallingConv::Fast != CC &&
1929 "Var args not supported with calling convention fastcc");
1931 // From AMD64 ABI document:
1932 // For calls that may call functions that use varargs or stdargs
1933 // (prototype-less calls or calls to functions containing ellipsis (...) in
1934 // the declaration) %al is used as hidden argument to specify the number
1935 // of SSE registers used. The contents of %al do not need to match exactly
1936 // the number of registers, but must be an ubound on the number of SSE
1937 // registers used and is in the range 0 - 8 inclusive.
1939 // Count the number of XMM registers allocated.
1940 static const unsigned XMMArgRegs[] = {
1941 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1942 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1944 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1946 Chain = DAG.getCopyToReg(Chain, X86::AL,
1947 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1948 InFlag = Chain.getValue(1);
1951 // If the callee is a GlobalAddress node (quite common, every direct call is)
1952 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1953 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1954 // We should use extra load for direct calls to dllimported functions in
1956 if (getTargetMachine().getCodeModel() != CodeModel::Large
1957 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1958 getTargetMachine(), true))
1959 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1960 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1961 if (getTargetMachine().getCodeModel() != CodeModel::Large)
1962 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1964 // Returns a chain & a flag for retval copy to use.
1965 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1966 SmallVector<SDOperand, 8> Ops;
1967 Ops.push_back(Chain);
1968 Ops.push_back(Callee);
1970 // Add argument registers to the end of the list so that they are known live
1972 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1973 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1974 RegsToPass[i].second.getValueType()));
1977 Ops.push_back(InFlag);
1979 Chain = DAG.getNode(X86ISD::CALL,
1980 NodeTys, &Ops[0], Ops.size());
1981 InFlag = Chain.getValue(1);
1982 int NumBytesForCalleeToPush = 0;
1983 if (CC==CallingConv::Fast) {
1984 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1987 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1989 // Returns a flag for retval copy to use.
1990 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1992 Ops.push_back(Chain);
1993 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1994 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
1995 Ops.push_back(InFlag);
1996 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1997 InFlag = Chain.getValue(1);
1999 // Handle result values, copying them out of physregs into vregs that we
2001 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
2005 //===----------------------------------------------------------------------===//
2006 // Other Lowering Hooks
2007 //===----------------------------------------------------------------------===//
2010 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2011 MachineFunction &MF = DAG.getMachineFunction();
2012 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2013 int ReturnAddrIndex = FuncInfo->getRAIndex();
2015 if (ReturnAddrIndex == 0) {
2016 // Set up a frame object for the return address.
2017 if (Subtarget->is64Bit())
2018 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
2020 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
2022 FuncInfo->setRAIndex(ReturnAddrIndex);
2025 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2030 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
2031 /// specific condition code. It returns a false if it cannot do a direct
2032 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
2034 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2035 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
2036 SelectionDAG &DAG) {
2037 X86CC = X86::COND_INVALID;
2039 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2040 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2041 // X > -1 -> X == 0, jump !sign.
2042 RHS = DAG.getConstant(0, RHS.getValueType());
2043 X86CC = X86::COND_NS;
2045 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2046 // X < 0 -> X == 0, jump on sign.
2047 X86CC = X86::COND_S;
2049 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
2051 RHS = DAG.getConstant(0, RHS.getValueType());
2052 X86CC = X86::COND_LE;
2057 switch (SetCCOpcode) {
2059 case ISD::SETEQ: X86CC = X86::COND_E; break;
2060 case ISD::SETGT: X86CC = X86::COND_G; break;
2061 case ISD::SETGE: X86CC = X86::COND_GE; break;
2062 case ISD::SETLT: X86CC = X86::COND_L; break;
2063 case ISD::SETLE: X86CC = X86::COND_LE; break;
2064 case ISD::SETNE: X86CC = X86::COND_NE; break;
2065 case ISD::SETULT: X86CC = X86::COND_B; break;
2066 case ISD::SETUGT: X86CC = X86::COND_A; break;
2067 case ISD::SETULE: X86CC = X86::COND_BE; break;
2068 case ISD::SETUGE: X86CC = X86::COND_AE; break;
2071 // On a floating point condition, the flags are set as follows:
2073 // 0 | 0 | 0 | X > Y
2074 // 0 | 0 | 1 | X < Y
2075 // 1 | 0 | 0 | X == Y
2076 // 1 | 1 | 1 | unordered
2078 switch (SetCCOpcode) {
2081 case ISD::SETEQ: X86CC = X86::COND_E; break;
2082 case ISD::SETOLT: Flip = true; // Fallthrough
2084 case ISD::SETGT: X86CC = X86::COND_A; break;
2085 case ISD::SETOLE: Flip = true; // Fallthrough
2087 case ISD::SETGE: X86CC = X86::COND_AE; break;
2088 case ISD::SETUGT: Flip = true; // Fallthrough
2090 case ISD::SETLT: X86CC = X86::COND_B; break;
2091 case ISD::SETUGE: Flip = true; // Fallthrough
2093 case ISD::SETLE: X86CC = X86::COND_BE; break;
2095 case ISD::SETNE: X86CC = X86::COND_NE; break;
2096 case ISD::SETUO: X86CC = X86::COND_P; break;
2097 case ISD::SETO: X86CC = X86::COND_NP; break;
2100 std::swap(LHS, RHS);
2103 return X86CC != X86::COND_INVALID;
2106 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2107 /// code. Current x86 isa includes the following FP cmov instructions:
2108 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2109 static bool hasFPCMov(unsigned X86CC) {
2125 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2126 /// true if Op is undef or if its value falls within the specified range (L, H].
2127 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2128 if (Op.getOpcode() == ISD::UNDEF)
2131 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2132 return (Val >= Low && Val < Hi);
2135 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2136 /// true if Op is undef or if its value equal to the specified value.
2137 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2138 if (Op.getOpcode() == ISD::UNDEF)
2140 return cast<ConstantSDNode>(Op)->getValue() == Val;
2143 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2144 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2145 bool X86::isPSHUFDMask(SDNode *N) {
2146 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2148 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2151 // Check if the value doesn't reference the second vector.
2152 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2153 SDOperand Arg = N->getOperand(i);
2154 if (Arg.getOpcode() == ISD::UNDEF) continue;
2155 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2156 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2163 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2164 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2165 bool X86::isPSHUFHWMask(SDNode *N) {
2166 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2168 if (N->getNumOperands() != 8)
2171 // Lower quadword copied in order.
2172 for (unsigned i = 0; i != 4; ++i) {
2173 SDOperand Arg = N->getOperand(i);
2174 if (Arg.getOpcode() == ISD::UNDEF) continue;
2175 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2176 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2180 // Upper quadword shuffled.
2181 for (unsigned i = 4; i != 8; ++i) {
2182 SDOperand Arg = N->getOperand(i);
2183 if (Arg.getOpcode() == ISD::UNDEF) continue;
2184 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2185 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2186 if (Val < 4 || Val > 7)
2193 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2194 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2195 bool X86::isPSHUFLWMask(SDNode *N) {
2196 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2198 if (N->getNumOperands() != 8)
2201 // Upper quadword copied in order.
2202 for (unsigned i = 4; i != 8; ++i)
2203 if (!isUndefOrEqual(N->getOperand(i), i))
2206 // Lower quadword shuffled.
2207 for (unsigned i = 0; i != 4; ++i)
2208 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2214 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2215 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2216 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2217 if (NumElems != 2 && NumElems != 4) return false;
2219 unsigned Half = NumElems / 2;
2220 for (unsigned i = 0; i < Half; ++i)
2221 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2223 for (unsigned i = Half; i < NumElems; ++i)
2224 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2230 bool X86::isSHUFPMask(SDNode *N) {
2231 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2232 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2235 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2236 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2237 /// half elements to come from vector 1 (which would equal the dest.) and
2238 /// the upper half to come from vector 2.
2239 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2240 if (NumOps != 2 && NumOps != 4) return false;
2242 unsigned Half = NumOps / 2;
2243 for (unsigned i = 0; i < Half; ++i)
2244 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2246 for (unsigned i = Half; i < NumOps; ++i)
2247 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2252 static bool isCommutedSHUFP(SDNode *N) {
2253 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2254 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2257 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2258 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2259 bool X86::isMOVHLPSMask(SDNode *N) {
2260 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2262 if (N->getNumOperands() != 4)
2265 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2266 return isUndefOrEqual(N->getOperand(0), 6) &&
2267 isUndefOrEqual(N->getOperand(1), 7) &&
2268 isUndefOrEqual(N->getOperand(2), 2) &&
2269 isUndefOrEqual(N->getOperand(3), 3);
2272 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2273 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2275 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2276 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2278 if (N->getNumOperands() != 4)
2281 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2282 return isUndefOrEqual(N->getOperand(0), 2) &&
2283 isUndefOrEqual(N->getOperand(1), 3) &&
2284 isUndefOrEqual(N->getOperand(2), 2) &&
2285 isUndefOrEqual(N->getOperand(3), 3);
2288 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2289 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2290 bool X86::isMOVLPMask(SDNode *N) {
2291 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2293 unsigned NumElems = N->getNumOperands();
2294 if (NumElems != 2 && NumElems != 4)
2297 for (unsigned i = 0; i < NumElems/2; ++i)
2298 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2301 for (unsigned i = NumElems/2; i < NumElems; ++i)
2302 if (!isUndefOrEqual(N->getOperand(i), i))
2308 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2309 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2311 bool X86::isMOVHPMask(SDNode *N) {
2312 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2314 unsigned NumElems = N->getNumOperands();
2315 if (NumElems != 2 && NumElems != 4)
2318 for (unsigned i = 0; i < NumElems/2; ++i)
2319 if (!isUndefOrEqual(N->getOperand(i), i))
2322 for (unsigned i = 0; i < NumElems/2; ++i) {
2323 SDOperand Arg = N->getOperand(i + NumElems/2);
2324 if (!isUndefOrEqual(Arg, i + NumElems))
2331 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2332 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2333 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2334 bool V2IsSplat = false) {
2335 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2338 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2339 SDOperand BitI = Elts[i];
2340 SDOperand BitI1 = Elts[i+1];
2341 if (!isUndefOrEqual(BitI, j))
2344 if (isUndefOrEqual(BitI1, NumElts))
2347 if (!isUndefOrEqual(BitI1, j + NumElts))
2355 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2356 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2357 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2360 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2361 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2362 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2363 bool V2IsSplat = false) {
2364 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2367 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2368 SDOperand BitI = Elts[i];
2369 SDOperand BitI1 = Elts[i+1];
2370 if (!isUndefOrEqual(BitI, j + NumElts/2))
2373 if (isUndefOrEqual(BitI1, NumElts))
2376 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2384 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2385 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2386 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2389 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2390 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2392 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2393 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2395 unsigned NumElems = N->getNumOperands();
2396 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2399 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2400 SDOperand BitI = N->getOperand(i);
2401 SDOperand BitI1 = N->getOperand(i+1);
2403 if (!isUndefOrEqual(BitI, j))
2405 if (!isUndefOrEqual(BitI1, j))
2412 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2413 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2415 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2416 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2418 unsigned NumElems = N->getNumOperands();
2419 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2422 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2423 SDOperand BitI = N->getOperand(i);
2424 SDOperand BitI1 = N->getOperand(i + 1);
2426 if (!isUndefOrEqual(BitI, j))
2428 if (!isUndefOrEqual(BitI1, j))
2435 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2436 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2437 /// MOVSD, and MOVD, i.e. setting the lowest element.
2438 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2439 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2442 if (!isUndefOrEqual(Elts[0], NumElts))
2445 for (unsigned i = 1; i < NumElts; ++i) {
2446 if (!isUndefOrEqual(Elts[i], i))
2453 bool X86::isMOVLMask(SDNode *N) {
2454 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2455 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2458 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2459 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2460 /// element of vector 2 and the other elements to come from vector 1 in order.
2461 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2462 bool V2IsSplat = false,
2463 bool V2IsUndef = false) {
2464 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2467 if (!isUndefOrEqual(Ops[0], 0))
2470 for (unsigned i = 1; i < NumOps; ++i) {
2471 SDOperand Arg = Ops[i];
2472 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2473 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2474 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2481 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2482 bool V2IsUndef = false) {
2483 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2484 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2485 V2IsSplat, V2IsUndef);
2488 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2489 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2490 bool X86::isMOVSHDUPMask(SDNode *N) {
2491 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2493 if (N->getNumOperands() != 4)
2496 // Expect 1, 1, 3, 3
2497 for (unsigned i = 0; i < 2; ++i) {
2498 SDOperand Arg = N->getOperand(i);
2499 if (Arg.getOpcode() == ISD::UNDEF) continue;
2500 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2501 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2502 if (Val != 1) return false;
2506 for (unsigned i = 2; i < 4; ++i) {
2507 SDOperand Arg = N->getOperand(i);
2508 if (Arg.getOpcode() == ISD::UNDEF) continue;
2509 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2510 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2511 if (Val != 3) return false;
2515 // Don't use movshdup if it can be done with a shufps.
2519 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2520 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2521 bool X86::isMOVSLDUPMask(SDNode *N) {
2522 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2524 if (N->getNumOperands() != 4)
2527 // Expect 0, 0, 2, 2
2528 for (unsigned i = 0; i < 2; ++i) {
2529 SDOperand Arg = N->getOperand(i);
2530 if (Arg.getOpcode() == ISD::UNDEF) continue;
2531 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2532 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2533 if (Val != 0) return false;
2537 for (unsigned i = 2; i < 4; ++i) {
2538 SDOperand Arg = N->getOperand(i);
2539 if (Arg.getOpcode() == ISD::UNDEF) continue;
2540 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2541 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2542 if (Val != 2) return false;
2546 // Don't use movshdup if it can be done with a shufps.
2550 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2551 /// specifies a identity operation on the LHS or RHS.
2552 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2553 unsigned NumElems = N->getNumOperands();
2554 for (unsigned i = 0; i < NumElems; ++i)
2555 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2560 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2561 /// a splat of a single element.
2562 static bool isSplatMask(SDNode *N) {
2563 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2565 // This is a splat operation if each element of the permute is the same, and
2566 // if the value doesn't reference the second vector.
2567 unsigned NumElems = N->getNumOperands();
2568 SDOperand ElementBase;
2570 for (; i != NumElems; ++i) {
2571 SDOperand Elt = N->getOperand(i);
2572 if (isa<ConstantSDNode>(Elt)) {
2578 if (!ElementBase.Val)
2581 for (; i != NumElems; ++i) {
2582 SDOperand Arg = N->getOperand(i);
2583 if (Arg.getOpcode() == ISD::UNDEF) continue;
2584 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2585 if (Arg != ElementBase) return false;
2588 // Make sure it is a splat of the first vector operand.
2589 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2592 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2593 /// a splat of a single element and it's a 2 or 4 element mask.
2594 bool X86::isSplatMask(SDNode *N) {
2595 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2597 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2598 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2600 return ::isSplatMask(N);
2603 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2604 /// specifies a splat of zero element.
2605 bool X86::isSplatLoMask(SDNode *N) {
2606 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2608 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2609 if (!isUndefOrEqual(N->getOperand(i), 0))
2614 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2615 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2617 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2618 unsigned NumOperands = N->getNumOperands();
2619 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2621 for (unsigned i = 0; i < NumOperands; ++i) {
2623 SDOperand Arg = N->getOperand(NumOperands-i-1);
2624 if (Arg.getOpcode() != ISD::UNDEF)
2625 Val = cast<ConstantSDNode>(Arg)->getValue();
2626 if (Val >= NumOperands) Val -= NumOperands;
2628 if (i != NumOperands - 1)
2635 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2636 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2638 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2640 // 8 nodes, but we only care about the last 4.
2641 for (unsigned i = 7; i >= 4; --i) {
2643 SDOperand Arg = N->getOperand(i);
2644 if (Arg.getOpcode() != ISD::UNDEF)
2645 Val = cast<ConstantSDNode>(Arg)->getValue();
2654 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2655 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2657 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2659 // 8 nodes, but we only care about the first 4.
2660 for (int i = 3; i >= 0; --i) {
2662 SDOperand Arg = N->getOperand(i);
2663 if (Arg.getOpcode() != ISD::UNDEF)
2664 Val = cast<ConstantSDNode>(Arg)->getValue();
2673 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2674 /// specifies a 8 element shuffle that can be broken into a pair of
2675 /// PSHUFHW and PSHUFLW.
2676 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2677 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2679 if (N->getNumOperands() != 8)
2682 // Lower quadword shuffled.
2683 for (unsigned i = 0; i != 4; ++i) {
2684 SDOperand Arg = N->getOperand(i);
2685 if (Arg.getOpcode() == ISD::UNDEF) continue;
2686 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2687 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2692 // Upper quadword shuffled.
2693 for (unsigned i = 4; i != 8; ++i) {
2694 SDOperand Arg = N->getOperand(i);
2695 if (Arg.getOpcode() == ISD::UNDEF) continue;
2696 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2697 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2698 if (Val < 4 || Val > 7)
2705 /// CommuteVectorShuffle - Swap vector_shuffle operandsas well as
2706 /// values in ther permute mask.
2707 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2708 SDOperand &V2, SDOperand &Mask,
2709 SelectionDAG &DAG) {
2710 MVT::ValueType VT = Op.getValueType();
2711 MVT::ValueType MaskVT = Mask.getValueType();
2712 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2713 unsigned NumElems = Mask.getNumOperands();
2714 SmallVector<SDOperand, 8> MaskVec;
2716 for (unsigned i = 0; i != NumElems; ++i) {
2717 SDOperand Arg = Mask.getOperand(i);
2718 if (Arg.getOpcode() == ISD::UNDEF) {
2719 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2722 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2723 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2725 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2727 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2731 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2732 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2735 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2736 /// match movhlps. The lower half elements should come from upper half of
2737 /// V1 (and in order), and the upper half elements should come from the upper
2738 /// half of V2 (and in order).
2739 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2740 unsigned NumElems = Mask->getNumOperands();
2743 for (unsigned i = 0, e = 2; i != e; ++i)
2744 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2746 for (unsigned i = 2; i != 4; ++i)
2747 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2752 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2753 /// is promoted to a vector.
2754 static inline bool isScalarLoadToVector(SDNode *N) {
2755 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2756 N = N->getOperand(0).Val;
2757 return ISD::isNON_EXTLoad(N);
2762 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2763 /// match movlp{s|d}. The lower half elements should come from lower half of
2764 /// V1 (and in order), and the upper half elements should come from the upper
2765 /// half of V2 (and in order). And since V1 will become the source of the
2766 /// MOVLP, it must be either a vector load or a scalar load to vector.
2767 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2768 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2770 // Is V2 is a vector load, don't do this transformation. We will try to use
2771 // load folding shufps op.
2772 if (ISD::isNON_EXTLoad(V2))
2775 unsigned NumElems = Mask->getNumOperands();
2776 if (NumElems != 2 && NumElems != 4)
2778 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2779 if (!isUndefOrEqual(Mask->getOperand(i), i))
2781 for (unsigned i = NumElems/2; i != NumElems; ++i)
2782 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2787 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2789 static bool isSplatVector(SDNode *N) {
2790 if (N->getOpcode() != ISD::BUILD_VECTOR)
2793 SDOperand SplatValue = N->getOperand(0);
2794 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2795 if (N->getOperand(i) != SplatValue)
2800 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2802 static bool isUndefShuffle(SDNode *N) {
2803 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2806 SDOperand V1 = N->getOperand(0);
2807 SDOperand V2 = N->getOperand(1);
2808 SDOperand Mask = N->getOperand(2);
2809 unsigned NumElems = Mask.getNumOperands();
2810 for (unsigned i = 0; i != NumElems; ++i) {
2811 SDOperand Arg = Mask.getOperand(i);
2812 if (Arg.getOpcode() != ISD::UNDEF) {
2813 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2814 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2816 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2823 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2825 static inline bool isZeroNode(SDOperand Elt) {
2826 return ((isa<ConstantSDNode>(Elt) &&
2827 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2828 (isa<ConstantFPSDNode>(Elt) &&
2829 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2832 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2833 /// to an zero vector.
2834 static bool isZeroShuffle(SDNode *N) {
2835 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2838 SDOperand V1 = N->getOperand(0);
2839 SDOperand V2 = N->getOperand(1);
2840 SDOperand Mask = N->getOperand(2);
2841 unsigned NumElems = Mask.getNumOperands();
2842 for (unsigned i = 0; i != NumElems; ++i) {
2843 SDOperand Arg = Mask.getOperand(i);
2844 if (Arg.getOpcode() != ISD::UNDEF) {
2845 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2846 if (Idx < NumElems) {
2847 unsigned Opc = V1.Val->getOpcode();
2848 if (Opc == ISD::UNDEF)
2850 if (Opc != ISD::BUILD_VECTOR ||
2851 !isZeroNode(V1.Val->getOperand(Idx)))
2853 } else if (Idx >= NumElems) {
2854 unsigned Opc = V2.Val->getOpcode();
2855 if (Opc == ISD::UNDEF)
2857 if (Opc != ISD::BUILD_VECTOR ||
2858 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2866 /// getZeroVector - Returns a vector of specified type with all zero elements.
2868 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2869 assert(MVT::isVector(VT) && "Expected a vector type");
2870 unsigned NumElems = MVT::getVectorNumElements(VT);
2871 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2872 bool isFP = MVT::isFloatingPoint(EVT);
2873 SDOperand Zero = isFP ? DAG.getConstantFP(0.0, EVT) : DAG.getConstant(0, EVT);
2874 SmallVector<SDOperand, 8> ZeroVec(NumElems, Zero);
2875 return DAG.getNode(ISD::BUILD_VECTOR, VT, &ZeroVec[0], ZeroVec.size());
2878 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2879 /// that point to V2 points to its first element.
2880 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2881 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2883 bool Changed = false;
2884 SmallVector<SDOperand, 8> MaskVec;
2885 unsigned NumElems = Mask.getNumOperands();
2886 for (unsigned i = 0; i != NumElems; ++i) {
2887 SDOperand Arg = Mask.getOperand(i);
2888 if (Arg.getOpcode() != ISD::UNDEF) {
2889 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2890 if (Val > NumElems) {
2891 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2895 MaskVec.push_back(Arg);
2899 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2900 &MaskVec[0], MaskVec.size());
2904 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2905 /// operation of specified width.
2906 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2907 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2908 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2910 SmallVector<SDOperand, 8> MaskVec;
2911 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2912 for (unsigned i = 1; i != NumElems; ++i)
2913 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2914 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2917 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2918 /// of specified width.
2919 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2920 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2921 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2922 SmallVector<SDOperand, 8> MaskVec;
2923 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2924 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2925 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2927 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2930 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2931 /// of specified width.
2932 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2933 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2934 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2935 unsigned Half = NumElems/2;
2936 SmallVector<SDOperand, 8> MaskVec;
2937 for (unsigned i = 0; i != Half; ++i) {
2938 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2939 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2941 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2944 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2946 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2947 SDOperand V1 = Op.getOperand(0);
2948 SDOperand Mask = Op.getOperand(2);
2949 MVT::ValueType VT = Op.getValueType();
2950 unsigned NumElems = Mask.getNumOperands();
2951 Mask = getUnpacklMask(NumElems, DAG);
2952 while (NumElems != 4) {
2953 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2956 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2958 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2959 Mask = getZeroVector(MaskVT, DAG);
2960 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2961 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2962 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2965 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2966 /// vector of zero or undef vector.
2967 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2968 unsigned NumElems, unsigned Idx,
2969 bool isZero, SelectionDAG &DAG) {
2970 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2971 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2972 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2973 SDOperand Zero = DAG.getConstant(0, EVT);
2974 SmallVector<SDOperand, 8> MaskVec(NumElems, Zero);
2975 MaskVec[Idx] = DAG.getConstant(NumElems, EVT);
2976 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2977 &MaskVec[0], MaskVec.size());
2978 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2981 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2983 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2984 unsigned NumNonZero, unsigned NumZero,
2985 SelectionDAG &DAG, TargetLowering &TLI) {
2991 for (unsigned i = 0; i < 16; ++i) {
2992 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2993 if (ThisIsNonZero && First) {
2995 V = getZeroVector(MVT::v8i16, DAG);
2997 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3002 SDOperand ThisElt(0, 0), LastElt(0, 0);
3003 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3004 if (LastIsNonZero) {
3005 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3007 if (ThisIsNonZero) {
3008 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3009 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3010 ThisElt, DAG.getConstant(8, MVT::i8));
3012 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3017 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3018 DAG.getConstant(i/2, TLI.getPointerTy()));
3022 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3025 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3027 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3028 unsigned NumNonZero, unsigned NumZero,
3029 SelectionDAG &DAG, TargetLowering &TLI) {
3035 for (unsigned i = 0; i < 8; ++i) {
3036 bool isNonZero = (NonZeros & (1 << i)) != 0;
3040 V = getZeroVector(MVT::v8i16, DAG);
3042 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3045 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3046 DAG.getConstant(i, TLI.getPointerTy()));
3054 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3055 // All zero's are handled with pxor.
3056 if (ISD::isBuildVectorAllZeros(Op.Val))
3059 // All one's are handled with pcmpeqd.
3060 if (ISD::isBuildVectorAllOnes(Op.Val))
3063 MVT::ValueType VT = Op.getValueType();
3064 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3065 unsigned EVTBits = MVT::getSizeInBits(EVT);
3067 unsigned NumElems = Op.getNumOperands();
3068 unsigned NumZero = 0;
3069 unsigned NumNonZero = 0;
3070 unsigned NonZeros = 0;
3071 unsigned NumNonZeroImms = 0;
3072 std::set<SDOperand> Values;
3073 for (unsigned i = 0; i < NumElems; ++i) {
3074 SDOperand Elt = Op.getOperand(i);
3075 if (Elt.getOpcode() != ISD::UNDEF) {
3077 if (isZeroNode(Elt))
3080 NonZeros |= (1 << i);
3082 if (Elt.getOpcode() == ISD::Constant ||
3083 Elt.getOpcode() == ISD::ConstantFP)
3089 if (NumNonZero == 0) {
3091 // All undef vector. Return an UNDEF.
3092 return DAG.getNode(ISD::UNDEF, VT);
3094 // A mix of zero and undef. Return a zero vector.
3095 return getZeroVector(VT, DAG);
3098 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3099 if (Values.size() == 1)
3102 // Special case for single non-zero element.
3103 if (NumNonZero == 1) {
3104 unsigned Idx = CountTrailingZeros_32(NonZeros);
3105 SDOperand Item = Op.getOperand(Idx);
3106 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3108 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3109 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
3112 if (EVTBits == 32) {
3113 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3114 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
3116 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3117 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3118 SmallVector<SDOperand, 8> MaskVec;
3119 for (unsigned i = 0; i < NumElems; i++)
3120 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3121 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3122 &MaskVec[0], MaskVec.size());
3123 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3124 DAG.getNode(ISD::UNDEF, VT), Mask);
3128 // A vector full of immediates; various special cases are already
3129 // handled, so this is best done with a single constant-pool load.
3130 if (NumNonZero == NumNonZeroImms)
3133 // Let legalizer expand 2-wide build_vectors.
3137 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3138 if (EVTBits == 8 && NumElems == 16) {
3139 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3141 if (V.Val) return V;
3144 if (EVTBits == 16 && NumElems == 8) {
3145 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3147 if (V.Val) return V;
3150 // If element VT is == 32 bits, turn it into a number of shuffles.
3151 SmallVector<SDOperand, 8> V;
3153 if (NumElems == 4 && NumZero > 0) {
3154 for (unsigned i = 0; i < 4; ++i) {
3155 bool isZero = !(NonZeros & (1 << i));
3157 V[i] = getZeroVector(VT, DAG);
3159 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3162 for (unsigned i = 0; i < 2; ++i) {
3163 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3166 V[i] = V[i*2]; // Must be a zero vector.
3169 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3170 getMOVLMask(NumElems, DAG));
3173 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3174 getMOVLMask(NumElems, DAG));
3177 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3178 getUnpacklMask(NumElems, DAG));
3183 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3184 // clears the upper bits.
3185 // FIXME: we can do the same for v4f32 case when we know both parts of
3186 // the lower half come from scalar_to_vector (loadf32). We should do
3187 // that in post legalizer dag combiner with target specific hooks.
3188 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3190 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3191 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3192 SmallVector<SDOperand, 8> MaskVec;
3193 bool Reverse = (NonZeros & 0x3) == 2;
3194 for (unsigned i = 0; i < 2; ++i)
3196 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3198 MaskVec.push_back(DAG.getConstant(i, EVT));
3199 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3200 for (unsigned i = 0; i < 2; ++i)
3202 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3204 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3205 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3206 &MaskVec[0], MaskVec.size());
3207 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3210 if (Values.size() > 2) {
3211 // Expand into a number of unpckl*.
3213 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3214 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3215 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3216 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3217 for (unsigned i = 0; i < NumElems; ++i)
3218 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3220 while (NumElems != 0) {
3221 for (unsigned i = 0; i < NumElems; ++i)
3222 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3233 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3234 SDOperand V1 = Op.getOperand(0);
3235 SDOperand V2 = Op.getOperand(1);
3236 SDOperand PermMask = Op.getOperand(2);
3237 MVT::ValueType VT = Op.getValueType();
3238 unsigned NumElems = PermMask.getNumOperands();
3239 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3240 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3241 bool V1IsSplat = false;
3242 bool V2IsSplat = false;
3244 if (isUndefShuffle(Op.Val))
3245 return DAG.getNode(ISD::UNDEF, VT);
3247 if (isZeroShuffle(Op.Val))
3248 return getZeroVector(VT, DAG);
3250 if (isIdentityMask(PermMask.Val))
3252 else if (isIdentityMask(PermMask.Val, true))
3255 if (isSplatMask(PermMask.Val)) {
3256 if (NumElems <= 4) return Op;
3257 // Promote it to a v4i32 splat.
3258 return PromoteSplat(Op, DAG);
3261 if (X86::isMOVLMask(PermMask.Val))
3262 return (V1IsUndef) ? V2 : Op;
3264 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3265 X86::isMOVSLDUPMask(PermMask.Val) ||
3266 X86::isMOVHLPSMask(PermMask.Val) ||
3267 X86::isMOVHPMask(PermMask.Val) ||
3268 X86::isMOVLPMask(PermMask.Val))
3271 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3272 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3273 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3275 bool Commuted = false;
3276 V1IsSplat = isSplatVector(V1.Val);
3277 V2IsSplat = isSplatVector(V2.Val);
3278 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3279 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3280 std::swap(V1IsSplat, V2IsSplat);
3281 std::swap(V1IsUndef, V2IsUndef);
3285 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3286 if (V2IsUndef) return V1;
3287 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3289 // V2 is a splat, so the mask may be malformed. That is, it may point
3290 // to any V2 element. The instruction selectior won't like this. Get
3291 // a corrected mask and commute to form a proper MOVS{S|D}.
3292 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3293 if (NewMask.Val != PermMask.Val)
3294 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3299 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3300 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3301 X86::isUNPCKLMask(PermMask.Val) ||
3302 X86::isUNPCKHMask(PermMask.Val))
3306 // Normalize mask so all entries that point to V2 points to its first
3307 // element then try to match unpck{h|l} again. If match, return a
3308 // new vector_shuffle with the corrected mask.
3309 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3310 if (NewMask.Val != PermMask.Val) {
3311 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3312 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3313 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3314 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3315 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3316 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3321 // Normalize the node to match x86 shuffle ops if needed
3322 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3323 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3326 // Commute is back and try unpck* again.
3327 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3328 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3329 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3330 X86::isUNPCKLMask(PermMask.Val) ||
3331 X86::isUNPCKHMask(PermMask.Val))
3335 // If VT is integer, try PSHUF* first, then SHUFP*.
3336 if (MVT::isInteger(VT)) {
3337 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3338 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3339 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3340 X86::isPSHUFDMask(PermMask.Val)) ||
3341 X86::isPSHUFHWMask(PermMask.Val) ||
3342 X86::isPSHUFLWMask(PermMask.Val)) {
3343 if (V2.getOpcode() != ISD::UNDEF)
3344 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3345 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3349 if (X86::isSHUFPMask(PermMask.Val) &&
3350 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3353 // Handle v8i16 shuffle high / low shuffle node pair.
3354 if (VT == MVT::v8i16 && isPSHUFHW_PSHUFLWMask(PermMask.Val)) {
3355 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3356 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3357 SmallVector<SDOperand, 8> MaskVec;
3358 for (unsigned i = 0; i != 4; ++i)
3359 MaskVec.push_back(PermMask.getOperand(i));
3360 for (unsigned i = 4; i != 8; ++i)
3361 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3362 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3363 &MaskVec[0], MaskVec.size());
3364 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3366 for (unsigned i = 0; i != 4; ++i)
3367 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3368 for (unsigned i = 4; i != 8; ++i)
3369 MaskVec.push_back(PermMask.getOperand(i));
3370 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0],MaskVec.size());
3371 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3374 // Floating point cases in the other order.
3375 if (X86::isSHUFPMask(PermMask.Val))
3377 if (X86::isPSHUFDMask(PermMask.Val) ||
3378 X86::isPSHUFHWMask(PermMask.Val) ||
3379 X86::isPSHUFLWMask(PermMask.Val)) {
3380 if (V2.getOpcode() != ISD::UNDEF)
3381 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3382 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3387 if (NumElems == 4 &&
3388 // Don't do this for MMX.
3389 MVT::getSizeInBits(VT) != 64) {
3390 MVT::ValueType MaskVT = PermMask.getValueType();
3391 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3392 SmallVector<std::pair<int, int>, 8> Locs;
3393 Locs.reserve(NumElems);
3394 SmallVector<SDOperand, 8> Mask1(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3395 SmallVector<SDOperand, 8> Mask2(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3398 // If no more than two elements come from either vector. This can be
3399 // implemented with two shuffles. First shuffle gather the elements.
3400 // The second shuffle, which takes the first shuffle as both of its
3401 // vector operands, put the elements into the right order.
3402 for (unsigned i = 0; i != NumElems; ++i) {
3403 SDOperand Elt = PermMask.getOperand(i);
3404 if (Elt.getOpcode() == ISD::UNDEF) {
3405 Locs[i] = std::make_pair(-1, -1);
3407 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3408 if (Val < NumElems) {
3409 Locs[i] = std::make_pair(0, NumLo);
3413 Locs[i] = std::make_pair(1, NumHi);
3414 if (2+NumHi < NumElems)
3415 Mask1[2+NumHi] = Elt;
3420 if (NumLo <= 2 && NumHi <= 2) {
3421 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3422 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3423 &Mask1[0], Mask1.size()));
3424 for (unsigned i = 0; i != NumElems; ++i) {
3425 if (Locs[i].first == -1)
3428 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3429 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3430 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3434 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3435 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3436 &Mask2[0], Mask2.size()));
3439 // Break it into (shuffle shuffle_hi, shuffle_lo).
3441 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3442 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3443 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3444 unsigned MaskIdx = 0;
3446 unsigned HiIdx = NumElems/2;
3447 for (unsigned i = 0; i != NumElems; ++i) {
3448 if (i == NumElems/2) {
3454 SDOperand Elt = PermMask.getOperand(i);
3455 if (Elt.getOpcode() == ISD::UNDEF) {
3456 Locs[i] = std::make_pair(-1, -1);
3457 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3458 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3459 (*MaskPtr)[LoIdx] = Elt;
3462 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3463 (*MaskPtr)[HiIdx] = Elt;
3468 SDOperand LoShuffle =
3469 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3470 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3471 &LoMask[0], LoMask.size()));
3472 SDOperand HiShuffle =
3473 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3474 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3475 &HiMask[0], HiMask.size()));
3476 SmallVector<SDOperand, 8> MaskOps;
3477 for (unsigned i = 0; i != NumElems; ++i) {
3478 if (Locs[i].first == -1) {
3479 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3481 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3482 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3485 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3486 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3487 &MaskOps[0], MaskOps.size()));
3494 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3495 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3498 MVT::ValueType VT = Op.getValueType();
3499 // TODO: handle v16i8.
3500 if (MVT::getSizeInBits(VT) == 16) {
3501 // Transform it so it match pextrw which produces a 32-bit result.
3502 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3503 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3504 Op.getOperand(0), Op.getOperand(1));
3505 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3506 DAG.getValueType(VT));
3507 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3508 } else if (MVT::getSizeInBits(VT) == 32) {
3509 SDOperand Vec = Op.getOperand(0);
3510 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3513 // SHUFPS the element to the lowest double word, then movss.
3514 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3515 SmallVector<SDOperand, 8> IdxVec;
3517 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3519 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3521 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3523 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3524 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3525 &IdxVec[0], IdxVec.size());
3526 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3527 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3528 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3529 DAG.getConstant(0, getPointerTy()));
3530 } else if (MVT::getSizeInBits(VT) == 64) {
3531 SDOperand Vec = Op.getOperand(0);
3532 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3536 // UNPCKHPD the element to the lowest double word, then movsd.
3537 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3538 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3539 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3540 SmallVector<SDOperand, 8> IdxVec;
3541 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3543 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3544 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3545 &IdxVec[0], IdxVec.size());
3546 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3547 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3548 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3549 DAG.getConstant(0, getPointerTy()));
3556 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3557 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3558 // as its second argument.
3559 MVT::ValueType VT = Op.getValueType();
3560 MVT::ValueType BaseVT = MVT::getVectorElementType(VT);
3561 SDOperand N0 = Op.getOperand(0);
3562 SDOperand N1 = Op.getOperand(1);
3563 SDOperand N2 = Op.getOperand(2);
3564 if (MVT::getSizeInBits(BaseVT) == 16) {
3565 if (N1.getValueType() != MVT::i32)
3566 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3567 if (N2.getValueType() != MVT::i32)
3568 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
3569 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3570 } else if (MVT::getSizeInBits(BaseVT) == 32) {
3571 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
3574 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
3575 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3576 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3577 SmallVector<SDOperand, 8> MaskVec;
3578 MaskVec.push_back(DAG.getConstant(4, BaseVT));
3579 for (unsigned i = 1; i <= 3; ++i)
3580 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3581 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
3582 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3583 &MaskVec[0], MaskVec.size()));
3585 // Use two pinsrw instructions to insert a 32 bit value.
3587 if (MVT::isFloatingPoint(N1.getValueType())) {
3588 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
3589 N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
3590 N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
3591 DAG.getConstant(0, getPointerTy()));
3593 N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
3594 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3595 DAG.getConstant(Idx, getPointerTy()));
3596 N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
3597 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3598 DAG.getConstant(Idx+1, getPointerTy()));
3599 return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3607 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3608 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3609 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3612 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3613 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3614 // one of the above mentioned nodes. It has to be wrapped because otherwise
3615 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3616 // be used to form addressing mode. These wrapped nodes will be selected
3619 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3620 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3621 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3623 CP->getAlignment());
3624 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3625 // With PIC, the address is actually $g + Offset.
3626 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3627 !Subtarget->isPICStyleRIPRel()) {
3628 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3629 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3637 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3638 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3639 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3640 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3641 // With PIC, the address is actually $g + Offset.
3642 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3643 !Subtarget->isPICStyleRIPRel()) {
3644 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3645 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3649 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3650 // load the value at address GV, not the value of GV itself. This means that
3651 // the GlobalAddress must be in the base or index register of the address, not
3652 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3653 // The same applies for external symbols during PIC codegen
3654 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3655 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
3660 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3662 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3663 const MVT::ValueType PtrVT) {
3665 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3666 DAG.getNode(X86ISD::GlobalBaseReg,
3668 InFlag = Chain.getValue(1);
3670 // emit leal symbol@TLSGD(,%ebx,1), %eax
3671 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3672 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3673 GA->getValueType(0),
3675 SDOperand Ops[] = { Chain, TGA, InFlag };
3676 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3677 InFlag = Result.getValue(2);
3678 Chain = Result.getValue(1);
3680 // call ___tls_get_addr. This function receives its argument in
3681 // the register EAX.
3682 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3683 InFlag = Chain.getValue(1);
3685 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3686 SDOperand Ops1[] = { Chain,
3687 DAG.getTargetExternalSymbol("___tls_get_addr",
3689 DAG.getRegister(X86::EAX, PtrVT),
3690 DAG.getRegister(X86::EBX, PtrVT),
3692 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3693 InFlag = Chain.getValue(1);
3695 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3698 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3699 // "local exec" model.
3701 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3702 const MVT::ValueType PtrVT) {
3703 // Get the Thread Pointer
3704 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3705 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3707 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3708 GA->getValueType(0),
3710 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3712 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3713 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
3715 // The address of the thread local variable is the add of the thread
3716 // pointer with the offset of the variable.
3717 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3721 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3722 // TODO: implement the "local dynamic" model
3723 // TODO: implement the "initial exec"model for pic executables
3724 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3725 "TLS not implemented for non-ELF and 64-bit targets");
3726 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3727 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3728 // otherwise use the "Local Exec"TLS Model
3729 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3730 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3732 return LowerToTLSExecModel(GA, DAG, getPointerTy());
3736 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3737 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3738 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3739 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3740 // With PIC, the address is actually $g + Offset.
3741 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3742 !Subtarget->isPICStyleRIPRel()) {
3743 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3744 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3751 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3752 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3753 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3754 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3755 // With PIC, the address is actually $g + Offset.
3756 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3757 !Subtarget->isPICStyleRIPRel()) {
3758 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3759 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3766 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
3767 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
3768 "Not an i64 shift!");
3769 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
3770 SDOperand ShOpLo = Op.getOperand(0);
3771 SDOperand ShOpHi = Op.getOperand(1);
3772 SDOperand ShAmt = Op.getOperand(2);
3773 SDOperand Tmp1 = isSRA ?
3774 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
3775 DAG.getConstant(0, MVT::i32);
3777 SDOperand Tmp2, Tmp3;
3778 if (Op.getOpcode() == ISD::SHL_PARTS) {
3779 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
3780 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
3782 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
3783 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
3786 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3787 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
3788 DAG.getConstant(32, MVT::i8));
3789 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
3790 AndNode, DAG.getConstant(0, MVT::i8));
3793 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3794 unsigned Opc = X86ISD::CMOV;
3795 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
3796 SmallVector<SDOperand, 4> Ops;
3797 if (Op.getOpcode() == ISD::SHL_PARTS) {
3798 Ops.push_back(Tmp2);
3799 Ops.push_back(Tmp3);
3801 Ops.push_back(Cond);
3802 Hi = DAG.getNode(Opc, MVT::i32, &Ops[0], Ops.size());
3805 Ops.push_back(Tmp3);
3806 Ops.push_back(Tmp1);
3808 Ops.push_back(Cond);
3809 Lo = DAG.getNode(Opc, MVT::i32, &Ops[0], Ops.size());
3811 Ops.push_back(Tmp2);
3812 Ops.push_back(Tmp3);
3814 Ops.push_back(Cond);
3815 Lo = DAG.getNode(Opc, MVT::i32, &Ops[0], Ops.size());
3818 Ops.push_back(Tmp3);
3819 Ops.push_back(Tmp1);
3821 Ops.push_back(Cond);
3822 Hi = DAG.getNode(Opc, MVT::i32, &Ops[0], Ops.size());
3825 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
3829 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
3832 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
3833 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
3834 Op.getOperand(0).getValueType() >= MVT::i16 &&
3835 "Unknown SINT_TO_FP to lower!");
3838 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
3839 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
3840 MachineFunction &MF = DAG.getMachineFunction();
3841 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
3842 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3843 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
3844 StackSlot, NULL, 0);
3846 // These are really Legal; caller falls through into that case.
3847 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f32 && X86ScalarSSEf32)
3849 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f64 && X86ScalarSSEf64)
3851 if (SrcVT==MVT::i64 && Op.getValueType() != MVT::f80 &&
3852 Subtarget->is64Bit())
3857 bool useSSE = (X86ScalarSSEf32 && Op.getValueType() == MVT::f32) ||
3858 (X86ScalarSSEf64 && Op.getValueType() == MVT::f64);
3860 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
3862 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
3863 SmallVector<SDOperand, 8> Ops;
3864 Ops.push_back(Chain);
3865 Ops.push_back(StackSlot);
3866 Ops.push_back(DAG.getValueType(SrcVT));
3867 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
3868 Tys, &Ops[0], Ops.size());
3871 Chain = Result.getValue(1);
3872 SDOperand InFlag = Result.getValue(2);
3874 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
3875 // shouldn't be necessary except that RFP cannot be live across
3876 // multiple blocks. When stackifier is fixed, they can be uncoupled.
3877 MachineFunction &MF = DAG.getMachineFunction();
3878 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3879 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3880 Tys = DAG.getVTList(MVT::Other);
3881 SmallVector<SDOperand, 8> Ops;
3882 Ops.push_back(Chain);
3883 Ops.push_back(Result);
3884 Ops.push_back(StackSlot);
3885 Ops.push_back(DAG.getValueType(Op.getValueType()));
3886 Ops.push_back(InFlag);
3887 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
3888 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
3894 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
3895 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
3896 "Unknown FP_TO_SINT to lower!");
3897 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
3900 MachineFunction &MF = DAG.getMachineFunction();
3901 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
3902 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3903 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3905 // These are really Legal.
3906 if (Op.getValueType() == MVT::i32 &&
3907 X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32)
3909 if (Op.getValueType() == MVT::i32 &&
3910 X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)
3912 if (Subtarget->is64Bit() &&
3913 Op.getValueType() == MVT::i64 &&
3914 Op.getOperand(0).getValueType() != MVT::f80)
3918 switch (Op.getValueType()) {
3919 default: assert(0 && "Invalid FP_TO_SINT to lower!");
3920 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
3921 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
3922 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
3925 SDOperand Chain = DAG.getEntryNode();
3926 SDOperand Value = Op.getOperand(0);
3927 if ((X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32) ||
3928 (X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)) {
3929 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
3930 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
3931 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
3933 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
3935 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
3936 Chain = Value.getValue(1);
3937 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3938 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3941 // Build the FP_TO_INT*_IN_MEM
3942 SDOperand Ops[] = { Chain, Value, StackSlot };
3943 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
3946 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
3949 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
3950 MVT::ValueType VT = Op.getValueType();
3951 MVT::ValueType EltVT = VT;
3952 if (MVT::isVector(VT))
3953 EltVT = MVT::getVectorElementType(VT);
3954 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
3955 std::vector<Constant*> CV;
3956 if (EltVT == MVT::f64) {
3957 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
3961 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
3967 Constant *C = ConstantVector::get(CV);
3968 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
3969 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
3971 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
3974 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
3975 MVT::ValueType VT = Op.getValueType();
3976 MVT::ValueType EltVT = VT;
3977 unsigned EltNum = 1;
3978 if (MVT::isVector(VT)) {
3979 EltVT = MVT::getVectorElementType(VT);
3980 EltNum = MVT::getVectorNumElements(VT);
3982 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
3983 std::vector<Constant*> CV;
3984 if (EltVT == MVT::f64) {
3985 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
3989 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
3995 Constant *C = ConstantVector::get(CV);
3996 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
3997 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
3999 if (MVT::isVector(VT)) {
4000 return DAG.getNode(ISD::BIT_CONVERT, VT,
4001 DAG.getNode(ISD::XOR, MVT::v2i64,
4002 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4003 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4005 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4009 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4010 SDOperand Op0 = Op.getOperand(0);
4011 SDOperand Op1 = Op.getOperand(1);
4012 MVT::ValueType VT = Op.getValueType();
4013 MVT::ValueType SrcVT = Op1.getValueType();
4014 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4016 // If second operand is smaller, extend it first.
4017 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4018 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4020 SrcTy = MVT::getTypeForValueType(SrcVT);
4023 // First get the sign bit of second operand.
4024 std::vector<Constant*> CV;
4025 if (SrcVT == MVT::f64) {
4026 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4027 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4029 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4030 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4031 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4032 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4034 Constant *C = ConstantVector::get(CV);
4035 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4036 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx, NULL, 0,
4038 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4040 // Shift sign bit right or left if the two operands have different types.
4041 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4042 // Op0 is MVT::f32, Op1 is MVT::f64.
4043 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4044 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4045 DAG.getConstant(32, MVT::i32));
4046 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4047 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4048 DAG.getConstant(0, getPointerTy()));
4051 // Clear first operand sign bit.
4053 if (VT == MVT::f64) {
4054 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4055 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4057 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4058 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4059 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4060 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4062 C = ConstantVector::get(CV);
4063 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4064 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4066 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4068 // Or the value with the sign bit.
4069 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4072 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4073 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4075 SDOperand Op0 = Op.getOperand(0);
4076 SDOperand Op1 = Op.getOperand(1);
4077 SDOperand CC = Op.getOperand(2);
4078 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4079 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4082 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4084 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4085 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4086 DAG.getConstant(X86CC, MVT::i8), Cond);
4089 assert(isFP && "Illegal integer SetCC!");
4091 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4092 switch (SetCCOpcode) {
4093 default: assert(false && "Illegal floating point SetCC!");
4094 case ISD::SETOEQ: { // !PF & ZF
4095 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4096 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4097 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4098 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4099 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4101 case ISD::SETUNE: { // PF | !ZF
4102 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4103 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4104 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4105 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4106 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4112 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4113 bool addTest = true;
4114 SDOperand Cond = Op.getOperand(0);
4117 if (Cond.getOpcode() == ISD::SETCC)
4118 Cond = LowerSETCC(Cond, DAG);
4120 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4121 // setting operand in place of the X86ISD::SETCC.
4122 if (Cond.getOpcode() == X86ISD::SETCC) {
4123 CC = Cond.getOperand(0);
4125 SDOperand Cmp = Cond.getOperand(1);
4126 unsigned Opc = Cmp.getOpcode();
4127 MVT::ValueType VT = Op.getValueType();
4128 bool IllegalFPCMov = false;
4129 if (VT == MVT::f32 && !X86ScalarSSEf32)
4130 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4131 else if (VT == MVT::f64 && !X86ScalarSSEf64)
4132 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4133 if ((Opc == X86ISD::CMP ||
4134 Opc == X86ISD::COMI ||
4135 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4142 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4143 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4146 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4148 SmallVector<SDOperand, 4> Ops;
4149 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4150 // condition is true.
4151 Ops.push_back(Op.getOperand(2));
4152 Ops.push_back(Op.getOperand(1));
4154 Ops.push_back(Cond);
4155 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4158 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4159 bool addTest = true;
4160 SDOperand Chain = Op.getOperand(0);
4161 SDOperand Cond = Op.getOperand(1);
4162 SDOperand Dest = Op.getOperand(2);
4165 if (Cond.getOpcode() == ISD::SETCC)
4166 Cond = LowerSETCC(Cond, DAG);
4168 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4169 // setting operand in place of the X86ISD::SETCC.
4170 if (Cond.getOpcode() == X86ISD::SETCC) {
4171 CC = Cond.getOperand(0);
4173 SDOperand Cmp = Cond.getOperand(1);
4174 unsigned Opc = Cmp.getOpcode();
4175 if (Opc == X86ISD::CMP ||
4176 Opc == X86ISD::COMI ||
4177 Opc == X86ISD::UCOMI) {
4184 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4185 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4187 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4188 Chain, Op.getOperand(2), CC, Cond);
4191 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
4192 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4193 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
4195 if (Subtarget->is64Bit())
4196 if(CallingConv==CallingConv::Fast && isTailCall && PerformTailCallOpt)
4197 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4199 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
4201 switch (CallingConv) {
4203 assert(0 && "Unsupported calling convention");
4204 case CallingConv::Fast:
4205 if (isTailCall && PerformTailCallOpt)
4206 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4208 return LowerCCCCallTo(Op,DAG, CallingConv);
4209 case CallingConv::C:
4210 case CallingConv::X86_StdCall:
4211 return LowerCCCCallTo(Op, DAG, CallingConv);
4212 case CallingConv::X86_FastCall:
4213 return LowerFastCCCallTo(Op, DAG, CallingConv);
4218 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4219 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4220 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4221 // that the guard pages used by the OS virtual memory manager are allocated in
4222 // correct sequence.
4224 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4225 SelectionDAG &DAG) {
4226 assert(Subtarget->isTargetCygMing() &&
4227 "This should be used only on Cygwin/Mingw targets");
4230 SDOperand Chain = Op.getOperand(0);
4231 SDOperand Size = Op.getOperand(1);
4232 // FIXME: Ensure alignment here
4236 MVT::ValueType IntPtr = getPointerTy();
4237 MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
4239 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4240 Flag = Chain.getValue(1);
4242 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4243 SDOperand Ops[] = { Chain,
4244 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4245 DAG.getRegister(X86::EAX, IntPtr),
4247 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4248 Flag = Chain.getValue(1);
4250 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4252 std::vector<MVT::ValueType> Tys;
4253 Tys.push_back(SPTy);
4254 Tys.push_back(MVT::Other);
4255 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4256 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4260 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
4261 MachineFunction &MF = DAG.getMachineFunction();
4262 const Function* Fn = MF.getFunction();
4263 if (Fn->hasExternalLinkage() &&
4264 Subtarget->isTargetCygMing() &&
4265 Fn->getName() == "main")
4266 MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
4268 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4269 if (Subtarget->is64Bit())
4270 return LowerX86_64CCCArguments(Op, DAG);
4274 assert(0 && "Unsupported calling convention");
4275 case CallingConv::Fast:
4276 return LowerCCCArguments(Op,DAG, true);
4278 case CallingConv::C:
4279 return LowerCCCArguments(Op, DAG);
4280 case CallingConv::X86_StdCall:
4281 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
4282 return LowerCCCArguments(Op, DAG, true);
4283 case CallingConv::X86_FastCall:
4284 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
4285 return LowerFastCCArguments(Op, DAG);
4289 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4290 SDOperand InFlag(0, 0);
4291 SDOperand Chain = Op.getOperand(0);
4293 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4294 if (Align == 0) Align = 1;
4296 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4297 // If not DWORD aligned or size is more than the threshold, call memset.
4298 // The libc version is likely to be faster for these cases. It can use the
4299 // address value and run time information about the CPU.
4300 if ((Align & 3) != 0 ||
4301 (I && I->getValue() > Subtarget->getMinRepStrSizeThreshold())) {
4302 MVT::ValueType IntPtr = getPointerTy();
4303 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4304 TargetLowering::ArgListTy Args;
4305 TargetLowering::ArgListEntry Entry;
4306 Entry.Node = Op.getOperand(1);
4307 Entry.Ty = IntPtrTy;
4308 Args.push_back(Entry);
4309 // Extend the unsigned i8 argument to be an int value for the call.
4310 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4311 Entry.Ty = IntPtrTy;
4312 Args.push_back(Entry);
4313 Entry.Node = Op.getOperand(3);
4314 Args.push_back(Entry);
4315 std::pair<SDOperand,SDOperand> CallResult =
4316 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4317 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4318 return CallResult.second;
4323 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4324 unsigned BytesLeft = 0;
4325 bool TwoRepStos = false;
4328 uint64_t Val = ValC->getValue() & 255;
4330 // If the value is a constant, then we can potentially use larger sets.
4331 switch (Align & 3) {
4332 case 2: // WORD aligned
4335 Val = (Val << 8) | Val;
4337 case 0: // DWORD aligned
4340 Val = (Val << 8) | Val;
4341 Val = (Val << 16) | Val;
4342 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4345 Val = (Val << 32) | Val;
4348 default: // Byte aligned
4351 Count = Op.getOperand(3);
4355 if (AVT > MVT::i8) {
4357 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4358 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
4359 BytesLeft = I->getValue() % UBytes;
4361 assert(AVT >= MVT::i32 &&
4362 "Do not use rep;stos if not at least DWORD aligned");
4363 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4364 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4369 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4371 InFlag = Chain.getValue(1);
4374 Count = Op.getOperand(3);
4375 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4376 InFlag = Chain.getValue(1);
4379 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4381 InFlag = Chain.getValue(1);
4382 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4383 Op.getOperand(1), InFlag);
4384 InFlag = Chain.getValue(1);
4386 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4387 SmallVector<SDOperand, 8> Ops;
4388 Ops.push_back(Chain);
4389 Ops.push_back(DAG.getValueType(AVT));
4390 Ops.push_back(InFlag);
4391 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4394 InFlag = Chain.getValue(1);
4395 Count = Op.getOperand(3);
4396 MVT::ValueType CVT = Count.getValueType();
4397 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4398 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4399 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4401 InFlag = Chain.getValue(1);
4402 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4404 Ops.push_back(Chain);
4405 Ops.push_back(DAG.getValueType(MVT::i8));
4406 Ops.push_back(InFlag);
4407 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4408 } else if (BytesLeft) {
4409 // Issue stores for the last 1 - 7 bytes.
4411 unsigned Val = ValC->getValue() & 255;
4412 unsigned Offset = I->getValue() - BytesLeft;
4413 SDOperand DstAddr = Op.getOperand(1);
4414 MVT::ValueType AddrVT = DstAddr.getValueType();
4415 if (BytesLeft >= 4) {
4416 Val = (Val << 8) | Val;
4417 Val = (Val << 16) | Val;
4418 Value = DAG.getConstant(Val, MVT::i32);
4419 Chain = DAG.getStore(Chain, Value,
4420 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4421 DAG.getConstant(Offset, AddrVT)),
4426 if (BytesLeft >= 2) {
4427 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4428 Chain = DAG.getStore(Chain, Value,
4429 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4430 DAG.getConstant(Offset, AddrVT)),
4435 if (BytesLeft == 1) {
4436 Value = DAG.getConstant(Val, MVT::i8);
4437 Chain = DAG.getStore(Chain, Value,
4438 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4439 DAG.getConstant(Offset, AddrVT)),
4447 SDOperand X86TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
4448 SDOperand ChainOp = Op.getOperand(0);
4449 SDOperand DestOp = Op.getOperand(1);
4450 SDOperand SourceOp = Op.getOperand(2);
4451 SDOperand CountOp = Op.getOperand(3);
4452 SDOperand AlignOp = Op.getOperand(4);
4453 unsigned Align = (unsigned)cast<ConstantSDNode>(AlignOp)->getValue();
4454 if (Align == 0) Align = 1;
4456 // The libc version is likely to be faster for the following cases. It can
4457 // use the address value and run time information about the CPU.
4458 // With glibc 2.6.1 on a core 2, coping an array of 100M longs was 30% faster
4460 // If not DWORD aligned, call memcpy.
4461 if ((Align & 3) != 0)
4462 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
4464 // If size is unknown, call memcpy.
4465 ConstantSDNode *I = dyn_cast<ConstantSDNode>(CountOp);
4467 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
4469 // If size is more than the threshold, call memcpy.
4470 unsigned Size = I->getValue();
4471 if (Size > Subtarget->getMinRepStrSizeThreshold())
4472 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
4474 return LowerMEMCPYInline(ChainOp, DestOp, SourceOp, Size, Align, DAG);
4477 SDOperand X86TargetLowering::LowerMEMCPYCall(SDOperand Chain,
4481 SelectionDAG &DAG) {
4482 MVT::ValueType IntPtr = getPointerTy();
4483 TargetLowering::ArgListTy Args;
4484 TargetLowering::ArgListEntry Entry;
4485 Entry.Ty = getTargetData()->getIntPtrType();
4486 Entry.Node = Dest; Args.push_back(Entry);
4487 Entry.Node = Source; Args.push_back(Entry);
4488 Entry.Node = Count; Args.push_back(Entry);
4489 std::pair<SDOperand,SDOperand> CallResult =
4490 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4491 DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
4492 return CallResult.second;
4495 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4500 SelectionDAG &DAG) {
4502 unsigned BytesLeft = 0;
4503 switch (Align & 3) {
4504 case 2: // WORD aligned
4507 case 0: // DWORD aligned
4509 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4512 default: // Byte aligned
4517 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4518 SDOperand Count = DAG.getConstant(Size / UBytes, getPointerTy());
4519 BytesLeft = Size % UBytes;
4521 SDOperand InFlag(0, 0);
4522 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4524 InFlag = Chain.getValue(1);
4525 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4527 InFlag = Chain.getValue(1);
4528 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4530 InFlag = Chain.getValue(1);
4532 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4533 SmallVector<SDOperand, 8> Ops;
4534 Ops.push_back(Chain);
4535 Ops.push_back(DAG.getValueType(AVT));
4536 Ops.push_back(InFlag);
4537 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4540 // Issue loads and stores for the last 1 - 7 bytes.
4541 unsigned Offset = Size - BytesLeft;
4542 SDOperand DstAddr = Dest;
4543 MVT::ValueType DstVT = DstAddr.getValueType();
4544 SDOperand SrcAddr = Source;
4545 MVT::ValueType SrcVT = SrcAddr.getValueType();
4547 if (BytesLeft >= 4) {
4548 Value = DAG.getLoad(MVT::i32, Chain,
4549 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4550 DAG.getConstant(Offset, SrcVT)),
4552 Chain = Value.getValue(1);
4553 Chain = DAG.getStore(Chain, Value,
4554 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4555 DAG.getConstant(Offset, DstVT)),
4560 if (BytesLeft >= 2) {
4561 Value = DAG.getLoad(MVT::i16, Chain,
4562 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4563 DAG.getConstant(Offset, SrcVT)),
4565 Chain = Value.getValue(1);
4566 Chain = DAG.getStore(Chain, Value,
4567 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4568 DAG.getConstant(Offset, DstVT)),
4574 if (BytesLeft == 1) {
4575 Value = DAG.getLoad(MVT::i8, Chain,
4576 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4577 DAG.getConstant(Offset, SrcVT)),
4579 Chain = Value.getValue(1);
4580 Chain = DAG.getStore(Chain, Value,
4581 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4582 DAG.getConstant(Offset, DstVT)),
4591 X86TargetLowering::LowerREADCYCLCECOUNTER(SDOperand Op, SelectionDAG &DAG) {
4592 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4593 SDOperand TheOp = Op.getOperand(0);
4594 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheOp, 1);
4595 if (Subtarget->is64Bit()) {
4597 DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4598 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::RDX,
4599 MVT::i64, Copy1.getValue(2));
4600 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, Copy2,
4601 DAG.getConstant(32, MVT::i8));
4603 DAG.getNode(ISD::OR, MVT::i64, Copy1, Tmp), Copy2.getValue(1)
4606 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4607 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2);
4610 SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4611 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::EDX,
4612 MVT::i32, Copy1.getValue(2));
4613 SDOperand Ops[] = { Copy1, Copy2, Copy2.getValue(1) };
4614 Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
4615 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 3);
4618 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4619 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
4621 if (!Subtarget->is64Bit()) {
4622 // vastart just stores the address of the VarArgsFrameIndex slot into the
4623 // memory location argument.
4624 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4625 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
4630 // gp_offset (0 - 6 * 8)
4631 // fp_offset (48 - 48 + 8 * 16)
4632 // overflow_arg_area (point to parameters coming in memory).
4634 SmallVector<SDOperand, 8> MemOps;
4635 SDOperand FIN = Op.getOperand(1);
4637 SDOperand Store = DAG.getStore(Op.getOperand(0),
4638 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4639 FIN, SV->getValue(), SV->getOffset());
4640 MemOps.push_back(Store);
4643 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4644 DAG.getConstant(4, getPointerTy()));
4645 Store = DAG.getStore(Op.getOperand(0),
4646 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4647 FIN, SV->getValue(), SV->getOffset());
4648 MemOps.push_back(Store);
4650 // Store ptr to overflow_arg_area
4651 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4652 DAG.getConstant(4, getPointerTy()));
4653 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4654 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
4656 MemOps.push_back(Store);
4658 // Store ptr to reg_save_area.
4659 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4660 DAG.getConstant(8, getPointerTy()));
4661 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4662 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
4664 MemOps.push_back(Store);
4665 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4668 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4669 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4670 SDOperand Chain = Op.getOperand(0);
4671 SDOperand DstPtr = Op.getOperand(1);
4672 SDOperand SrcPtr = Op.getOperand(2);
4673 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
4674 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
4676 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
4677 SrcSV->getValue(), SrcSV->getOffset());
4678 Chain = SrcPtr.getValue(1);
4679 for (unsigned i = 0; i < 3; ++i) {
4680 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
4681 SrcSV->getValue(), SrcSV->getOffset());
4682 Chain = Val.getValue(1);
4683 Chain = DAG.getStore(Chain, Val, DstPtr,
4684 DstSV->getValue(), DstSV->getOffset());
4687 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
4688 DAG.getConstant(8, getPointerTy()));
4689 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
4690 DAG.getConstant(8, getPointerTy()));
4696 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4697 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4699 default: return SDOperand(); // Don't custom lower most intrinsics.
4700 // Comparison intrinsics.
4701 case Intrinsic::x86_sse_comieq_ss:
4702 case Intrinsic::x86_sse_comilt_ss:
4703 case Intrinsic::x86_sse_comile_ss:
4704 case Intrinsic::x86_sse_comigt_ss:
4705 case Intrinsic::x86_sse_comige_ss:
4706 case Intrinsic::x86_sse_comineq_ss:
4707 case Intrinsic::x86_sse_ucomieq_ss:
4708 case Intrinsic::x86_sse_ucomilt_ss:
4709 case Intrinsic::x86_sse_ucomile_ss:
4710 case Intrinsic::x86_sse_ucomigt_ss:
4711 case Intrinsic::x86_sse_ucomige_ss:
4712 case Intrinsic::x86_sse_ucomineq_ss:
4713 case Intrinsic::x86_sse2_comieq_sd:
4714 case Intrinsic::x86_sse2_comilt_sd:
4715 case Intrinsic::x86_sse2_comile_sd:
4716 case Intrinsic::x86_sse2_comigt_sd:
4717 case Intrinsic::x86_sse2_comige_sd:
4718 case Intrinsic::x86_sse2_comineq_sd:
4719 case Intrinsic::x86_sse2_ucomieq_sd:
4720 case Intrinsic::x86_sse2_ucomilt_sd:
4721 case Intrinsic::x86_sse2_ucomile_sd:
4722 case Intrinsic::x86_sse2_ucomigt_sd:
4723 case Intrinsic::x86_sse2_ucomige_sd:
4724 case Intrinsic::x86_sse2_ucomineq_sd: {
4726 ISD::CondCode CC = ISD::SETCC_INVALID;
4729 case Intrinsic::x86_sse_comieq_ss:
4730 case Intrinsic::x86_sse2_comieq_sd:
4734 case Intrinsic::x86_sse_comilt_ss:
4735 case Intrinsic::x86_sse2_comilt_sd:
4739 case Intrinsic::x86_sse_comile_ss:
4740 case Intrinsic::x86_sse2_comile_sd:
4744 case Intrinsic::x86_sse_comigt_ss:
4745 case Intrinsic::x86_sse2_comigt_sd:
4749 case Intrinsic::x86_sse_comige_ss:
4750 case Intrinsic::x86_sse2_comige_sd:
4754 case Intrinsic::x86_sse_comineq_ss:
4755 case Intrinsic::x86_sse2_comineq_sd:
4759 case Intrinsic::x86_sse_ucomieq_ss:
4760 case Intrinsic::x86_sse2_ucomieq_sd:
4761 Opc = X86ISD::UCOMI;
4764 case Intrinsic::x86_sse_ucomilt_ss:
4765 case Intrinsic::x86_sse2_ucomilt_sd:
4766 Opc = X86ISD::UCOMI;
4769 case Intrinsic::x86_sse_ucomile_ss:
4770 case Intrinsic::x86_sse2_ucomile_sd:
4771 Opc = X86ISD::UCOMI;
4774 case Intrinsic::x86_sse_ucomigt_ss:
4775 case Intrinsic::x86_sse2_ucomigt_sd:
4776 Opc = X86ISD::UCOMI;
4779 case Intrinsic::x86_sse_ucomige_ss:
4780 case Intrinsic::x86_sse2_ucomige_sd:
4781 Opc = X86ISD::UCOMI;
4784 case Intrinsic::x86_sse_ucomineq_ss:
4785 case Intrinsic::x86_sse2_ucomineq_sd:
4786 Opc = X86ISD::UCOMI;
4792 SDOperand LHS = Op.getOperand(1);
4793 SDOperand RHS = Op.getOperand(2);
4794 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4796 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
4797 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
4798 DAG.getConstant(X86CC, MVT::i8), Cond);
4799 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
4804 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4805 // Depths > 0 not supported yet!
4806 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4809 // Just load the return address
4810 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4811 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4814 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4815 // Depths > 0 not supported yet!
4816 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4819 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4820 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
4821 DAG.getConstant(4, getPointerTy()));
4824 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
4825 SelectionDAG &DAG) {
4826 // Is not yet supported on x86-64
4827 if (Subtarget->is64Bit())
4830 return DAG.getConstant(8, getPointerTy());
4833 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
4835 assert(!Subtarget->is64Bit() &&
4836 "Lowering of eh_return builtin is not supported yet on x86-64");
4838 MachineFunction &MF = DAG.getMachineFunction();
4839 SDOperand Chain = Op.getOperand(0);
4840 SDOperand Offset = Op.getOperand(1);
4841 SDOperand Handler = Op.getOperand(2);
4843 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
4846 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
4847 DAG.getConstant(-4UL, getPointerTy()));
4848 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
4849 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
4850 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
4851 MF.addLiveOut(X86::ECX);
4853 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
4854 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
4857 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
4858 SelectionDAG &DAG) {
4859 SDOperand Root = Op.getOperand(0);
4860 SDOperand Trmp = Op.getOperand(1); // trampoline
4861 SDOperand FPtr = Op.getOperand(2); // nested function
4862 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
4864 SrcValueSDNode *TrmpSV = cast<SrcValueSDNode>(Op.getOperand(4));
4866 if (Subtarget->is64Bit()) {
4867 return SDOperand(); // not yet supported
4869 Function *Func = (Function *)
4870 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
4871 unsigned CC = Func->getCallingConv();
4876 assert(0 && "Unsupported calling convention");
4877 case CallingConv::C:
4878 case CallingConv::Fast:
4879 case CallingConv::X86_StdCall: {
4880 // Pass 'nest' parameter in ECX.
4881 // Must be kept in sync with X86CallingConv.td
4884 // Check that ECX wasn't needed by an 'inreg' parameter.
4885 const FunctionType *FTy = Func->getFunctionType();
4886 const ParamAttrsList *Attrs = FTy->getParamAttrs();
4888 if (Attrs && !Func->isVarArg()) {
4889 unsigned InRegCount = 0;
4892 for (FunctionType::param_iterator I = FTy->param_begin(),
4893 E = FTy->param_end(); I != E; ++I, ++Idx)
4894 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
4895 // FIXME: should only count parameters that are lowered to integers.
4896 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
4898 if (InRegCount > 2) {
4899 cerr << "Nest register in use - reduce number of inreg parameters!\n";
4905 case CallingConv::X86_FastCall:
4906 // Pass 'nest' parameter in EAX.
4907 // Must be kept in sync with X86CallingConv.td
4912 const X86InstrInfo *TII =
4913 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
4915 SDOperand OutChains[4];
4916 SDOperand Addr, Disp;
4918 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
4919 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
4921 unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
4922 unsigned char N86Reg = ((X86RegisterInfo&)RegInfo).getX86RegNum(NestReg);
4923 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
4924 Trmp, TrmpSV->getValue(), TrmpSV->getOffset());
4926 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
4927 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpSV->getValue(),
4928 TrmpSV->getOffset() + 1, false, 1);
4930 unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
4931 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
4932 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
4933 TrmpSV->getValue() + 5, TrmpSV->getOffset());
4935 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
4936 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpSV->getValue(),
4937 TrmpSV->getOffset() + 6, false, 1);
4940 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
4941 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
4945 /// LowerOperation - Provide custom lowering hooks for some operations.
4947 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4948 switch (Op.getOpcode()) {
4949 default: assert(0 && "Should not custom lower this!");
4950 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
4951 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
4952 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4953 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
4954 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
4955 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
4956 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
4957 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
4958 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
4959 case ISD::SHL_PARTS:
4960 case ISD::SRA_PARTS:
4961 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
4962 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
4963 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
4964 case ISD::FABS: return LowerFABS(Op, DAG);
4965 case ISD::FNEG: return LowerFNEG(Op, DAG);
4966 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
4967 case ISD::SETCC: return LowerSETCC(Op, DAG);
4968 case ISD::SELECT: return LowerSELECT(Op, DAG);
4969 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4970 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
4971 case ISD::CALL: return LowerCALL(Op, DAG);
4972 case ISD::RET: return LowerRET(Op, DAG);
4973 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
4974 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
4975 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
4976 case ISD::READCYCLECOUNTER: return LowerREADCYCLCECOUNTER(Op, DAG);
4977 case ISD::VASTART: return LowerVASTART(Op, DAG);
4978 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
4979 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4980 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4981 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
4982 case ISD::FRAME_TO_ARGS_OFFSET:
4983 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
4984 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
4985 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
4986 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
4991 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
4993 default: return NULL;
4994 case X86ISD::SHLD: return "X86ISD::SHLD";
4995 case X86ISD::SHRD: return "X86ISD::SHRD";
4996 case X86ISD::FAND: return "X86ISD::FAND";
4997 case X86ISD::FOR: return "X86ISD::FOR";
4998 case X86ISD::FXOR: return "X86ISD::FXOR";
4999 case X86ISD::FSRL: return "X86ISD::FSRL";
5000 case X86ISD::FILD: return "X86ISD::FILD";
5001 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5002 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5003 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5004 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5005 case X86ISD::FLD: return "X86ISD::FLD";
5006 case X86ISD::FST: return "X86ISD::FST";
5007 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5008 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5009 case X86ISD::CALL: return "X86ISD::CALL";
5010 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5011 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5012 case X86ISD::CMP: return "X86ISD::CMP";
5013 case X86ISD::COMI: return "X86ISD::COMI";
5014 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5015 case X86ISD::SETCC: return "X86ISD::SETCC";
5016 case X86ISD::CMOV: return "X86ISD::CMOV";
5017 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5018 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5019 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5020 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5021 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5022 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5023 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5024 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5025 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5026 case X86ISD::FMAX: return "X86ISD::FMAX";
5027 case X86ISD::FMIN: return "X86ISD::FMIN";
5028 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5029 case X86ISD::FRCP: return "X86ISD::FRCP";
5030 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5031 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5032 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5033 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5037 // isLegalAddressingMode - Return true if the addressing mode represented
5038 // by AM is legal for this target, for a load/store of the specified type.
5039 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5040 const Type *Ty) const {
5041 // X86 supports extremely general addressing modes.
5043 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5044 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5048 // We can only fold this if we don't need an extra load.
5049 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5052 // X86-64 only supports addr of globals in small code model.
5053 if (Subtarget->is64Bit()) {
5054 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5056 // If lower 4G is not available, then we must use rip-relative addressing.
5057 if (AM.BaseOffs || AM.Scale > 1)
5068 // These scales always work.
5073 // These scales are formed with basereg+scalereg. Only accept if there is
5078 default: // Other stuff never works.
5086 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5087 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5088 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5089 /// are assumed to be legal.
5091 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5092 // Only do shuffles on 128-bit vector types for now.
5093 if (MVT::getSizeInBits(VT) == 64) return false;
5094 return (Mask.Val->getNumOperands() <= 4 ||
5095 isIdentityMask(Mask.Val) ||
5096 isIdentityMask(Mask.Val, true) ||
5097 isSplatMask(Mask.Val) ||
5098 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5099 X86::isUNPCKLMask(Mask.Val) ||
5100 X86::isUNPCKHMask(Mask.Val) ||
5101 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5102 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5105 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5107 SelectionDAG &DAG) const {
5108 unsigned NumElts = BVOps.size();
5109 // Only do shuffles on 128-bit vector types for now.
5110 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5111 if (NumElts == 2) return true;
5113 return (isMOVLMask(&BVOps[0], 4) ||
5114 isCommutedMOVL(&BVOps[0], 4, true) ||
5115 isSHUFPMask(&BVOps[0], 4) ||
5116 isCommutedSHUFP(&BVOps[0], 4));
5121 //===----------------------------------------------------------------------===//
5122 // X86 Scheduler Hooks
5123 //===----------------------------------------------------------------------===//
5126 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
5127 MachineBasicBlock *BB) {
5128 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5129 switch (MI->getOpcode()) {
5130 default: assert(false && "Unexpected instr type to insert");
5131 case X86::CMOV_FR32:
5132 case X86::CMOV_FR64:
5133 case X86::CMOV_V4F32:
5134 case X86::CMOV_V2F64:
5135 case X86::CMOV_V2I64: {
5136 // To "insert" a SELECT_CC instruction, we actually have to insert the
5137 // diamond control-flow pattern. The incoming instruction knows the
5138 // destination vreg to set, the condition code register to branch on, the
5139 // true/false values to select between, and a branch opcode to use.
5140 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5141 ilist<MachineBasicBlock>::iterator It = BB;
5147 // cmpTY ccX, r1, r2
5149 // fallthrough --> copy0MBB
5150 MachineBasicBlock *thisMBB = BB;
5151 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5152 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5154 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5155 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5156 MachineFunction *F = BB->getParent();
5157 F->getBasicBlockList().insert(It, copy0MBB);
5158 F->getBasicBlockList().insert(It, sinkMBB);
5159 // Update machine-CFG edges by first adding all successors of the current
5160 // block to the new block which will contain the Phi node for the select.
5161 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5162 e = BB->succ_end(); i != e; ++i)
5163 sinkMBB->addSuccessor(*i);
5164 // Next, remove all successors of the current block, and add the true
5165 // and fallthrough blocks as its successors.
5166 while(!BB->succ_empty())
5167 BB->removeSuccessor(BB->succ_begin());
5168 BB->addSuccessor(copy0MBB);
5169 BB->addSuccessor(sinkMBB);
5172 // %FalseValue = ...
5173 // # fallthrough to sinkMBB
5176 // Update machine-CFG edges
5177 BB->addSuccessor(sinkMBB);
5180 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5183 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5184 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5185 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5187 delete MI; // The pseudo instruction is gone now.
5191 case X86::FP32_TO_INT16_IN_MEM:
5192 case X86::FP32_TO_INT32_IN_MEM:
5193 case X86::FP32_TO_INT64_IN_MEM:
5194 case X86::FP64_TO_INT16_IN_MEM:
5195 case X86::FP64_TO_INT32_IN_MEM:
5196 case X86::FP64_TO_INT64_IN_MEM:
5197 case X86::FP80_TO_INT16_IN_MEM:
5198 case X86::FP80_TO_INT32_IN_MEM:
5199 case X86::FP80_TO_INT64_IN_MEM: {
5200 // Change the floating point control register to use "round towards zero"
5201 // mode when truncating to an integer value.
5202 MachineFunction *F = BB->getParent();
5203 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5204 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5206 // Load the old value of the high byte of the control word...
5208 F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
5209 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5211 // Set the high part to be round to zero...
5212 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5215 // Reload the modified control word now...
5216 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5218 // Restore the memory image of control word to original value
5219 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5222 // Get the X86 opcode to use.
5224 switch (MI->getOpcode()) {
5225 default: assert(0 && "illegal opcode!");
5226 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5227 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5228 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5229 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5230 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5231 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5232 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5233 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5234 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5238 MachineOperand &Op = MI->getOperand(0);
5239 if (Op.isRegister()) {
5240 AM.BaseType = X86AddressMode::RegBase;
5241 AM.Base.Reg = Op.getReg();
5243 AM.BaseType = X86AddressMode::FrameIndexBase;
5244 AM.Base.FrameIndex = Op.getFrameIndex();
5246 Op = MI->getOperand(1);
5247 if (Op.isImmediate())
5248 AM.Scale = Op.getImm();
5249 Op = MI->getOperand(2);
5250 if (Op.isImmediate())
5251 AM.IndexReg = Op.getImm();
5252 Op = MI->getOperand(3);
5253 if (Op.isGlobalAddress()) {
5254 AM.GV = Op.getGlobal();
5256 AM.Disp = Op.getImm();
5258 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5259 .addReg(MI->getOperand(4).getReg());
5261 // Reload the original control word now.
5262 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5264 delete MI; // The pseudo instruction is gone now.
5270 //===----------------------------------------------------------------------===//
5271 // X86 Optimization Hooks
5272 //===----------------------------------------------------------------------===//
5274 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5276 uint64_t &KnownZero,
5278 const SelectionDAG &DAG,
5279 unsigned Depth) const {
5280 unsigned Opc = Op.getOpcode();
5281 assert((Opc >= ISD::BUILTIN_OP_END ||
5282 Opc == ISD::INTRINSIC_WO_CHAIN ||
5283 Opc == ISD::INTRINSIC_W_CHAIN ||
5284 Opc == ISD::INTRINSIC_VOID) &&
5285 "Should use MaskedValueIsZero if you don't know whether Op"
5286 " is a target node!");
5288 KnownZero = KnownOne = 0; // Don't know anything.
5292 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5297 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5298 /// element of the result of the vector shuffle.
5299 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5300 MVT::ValueType VT = N->getValueType(0);
5301 SDOperand PermMask = N->getOperand(2);
5302 unsigned NumElems = PermMask.getNumOperands();
5303 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5305 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5307 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5308 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5309 SDOperand Idx = PermMask.getOperand(i);
5310 if (Idx.getOpcode() == ISD::UNDEF)
5311 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5312 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5317 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5318 /// node is a GlobalAddress + an offset.
5319 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5320 unsigned Opc = N->getOpcode();
5321 if (Opc == X86ISD::Wrapper) {
5322 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5323 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5326 } else if (Opc == ISD::ADD) {
5327 SDOperand N1 = N->getOperand(0);
5328 SDOperand N2 = N->getOperand(1);
5329 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5330 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5332 Offset += V->getSignExtended();
5335 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5336 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5338 Offset += V->getSignExtended();
5346 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5348 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5349 MachineFrameInfo *MFI) {
5350 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5353 SDOperand Loc = N->getOperand(1);
5354 SDOperand BaseLoc = Base->getOperand(1);
5355 if (Loc.getOpcode() == ISD::FrameIndex) {
5356 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5358 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5359 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5360 int FS = MFI->getObjectSize(FI);
5361 int BFS = MFI->getObjectSize(BFI);
5362 if (FS != BFS || FS != Size) return false;
5363 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5365 GlobalValue *GV1 = NULL;
5366 GlobalValue *GV2 = NULL;
5367 int64_t Offset1 = 0;
5368 int64_t Offset2 = 0;
5369 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5370 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5371 if (isGA1 && isGA2 && GV1 == GV2)
5372 return Offset1 == (Offset2 + Dist*Size);
5378 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5379 const X86Subtarget *Subtarget) {
5382 if (isGAPlusOffset(Base, GV, Offset))
5383 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5385 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
5386 int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
5388 // Fixed objects do not specify alignment, however the offsets are known.
5389 return ((Subtarget->getStackAlignment() % 16) == 0 &&
5390 (MFI->getObjectOffset(BFI) % 16) == 0);
5392 return MFI->getObjectAlignment(BFI) >= 16;
5398 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5399 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5400 /// if the load addresses are consecutive, non-overlapping, and in the right
5402 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5403 const X86Subtarget *Subtarget) {
5404 MachineFunction &MF = DAG.getMachineFunction();
5405 MachineFrameInfo *MFI = MF.getFrameInfo();
5406 MVT::ValueType VT = N->getValueType(0);
5407 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5408 SDOperand PermMask = N->getOperand(2);
5409 int NumElems = (int)PermMask.getNumOperands();
5410 SDNode *Base = NULL;
5411 for (int i = 0; i < NumElems; ++i) {
5412 SDOperand Idx = PermMask.getOperand(i);
5413 if (Idx.getOpcode() == ISD::UNDEF) {
5414 if (!Base) return SDOperand();
5417 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5418 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5422 else if (!isConsecutiveLoad(Arg.Val, Base,
5423 i, MVT::getSizeInBits(EVT)/8,MFI))
5428 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5429 LoadSDNode *LD = cast<LoadSDNode>(Base);
5431 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5432 LD->getSrcValueOffset(), LD->isVolatile());
5434 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5435 LD->getSrcValueOffset(), LD->isVolatile(),
5436 LD->getAlignment());
5440 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5441 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5442 const X86Subtarget *Subtarget) {
5443 SDOperand Cond = N->getOperand(0);
5445 // If we have SSE[12] support, try to form min/max nodes.
5446 if (Subtarget->hasSSE2() &&
5447 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5448 if (Cond.getOpcode() == ISD::SETCC) {
5449 // Get the LHS/RHS of the select.
5450 SDOperand LHS = N->getOperand(1);
5451 SDOperand RHS = N->getOperand(2);
5452 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5454 unsigned Opcode = 0;
5455 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5458 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5461 if (!UnsafeFPMath) break;
5463 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
5465 Opcode = X86ISD::FMIN;
5468 case ISD::SETOGT: // (X > Y) ? X : Y -> max
5471 if (!UnsafeFPMath) break;
5473 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
5475 Opcode = X86ISD::FMAX;
5478 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5481 case ISD::SETOGT: // (X > Y) ? Y : X -> min
5484 if (!UnsafeFPMath) break;
5486 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
5488 Opcode = X86ISD::FMIN;
5491 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
5494 if (!UnsafeFPMath) break;
5496 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
5498 Opcode = X86ISD::FMAX;
5504 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5513 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5514 DAGCombinerInfo &DCI) const {
5515 SelectionDAG &DAG = DCI.DAG;
5516 switch (N->getOpcode()) {
5518 case ISD::VECTOR_SHUFFLE:
5519 return PerformShuffleCombine(N, DAG, Subtarget);
5521 return PerformSELECTCombine(N, DAG, Subtarget);
5527 //===----------------------------------------------------------------------===//
5528 // X86 Inline Assembly Support
5529 //===----------------------------------------------------------------------===//
5531 /// getConstraintType - Given a constraint letter, return the type of
5532 /// constraint it is for this target.
5533 X86TargetLowering::ConstraintType
5534 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
5535 if (Constraint.size() == 1) {
5536 switch (Constraint[0]) {
5545 return C_RegisterClass;
5550 return TargetLowering::getConstraintType(Constraint);
5553 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5554 /// vector. If it is invalid, don't add anything to Ops.
5555 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
5557 std::vector<SDOperand>&Ops,
5558 SelectionDAG &DAG) {
5559 SDOperand Result(0, 0);
5561 switch (Constraint) {
5564 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5565 if (C->getValue() <= 31) {
5566 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5572 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5573 if (C->getValue() <= 255) {
5574 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5580 // Literal immediates are always ok.
5581 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
5582 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
5586 // If we are in non-pic codegen mode, we allow the address of a global (with
5587 // an optional displacement) to be used with 'i'.
5588 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
5591 // Match either (GA) or (GA+C)
5593 Offset = GA->getOffset();
5594 } else if (Op.getOpcode() == ISD::ADD) {
5595 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5596 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5598 Offset = GA->getOffset()+C->getValue();
5600 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5601 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5603 Offset = GA->getOffset()+C->getValue();
5610 // If addressing this global requires a load (e.g. in PIC mode), we can't
5612 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
5616 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5622 // Otherwise, not valid for this mode.
5628 Ops.push_back(Result);
5631 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5634 std::vector<unsigned> X86TargetLowering::
5635 getRegClassForInlineAsmConstraint(const std::string &Constraint,
5636 MVT::ValueType VT) const {
5637 if (Constraint.size() == 1) {
5638 // FIXME: not handling fp-stack yet!
5639 switch (Constraint[0]) { // GCC X86 Constraint Letters
5640 default: break; // Unknown constraint letter
5641 case 'A': // EAX/EDX
5642 if (VT == MVT::i32 || VT == MVT::i64)
5643 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
5645 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
5648 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
5649 else if (VT == MVT::i16)
5650 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
5651 else if (VT == MVT::i8)
5652 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
5657 return std::vector<unsigned>();
5660 std::pair<unsigned, const TargetRegisterClass*>
5661 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
5662 MVT::ValueType VT) const {
5663 // First, see if this is a constraint that directly corresponds to an LLVM
5665 if (Constraint.size() == 1) {
5666 // GCC Constraint Letters
5667 switch (Constraint[0]) {
5669 case 'r': // GENERAL_REGS
5670 case 'R': // LEGACY_REGS
5671 case 'l': // INDEX_REGS
5672 if (VT == MVT::i64 && Subtarget->is64Bit())
5673 return std::make_pair(0U, X86::GR64RegisterClass);
5675 return std::make_pair(0U, X86::GR32RegisterClass);
5676 else if (VT == MVT::i16)
5677 return std::make_pair(0U, X86::GR16RegisterClass);
5678 else if (VT == MVT::i8)
5679 return std::make_pair(0U, X86::GR8RegisterClass);
5681 case 'y': // MMX_REGS if MMX allowed.
5682 if (!Subtarget->hasMMX()) break;
5683 return std::make_pair(0U, X86::VR64RegisterClass);
5685 case 'Y': // SSE_REGS if SSE2 allowed
5686 if (!Subtarget->hasSSE2()) break;
5688 case 'x': // SSE_REGS if SSE1 allowed
5689 if (!Subtarget->hasSSE1()) break;
5693 // Scalar SSE types.
5696 return std::make_pair(0U, X86::FR32RegisterClass);
5699 return std::make_pair(0U, X86::FR64RegisterClass);
5707 return std::make_pair(0U, X86::VR128RegisterClass);
5713 // Use the default implementation in TargetLowering to convert the register
5714 // constraint into a member of a register class.
5715 std::pair<unsigned, const TargetRegisterClass*> Res;
5716 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
5718 // Not found as a standard register?
5719 if (Res.second == 0) {
5720 // GCC calls "st(0)" just plain "st".
5721 if (StringsEqualNoCase("{st}", Constraint)) {
5722 Res.first = X86::ST0;
5723 Res.second = X86::RFP80RegisterClass;
5729 // Otherwise, check to see if this is a register class of the wrong value
5730 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
5731 // turn into {ax},{dx}.
5732 if (Res.second->hasType(VT))
5733 return Res; // Correct type already, nothing to do.
5735 // All of the single-register GCC register classes map their values onto
5736 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
5737 // really want an 8-bit or 32-bit register, map to the appropriate register
5738 // class and return the appropriate register.
5739 if (Res.second != X86::GR16RegisterClass)
5742 if (VT == MVT::i8) {
5743 unsigned DestReg = 0;
5744 switch (Res.first) {
5746 case X86::AX: DestReg = X86::AL; break;
5747 case X86::DX: DestReg = X86::DL; break;
5748 case X86::CX: DestReg = X86::CL; break;
5749 case X86::BX: DestReg = X86::BL; break;
5752 Res.first = DestReg;
5753 Res.second = Res.second = X86::GR8RegisterClass;
5755 } else if (VT == MVT::i32) {
5756 unsigned DestReg = 0;
5757 switch (Res.first) {
5759 case X86::AX: DestReg = X86::EAX; break;
5760 case X86::DX: DestReg = X86::EDX; break;
5761 case X86::CX: DestReg = X86::ECX; break;
5762 case X86::BX: DestReg = X86::EBX; break;
5763 case X86::SI: DestReg = X86::ESI; break;
5764 case X86::DI: DestReg = X86::EDI; break;
5765 case X86::BP: DestReg = X86::EBP; break;
5766 case X86::SP: DestReg = X86::ESP; break;
5769 Res.first = DestReg;
5770 Res.second = Res.second = X86::GR32RegisterClass;
5772 } else if (VT == MVT::i64) {
5773 unsigned DestReg = 0;
5774 switch (Res.first) {
5776 case X86::AX: DestReg = X86::RAX; break;
5777 case X86::DX: DestReg = X86::RDX; break;
5778 case X86::CX: DestReg = X86::RCX; break;
5779 case X86::BX: DestReg = X86::RBX; break;
5780 case X86::SI: DestReg = X86::RSI; break;
5781 case X86::DI: DestReg = X86::RDI; break;
5782 case X86::BP: DestReg = X86::RBP; break;
5783 case X86::SP: DestReg = X86::RSP; break;
5786 Res.first = DestReg;
5787 Res.second = Res.second = X86::GR64RegisterClass;