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/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/CodeGen/SSARegMap.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/ParameterAttributes.h"
44 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
45 : TargetLowering(TM) {
46 Subtarget = &TM.getSubtarget<X86Subtarget>();
47 X86ScalarSSEf64 = Subtarget->hasSSE2();
48 X86ScalarSSEf32 = Subtarget->hasSSE1();
49 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
52 RegInfo = TM.getRegisterInfo();
54 // Set up the TargetLowering object.
56 // X86 is weird, it always uses i8 for shift amounts and setcc results.
57 setShiftAmountType(MVT::i8);
58 setSetCCResultType(MVT::i8);
59 setSetCCResultContents(ZeroOrOneSetCCResult);
60 setSchedulingPreference(SchedulingForRegPressure);
61 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
62 setStackPointerRegisterToSaveRestore(X86StackPtr);
64 if (Subtarget->isTargetDarwin()) {
65 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
66 setUseUnderscoreSetJmp(false);
67 setUseUnderscoreLongJmp(false);
68 } else if (Subtarget->isTargetMingw()) {
69 // MS runtime is weird: it exports _setjmp, but longjmp!
70 setUseUnderscoreSetJmp(true);
71 setUseUnderscoreLongJmp(false);
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(true);
77 // Set up the register classes.
78 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
79 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
80 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
81 if (Subtarget->is64Bit())
82 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
84 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
86 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
88 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
89 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
90 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
92 if (Subtarget->is64Bit()) {
93 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
94 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
97 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
98 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
100 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
103 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
105 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
106 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
107 // SSE has no i16 to fp conversion, only i32
108 if (X86ScalarSSEf32) {
109 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
110 // f32 and f64 cases are Legal, f80 case is not
111 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
113 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
114 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
117 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
118 // are Legal, f80 is custom lowered.
119 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
120 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
122 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
124 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
125 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
127 if (X86ScalarSSEf32) {
128 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
129 // f32 and f64 cases are Legal, f80 case is not
130 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
132 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
133 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
136 // Handle FP_TO_UINT by promoting the destination to a larger signed
138 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
139 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
140 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
142 if (Subtarget->is64Bit()) {
143 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
144 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
146 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
147 // Expand FP_TO_UINT into a select.
148 // FIXME: We would like to use a Custom expander here eventually to do
149 // the optimal thing for SSE vs. the default expansion in the legalizer.
150 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
152 // With SSE3 we can use fisttpll to convert to a signed i64.
153 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
156 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
157 if (!X86ScalarSSEf64) {
158 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
159 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
162 // Scalar integer multiply, multiply-high, divide, and remainder are
163 // lowered to use operations that produce two results, to match the
164 // available instructions. This exposes the two-result form to trivial
165 // CSE, which is able to combine x/y and x%y into a single instruction,
166 // for example. The single-result multiply instructions are introduced
167 // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
169 setOperationAction(ISD::MUL , MVT::i8 , Expand);
170 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
171 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
172 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
173 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
174 setOperationAction(ISD::SREM , MVT::i8 , Expand);
175 setOperationAction(ISD::UREM , MVT::i8 , Expand);
176 setOperationAction(ISD::MUL , MVT::i16 , Expand);
177 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
178 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
179 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
180 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
181 setOperationAction(ISD::SREM , MVT::i16 , Expand);
182 setOperationAction(ISD::UREM , MVT::i16 , Expand);
183 setOperationAction(ISD::MUL , MVT::i32 , Expand);
184 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
185 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
186 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
187 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
188 setOperationAction(ISD::SREM , MVT::i32 , Expand);
189 setOperationAction(ISD::UREM , MVT::i32 , Expand);
190 setOperationAction(ISD::MUL , MVT::i64 , Expand);
191 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
192 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
193 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
194 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
195 setOperationAction(ISD::SREM , MVT::i64 , Expand);
196 setOperationAction(ISD::UREM , MVT::i64 , Expand);
198 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
199 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
200 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
201 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
202 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
203 if (Subtarget->is64Bit())
204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
206 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
207 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
208 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
209 setOperationAction(ISD::FREM , MVT::f64 , Expand);
210 setOperationAction(ISD::FLT_ROUNDS , MVT::i32 , Custom);
212 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
213 setOperationAction(ISD::CTTZ , MVT::i8 , Expand);
214 setOperationAction(ISD::CTLZ , MVT::i8 , Expand);
215 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
216 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
217 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
218 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
219 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
220 setOperationAction(ISD::CTLZ , MVT::i32 , Expand);
221 if (Subtarget->is64Bit()) {
222 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
223 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
224 setOperationAction(ISD::CTLZ , MVT::i64 , Expand);
227 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
228 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
230 // These should be promoted to a larger select which is supported.
231 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
232 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
233 // X86 wants to expand cmov itself.
234 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
235 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
236 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
237 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
238 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
239 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
240 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
241 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
242 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
243 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
244 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
245 if (Subtarget->is64Bit()) {
246 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
247 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
249 // X86 ret instruction may pop stack.
250 setOperationAction(ISD::RET , MVT::Other, Custom);
251 if (!Subtarget->is64Bit())
252 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
255 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
256 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
257 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
258 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
259 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
260 if (Subtarget->is64Bit()) {
261 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
262 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
263 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
264 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
266 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
267 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
268 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
269 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
270 // X86 wants to expand memset / memcpy itself.
271 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
272 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
274 // Use the default ISD::LOCATION expansion.
275 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
276 // FIXME - use subtarget debug flags
277 if (!Subtarget->isTargetDarwin() &&
278 !Subtarget->isTargetELF() &&
279 !Subtarget->isTargetCygMing())
280 setOperationAction(ISD::LABEL, MVT::Other, Expand);
282 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
283 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
284 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
285 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
286 if (Subtarget->is64Bit()) {
288 setExceptionPointerRegister(X86::RAX);
289 setExceptionSelectorRegister(X86::RDX);
291 setExceptionPointerRegister(X86::EAX);
292 setExceptionSelectorRegister(X86::EDX);
294 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
296 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
298 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
299 setOperationAction(ISD::VASTART , MVT::Other, Custom);
300 setOperationAction(ISD::VAARG , MVT::Other, Expand);
301 setOperationAction(ISD::VAEND , MVT::Other, Expand);
302 if (Subtarget->is64Bit())
303 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
305 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
307 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
308 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
309 if (Subtarget->is64Bit())
310 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
311 if (Subtarget->isTargetCygMing())
312 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
314 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
316 if (X86ScalarSSEf64) {
317 // f32 and f64 use SSE.
318 // Set up the FP register classes.
319 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
320 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
322 // Use ANDPD to simulate FABS.
323 setOperationAction(ISD::FABS , MVT::f64, Custom);
324 setOperationAction(ISD::FABS , MVT::f32, Custom);
326 // Use XORP to simulate FNEG.
327 setOperationAction(ISD::FNEG , MVT::f64, Custom);
328 setOperationAction(ISD::FNEG , MVT::f32, Custom);
330 // Use ANDPD and ORPD to simulate FCOPYSIGN.
331 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
332 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
334 // We don't support sin/cos/fmod
335 setOperationAction(ISD::FSIN , MVT::f64, Expand);
336 setOperationAction(ISD::FCOS , MVT::f64, Expand);
337 setOperationAction(ISD::FREM , MVT::f64, Expand);
338 setOperationAction(ISD::FSIN , MVT::f32, Expand);
339 setOperationAction(ISD::FCOS , MVT::f32, Expand);
340 setOperationAction(ISD::FREM , MVT::f32, Expand);
342 // Expand FP immediates into loads from the stack, except for the special
344 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
345 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
346 addLegalFPImmediate(APFloat(+0.0)); // xorpd
347 addLegalFPImmediate(APFloat(+0.0f)); // xorps
349 // Conversions to long double (in X87) go through memory.
350 setConvertAction(MVT::f32, MVT::f80, Expand);
351 setConvertAction(MVT::f64, MVT::f80, Expand);
353 // Conversions from long double (in X87) go through memory.
354 setConvertAction(MVT::f80, MVT::f32, Expand);
355 setConvertAction(MVT::f80, MVT::f64, Expand);
356 } else if (X86ScalarSSEf32) {
357 // Use SSE for f32, x87 for f64.
358 // Set up the FP register classes.
359 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
360 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
362 // Use ANDPS to simulate FABS.
363 setOperationAction(ISD::FABS , MVT::f32, Custom);
365 // Use XORP to simulate FNEG.
366 setOperationAction(ISD::FNEG , MVT::f32, Custom);
368 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
370 // Use ANDPS and ORPS to simulate FCOPYSIGN.
371 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
372 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
374 // We don't support sin/cos/fmod
375 setOperationAction(ISD::FSIN , MVT::f32, Expand);
376 setOperationAction(ISD::FCOS , MVT::f32, Expand);
377 setOperationAction(ISD::FREM , MVT::f32, Expand);
379 // Expand FP immediates into loads from the stack, except for the special
381 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
382 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
383 addLegalFPImmediate(APFloat(+0.0f)); // xorps
384 addLegalFPImmediate(APFloat(+0.0)); // FLD0
385 addLegalFPImmediate(APFloat(+1.0)); // FLD1
386 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
387 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
389 // SSE->x87 conversions go through memory.
390 setConvertAction(MVT::f32, MVT::f64, Expand);
391 setConvertAction(MVT::f32, MVT::f80, Expand);
393 // x87->SSE truncations need to go through memory.
394 setConvertAction(MVT::f80, MVT::f32, Expand);
395 setConvertAction(MVT::f64, MVT::f32, Expand);
396 // And x87->x87 truncations also.
397 setConvertAction(MVT::f80, MVT::f64, Expand);
400 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
401 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
404 // f32 and f64 in x87.
405 // Set up the FP register classes.
406 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
407 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
409 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
410 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
411 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
412 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
414 // Floating truncations need to go through memory.
415 setConvertAction(MVT::f80, MVT::f32, Expand);
416 setConvertAction(MVT::f64, MVT::f32, Expand);
417 setConvertAction(MVT::f80, MVT::f64, Expand);
420 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
421 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
424 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
425 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
426 addLegalFPImmediate(APFloat(+0.0)); // FLD0
427 addLegalFPImmediate(APFloat(+1.0)); // FLD1
428 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
429 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
430 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
431 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
432 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
433 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
436 // Long double always uses X87.
437 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
438 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
439 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
440 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
442 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
443 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
446 // Always use a library call for pow.
447 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
448 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
449 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
451 // First set operation action for all vector types to expand. Then we
452 // will selectively turn on ones that can be effectively codegen'd.
453 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
454 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
455 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
456 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
457 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
458 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
459 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
460 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
461 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
462 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
463 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
464 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
465 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
466 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
467 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
468 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
469 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
470 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
471 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
472 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
473 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
474 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
475 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
476 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
477 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
478 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
479 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
480 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
481 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
482 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
483 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
484 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
485 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
488 if (Subtarget->hasMMX()) {
489 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
490 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
491 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
492 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
494 // FIXME: add MMX packed arithmetics
496 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
497 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
498 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
499 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
501 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
502 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
503 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
504 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
506 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
507 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
509 setOperationAction(ISD::AND, MVT::v8i8, Promote);
510 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
511 setOperationAction(ISD::AND, MVT::v4i16, Promote);
512 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
513 setOperationAction(ISD::AND, MVT::v2i32, Promote);
514 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
515 setOperationAction(ISD::AND, MVT::v1i64, Legal);
517 setOperationAction(ISD::OR, MVT::v8i8, Promote);
518 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
519 setOperationAction(ISD::OR, MVT::v4i16, Promote);
520 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
521 setOperationAction(ISD::OR, MVT::v2i32, Promote);
522 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
523 setOperationAction(ISD::OR, MVT::v1i64, Legal);
525 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
526 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
527 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
528 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
529 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
530 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
531 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
533 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
534 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
535 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
536 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
537 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
538 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
539 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
541 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
542 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
543 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
544 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
546 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
547 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
548 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
549 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
551 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
552 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
553 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
554 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
557 if (Subtarget->hasSSE1()) {
558 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
560 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
561 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
562 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
563 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
564 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
565 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
566 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
567 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
568 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
569 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
570 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
573 if (Subtarget->hasSSE2()) {
574 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
575 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
576 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
577 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
578 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
580 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
581 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
582 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
583 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
584 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
585 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
586 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
587 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
588 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
589 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
590 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
591 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
592 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
593 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
594 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
596 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
597 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
598 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
599 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
600 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
601 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
603 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
604 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
605 // Do not attempt to custom lower non-power-of-2 vectors
606 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
608 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
609 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
610 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
612 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
613 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
614 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
615 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
616 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
617 if (Subtarget->is64Bit())
618 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
620 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
621 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
622 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
623 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
624 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
625 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
626 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
627 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
628 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
629 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
630 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
631 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
634 // Custom lower v2i64 and v2f64 selects.
635 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
636 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
637 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
638 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
641 // We want to custom lower some of our intrinsics.
642 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
644 // We have target-specific dag combine patterns for the following nodes:
645 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
646 setTargetDAGCombine(ISD::SELECT);
648 computeRegisterProperties();
650 // FIXME: These should be based on subtarget info. Plus, the values should
651 // be smaller when we are in optimizing for size mode.
652 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
653 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
654 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
655 allowUnalignedMemoryAccesses = true; // x86 supports it!
659 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
661 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
662 SelectionDAG &DAG) const {
663 if (usesGlobalOffsetTable())
664 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
665 if (!Subtarget->isPICStyleRIPRel())
666 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
670 //===----------------------------------------------------------------------===//
671 // Return Value Calling Convention Implementation
672 //===----------------------------------------------------------------------===//
674 #include "X86GenCallingConv.inc"
676 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
677 /// exists skip possible ISD:TokenFactor.
678 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
679 if (Chain.getOpcode()==X86ISD::TAILCALL) {
681 } else if (Chain.getOpcode()==ISD::TokenFactor) {
682 if (Chain.getNumOperands() &&
683 Chain.getOperand(0).getOpcode()==X86ISD::TAILCALL)
684 return Chain.getOperand(0);
689 /// LowerRET - Lower an ISD::RET node.
690 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
691 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
693 SmallVector<CCValAssign, 16> RVLocs;
694 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
695 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
696 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
697 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
699 // If this is the first return lowered for this function, add the regs to the
700 // liveout set for the function.
701 if (DAG.getMachineFunction().liveout_empty()) {
702 for (unsigned i = 0; i != RVLocs.size(); ++i)
703 if (RVLocs[i].isRegLoc())
704 DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
706 SDOperand Chain = Op.getOperand(0);
708 // Handle tail call return.
709 Chain = GetPossiblePreceedingTailCall(Chain);
710 if (Chain.getOpcode() == X86ISD::TAILCALL) {
711 SDOperand TailCall = Chain;
712 SDOperand TargetAddress = TailCall.getOperand(1);
713 SDOperand StackAdjustment = TailCall.getOperand(2);
714 assert ( ((TargetAddress.getOpcode() == ISD::Register &&
715 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
716 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
717 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
718 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
719 "Expecting an global address, external symbol, or register");
720 assert( StackAdjustment.getOpcode() == ISD::Constant &&
721 "Expecting a const value");
723 SmallVector<SDOperand,8> Operands;
724 Operands.push_back(Chain.getOperand(0));
725 Operands.push_back(TargetAddress);
726 Operands.push_back(StackAdjustment);
727 // Copy registers used by the call. Last operand is a flag so it is not
729 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
730 Operands.push_back(Chain.getOperand(i));
732 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
739 // Copy the result values into the output registers.
740 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
741 RVLocs[0].getLocReg() != X86::ST0) {
742 for (unsigned i = 0; i != RVLocs.size(); ++i) {
743 CCValAssign &VA = RVLocs[i];
744 assert(VA.isRegLoc() && "Can only return in registers!");
745 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
747 Flag = Chain.getValue(1);
750 // We need to handle a destination of ST0 specially, because it isn't really
752 SDOperand Value = Op.getOperand(1);
754 // If this is an FP return with ScalarSSE, we need to move the value from
755 // an XMM register onto the fp-stack.
756 if ((X86ScalarSSEf32 && RVLocs[0].getValVT()==MVT::f32) ||
757 (X86ScalarSSEf64 && RVLocs[0].getValVT()==MVT::f64)) {
760 // If this is a load into a scalarsse value, don't store the loaded value
761 // back to the stack, only to reload it: just replace the scalar-sse load.
762 if (ISD::isNON_EXTLoad(Value.Val) &&
763 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
764 Chain = Value.getOperand(0);
765 MemLoc = Value.getOperand(1);
767 // Spill the value to memory and reload it into top of stack.
768 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
769 MachineFunction &MF = DAG.getMachineFunction();
770 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
771 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
772 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
774 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
775 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
776 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
777 Chain = Value.getValue(1);
780 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
781 SDOperand Ops[] = { Chain, Value };
782 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
783 Flag = Chain.getValue(1);
786 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
788 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
790 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
794 /// LowerCallResult - Lower the result values of an ISD::CALL into the
795 /// appropriate copies out of appropriate physical registers. This assumes that
796 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
797 /// being lowered. The returns a SDNode with the same number of values as the
799 SDNode *X86TargetLowering::
800 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
801 unsigned CallingConv, SelectionDAG &DAG) {
803 // Assign locations to each value returned by this call.
804 SmallVector<CCValAssign, 16> RVLocs;
805 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
806 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
807 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
810 SmallVector<SDOperand, 8> ResultVals;
812 // Copy all of the result registers out of their specified physreg.
813 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
814 for (unsigned i = 0; i != RVLocs.size(); ++i) {
815 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
816 RVLocs[i].getValVT(), InFlag).getValue(1);
817 InFlag = Chain.getValue(2);
818 ResultVals.push_back(Chain.getValue(0));
821 // Copies from the FP stack are special, as ST0 isn't a valid register
822 // before the fp stackifier runs.
824 // Copy ST0 into an RFP register with FP_GET_RESULT.
825 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
826 SDOperand GROps[] = { Chain, InFlag };
827 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
828 Chain = RetVal.getValue(1);
829 InFlag = RetVal.getValue(2);
831 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
833 if ((X86ScalarSSEf32 && RVLocs[0].getValVT() == MVT::f32) ||
834 (X86ScalarSSEf64 && RVLocs[0].getValVT() == MVT::f64)) {
835 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
836 // shouldn't be necessary except that RFP cannot be live across
837 // multiple blocks. When stackifier is fixed, they can be uncoupled.
838 MachineFunction &MF = DAG.getMachineFunction();
839 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
840 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
842 Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
844 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
845 RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
846 Chain = RetVal.getValue(1);
848 ResultVals.push_back(RetVal);
851 // Merge everything together with a MERGE_VALUES node.
852 ResultVals.push_back(Chain);
853 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
854 &ResultVals[0], ResultVals.size()).Val;
858 //===----------------------------------------------------------------------===//
859 // C & StdCall & Fast Calling Convention implementation
860 //===----------------------------------------------------------------------===//
861 // StdCall calling convention seems to be standard for many Windows' API
862 // routines and around. It differs from C calling convention just a little:
863 // callee should clean up the stack, not caller. Symbols should be also
864 // decorated in some fancy way :) It doesn't support any vector arguments.
865 // For info on fast calling convention see Fast Calling Convention (tail call)
866 // implementation LowerX86_32FastCCCallTo.
868 /// AddLiveIn - This helper function adds the specified physical register to the
869 /// MachineFunction as a live in value. It also creates a corresponding virtual
871 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
872 const TargetRegisterClass *RC) {
873 assert(RC->contains(PReg) && "Not the correct regclass!");
874 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
875 MF.addLiveIn(PReg, VReg);
879 // align stack arguments according to platform alignment needed for tail calls
880 unsigned GetAlignedArgumentStackSize(unsigned StackSize, SelectionDAG& DAG);
882 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
883 const CCValAssign &VA,
884 MachineFrameInfo *MFI,
885 SDOperand Root, unsigned i) {
886 // Create the nodes corresponding to a load from this parameter slot.
887 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
888 VA.getLocMemOffset());
889 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
891 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
893 if (Flags & ISD::ParamFlags::ByVal)
896 return DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0);
899 SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
901 unsigned NumArgs = Op.Val->getNumValues() - 1;
902 MachineFunction &MF = DAG.getMachineFunction();
903 MachineFrameInfo *MFI = MF.getFrameInfo();
904 SDOperand Root = Op.getOperand(0);
905 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
906 unsigned CC = MF.getFunction()->getCallingConv();
907 // Assign locations to all of the incoming arguments.
908 SmallVector<CCValAssign, 16> ArgLocs;
909 CCState CCInfo(CC, isVarArg,
910 getTargetMachine(), ArgLocs);
911 // Check for possible tail call calling convention.
912 if (CC == CallingConv::Fast && PerformTailCallOpt)
913 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_TailCall);
915 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
917 SmallVector<SDOperand, 8> ArgValues;
918 unsigned LastVal = ~0U;
919 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
920 CCValAssign &VA = ArgLocs[i];
921 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
923 assert(VA.getValNo() != LastVal &&
924 "Don't support value assigned to multiple locs yet");
925 LastVal = VA.getValNo();
928 MVT::ValueType RegVT = VA.getLocVT();
929 TargetRegisterClass *RC;
930 if (RegVT == MVT::i32)
931 RC = X86::GR32RegisterClass;
933 assert(MVT::isVector(RegVT));
934 RC = X86::VR128RegisterClass;
937 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
938 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
940 // If this is an 8 or 16-bit value, it is really passed promoted to 32
941 // bits. Insert an assert[sz]ext to capture this, then truncate to the
943 if (VA.getLocInfo() == CCValAssign::SExt)
944 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
945 DAG.getValueType(VA.getValVT()));
946 else if (VA.getLocInfo() == CCValAssign::ZExt)
947 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
948 DAG.getValueType(VA.getValVT()));
950 if (VA.getLocInfo() != CCValAssign::Full)
951 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
953 ArgValues.push_back(ArgValue);
955 assert(VA.isMemLoc());
956 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
960 unsigned StackSize = CCInfo.getNextStackOffset();
961 // align stack specially for tail calls
962 if (CC==CallingConv::Fast)
963 StackSize = GetAlignedArgumentStackSize(StackSize,DAG);
965 ArgValues.push_back(Root);
967 // If the function takes variable number of arguments, make a frame index for
968 // the start of the first vararg value... for expansion of llvm.va_start.
970 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
972 // Tail call calling convention (CallingConv::Fast) does not support varargs.
973 assert( !(isVarArg && CC == CallingConv::Fast) &&
974 "CallingConv::Fast does not support varargs.");
976 if (isStdCall && !isVarArg &&
977 (CC==CallingConv::Fast && PerformTailCallOpt || CC!=CallingConv::Fast)) {
978 BytesToPopOnReturn = StackSize; // Callee pops everything..
979 BytesCallerReserves = 0;
981 BytesToPopOnReturn = 0; // Callee pops nothing.
983 // If this is an sret function, the return should pop the hidden pointer.
985 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
986 ISD::ParamFlags::StructReturn))
987 BytesToPopOnReturn = 4;
989 BytesCallerReserves = StackSize;
992 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
994 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
995 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
997 // Return the new list of results.
998 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
999 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1002 SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
1004 SDOperand Chain = Op.getOperand(0);
1005 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1006 SDOperand Callee = Op.getOperand(4);
1007 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1009 // Analyze operands of the call, assigning locations to each operand.
1010 SmallVector<CCValAssign, 16> ArgLocs;
1011 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1012 if(CC==CallingConv::Fast && PerformTailCallOpt)
1013 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1015 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
1017 // Get a count of how many bytes are to be pushed on the stack.
1018 unsigned NumBytes = CCInfo.getNextStackOffset();
1019 if (CC==CallingConv::Fast)
1020 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1022 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1024 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1025 SmallVector<SDOperand, 8> MemOpChains;
1029 // Walk the register/memloc assignments, inserting copies/loads.
1030 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1031 CCValAssign &VA = ArgLocs[i];
1032 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1034 // Promote the value if needed.
1035 switch (VA.getLocInfo()) {
1036 default: assert(0 && "Unknown loc info!");
1037 case CCValAssign::Full: break;
1038 case CCValAssign::SExt:
1039 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1041 case CCValAssign::ZExt:
1042 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1044 case CCValAssign::AExt:
1045 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1049 if (VA.isRegLoc()) {
1050 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1052 assert(VA.isMemLoc());
1053 if (StackPtr.Val == 0)
1054 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1056 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1061 // If the first argument is an sret pointer, remember it.
1062 bool isSRet = NumOps &&
1063 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
1064 ISD::ParamFlags::StructReturn);
1066 if (!MemOpChains.empty())
1067 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1068 &MemOpChains[0], MemOpChains.size());
1070 // Build a sequence of copy-to-reg nodes chained together with token chain
1071 // and flag operands which copy the outgoing args into registers.
1073 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1074 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1076 InFlag = Chain.getValue(1);
1079 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1081 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1082 Subtarget->isPICStyleGOT()) {
1083 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1084 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1086 InFlag = Chain.getValue(1);
1089 // If the callee is a GlobalAddress node (quite common, every direct call is)
1090 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1091 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1092 // We should use extra load for direct calls to dllimported functions in
1094 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1095 getTargetMachine(), true))
1096 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1097 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1098 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1100 // Returns a chain & a flag for retval copy to use.
1101 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1102 SmallVector<SDOperand, 8> Ops;
1103 Ops.push_back(Chain);
1104 Ops.push_back(Callee);
1106 // Add argument registers to the end of the list so that they are known live
1108 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1109 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1110 RegsToPass[i].second.getValueType()));
1112 // Add an implicit use GOT pointer in EBX.
1113 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1114 Subtarget->isPICStyleGOT())
1115 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1118 Ops.push_back(InFlag);
1120 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1121 InFlag = Chain.getValue(1);
1123 // Create the CALLSEQ_END node.
1124 unsigned NumBytesForCalleeToPush = 0;
1126 if (CC == CallingConv::X86_StdCall ||
1127 (CC == CallingConv::Fast && PerformTailCallOpt)) {
1129 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1131 NumBytesForCalleeToPush = NumBytes;
1132 assert(!(isVarArg && CC==CallingConv::Fast) &&
1133 "CallingConv::Fast does not support varargs.");
1135 // If this is is a call to a struct-return function, the callee
1136 // pops the hidden struct pointer, so we have to push it back.
1137 // This is common for Darwin/X86, Linux & Mingw32 targets.
1138 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1141 Chain = DAG.getCALLSEQ_END(Chain,
1142 DAG.getConstant(NumBytes, getPointerTy()),
1143 DAG.getConstant(NumBytesForCalleeToPush,
1146 InFlag = Chain.getValue(1);
1148 // Handle result values, copying them out of physregs into vregs that we
1150 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1154 //===----------------------------------------------------------------------===//
1155 // FastCall Calling Convention implementation
1156 //===----------------------------------------------------------------------===//
1158 // The X86 'fastcall' calling convention passes up to two integer arguments in
1159 // registers (an appropriate portion of ECX/EDX), passes arguments in C order,
1160 // and requires that the callee pop its arguments off the stack (allowing proper
1161 // tail calls), and has the same return value conventions as C calling convs.
1163 // This calling convention always arranges for the callee pop value to be 8n+4
1164 // bytes, which is needed for tail recursion elimination and stack alignment
1167 X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
1168 MachineFunction &MF = DAG.getMachineFunction();
1169 MachineFrameInfo *MFI = MF.getFrameInfo();
1170 SDOperand Root = Op.getOperand(0);
1171 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1173 // Assign locations to all of the incoming arguments.
1174 SmallVector<CCValAssign, 16> ArgLocs;
1175 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
1176 getTargetMachine(), ArgLocs);
1177 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
1179 SmallVector<SDOperand, 8> ArgValues;
1180 unsigned LastVal = ~0U;
1181 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1182 CCValAssign &VA = ArgLocs[i];
1183 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1185 assert(VA.getValNo() != LastVal &&
1186 "Don't support value assigned to multiple locs yet");
1187 LastVal = VA.getValNo();
1189 if (VA.isRegLoc()) {
1190 MVT::ValueType RegVT = VA.getLocVT();
1191 TargetRegisterClass *RC;
1192 if (RegVT == MVT::i32)
1193 RC = X86::GR32RegisterClass;
1195 assert(MVT::isVector(RegVT));
1196 RC = X86::VR128RegisterClass;
1199 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1200 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1202 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1203 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1205 if (VA.getLocInfo() == CCValAssign::SExt)
1206 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1207 DAG.getValueType(VA.getValVT()));
1208 else if (VA.getLocInfo() == CCValAssign::ZExt)
1209 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1210 DAG.getValueType(VA.getValVT()));
1212 if (VA.getLocInfo() != CCValAssign::Full)
1213 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1215 ArgValues.push_back(ArgValue);
1217 assert(VA.isMemLoc());
1218 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1222 ArgValues.push_back(Root);
1224 unsigned StackSize = CCInfo.getNextStackOffset();
1226 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1227 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1228 // arguments and the arguments after the retaddr has been pushed are
1230 if ((StackSize & 7) == 0)
1234 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1235 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
1236 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
1237 BytesCallerReserves = 0;
1239 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1240 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1242 // Return the new list of results.
1243 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1244 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1248 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1249 const SDOperand &StackPtr,
1250 const CCValAssign &VA,
1253 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1254 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1255 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1256 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1257 if (Flags & ISD::ParamFlags::ByVal) {
1258 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1259 ISD::ParamFlags::ByValAlignOffs);
1261 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1262 ISD::ParamFlags::ByValSizeOffs;
1264 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1265 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1266 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1268 return DAG.getMemcpy(Chain, PtrOff, Arg, SizeNode, AlignNode,
1271 return DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1275 SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1277 SDOperand Chain = Op.getOperand(0);
1278 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1279 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1280 SDOperand Callee = Op.getOperand(4);
1282 // Analyze operands of the call, assigning locations to each operand.
1283 SmallVector<CCValAssign, 16> ArgLocs;
1284 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1285 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1287 // Get a count of how many bytes are to be pushed on the stack.
1288 unsigned NumBytes = CCInfo.getNextStackOffset();
1290 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1291 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1292 // arguments and the arguments after the retaddr has been pushed are
1294 if ((NumBytes & 7) == 0)
1298 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1300 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1301 SmallVector<SDOperand, 8> MemOpChains;
1305 // Walk the register/memloc assignments, inserting copies/loads.
1306 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1307 CCValAssign &VA = ArgLocs[i];
1308 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1310 // Promote the value if needed.
1311 switch (VA.getLocInfo()) {
1312 default: assert(0 && "Unknown loc info!");
1313 case CCValAssign::Full: break;
1314 case CCValAssign::SExt:
1315 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1317 case CCValAssign::ZExt:
1318 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1320 case CCValAssign::AExt:
1321 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1325 if (VA.isRegLoc()) {
1326 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1328 assert(VA.isMemLoc());
1329 if (StackPtr.Val == 0)
1330 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1332 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1337 if (!MemOpChains.empty())
1338 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1339 &MemOpChains[0], MemOpChains.size());
1341 // Build a sequence of copy-to-reg nodes chained together with token chain
1342 // and flag operands which copy the outgoing args into registers.
1344 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1345 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1347 InFlag = Chain.getValue(1);
1350 // If the callee is a GlobalAddress node (quite common, every direct call is)
1351 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1352 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1353 // We should use extra load for direct calls to dllimported functions in
1355 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1356 getTargetMachine(), true))
1357 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1358 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1359 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1361 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1363 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1364 Subtarget->isPICStyleGOT()) {
1365 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1366 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1368 InFlag = Chain.getValue(1);
1371 // Returns a chain & a flag for retval copy to use.
1372 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1373 SmallVector<SDOperand, 8> Ops;
1374 Ops.push_back(Chain);
1375 Ops.push_back(Callee);
1377 // Add argument registers to the end of the list so that they are known live
1379 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1380 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1381 RegsToPass[i].second.getValueType()));
1383 // Add an implicit use GOT pointer in EBX.
1384 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1385 Subtarget->isPICStyleGOT())
1386 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1389 Ops.push_back(InFlag);
1391 assert(isTailCall==false && "no tail call here");
1392 Chain = DAG.getNode(X86ISD::CALL,
1393 NodeTys, &Ops[0], Ops.size());
1394 InFlag = Chain.getValue(1);
1396 // Returns a flag for retval copy to use.
1397 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1399 Ops.push_back(Chain);
1400 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1401 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1402 Ops.push_back(InFlag);
1403 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1404 InFlag = Chain.getValue(1);
1406 // Handle result values, copying them out of physregs into vregs that we
1408 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1411 //===----------------------------------------------------------------------===//
1412 // Fast Calling Convention (tail call) implementation
1413 //===----------------------------------------------------------------------===//
1415 // Like std call, callee cleans arguments, convention except that ECX is
1416 // reserved for storing the tail called function address. Only 2 registers are
1417 // free for argument passing (inreg). Tail call optimization is performed
1419 // * tailcallopt is enabled
1420 // * caller/callee are fastcc
1421 // * elf/pic is disabled OR
1422 // * elf/pic enabled + callee is in module + callee has
1423 // visibility protected or hidden
1424 // To keep the stack aligned according to platform abi the function
1425 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1426 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1427 // If a tail called function callee has more arguments than the caller the
1428 // caller needs to make sure that there is room to move the RETADDR to. This is
1429 // achieved by reserving an area the size of the argument delta right after the
1430 // original REtADDR, but before the saved framepointer or the spilled registers
1431 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1443 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1444 /// for a 16 byte align requirement.
1445 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1446 SelectionDAG& DAG) {
1447 if (PerformTailCallOpt) {
1448 MachineFunction &MF = DAG.getMachineFunction();
1449 const TargetMachine &TM = MF.getTarget();
1450 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1451 unsigned StackAlignment = TFI.getStackAlignment();
1452 uint64_t AlignMask = StackAlignment - 1;
1453 int64_t Offset = StackSize;
1454 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1455 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1456 // Number smaller than 12 so just add the difference.
1457 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1459 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1460 Offset = ((~AlignMask) & Offset) + StackAlignment +
1461 (StackAlignment-SlotSize);
1468 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1469 /// following the call is a return. A function is eligible if caller/callee
1470 /// calling conventions match, currently only fastcc supports tail calls, and
1471 /// the function CALL is immediatly followed by a RET.
1472 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1474 SelectionDAG& DAG) const {
1475 if (!PerformTailCallOpt)
1478 // Check whether CALL node immediatly preceeds the RET node and whether the
1479 // return uses the result of the node or is a void return.
1480 unsigned NumOps = Ret.getNumOperands();
1482 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1483 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1485 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1486 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1487 MachineFunction &MF = DAG.getMachineFunction();
1488 unsigned CallerCC = MF.getFunction()->getCallingConv();
1489 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1490 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1491 SDOperand Callee = Call.getOperand(4);
1492 // On elf/pic %ebx needs to be livein.
1493 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1494 !Subtarget->isPICStyleGOT())
1497 // Can only do local tail calls with PIC.
1498 GlobalValue * GV = 0;
1499 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1501 (GV = G->getGlobal()) &&
1502 (GV->hasHiddenVisibility() || GV->hasProtectedVisibility()))
1510 SDOperand X86TargetLowering::LowerX86_TailCallTo(SDOperand Op,
1513 SDOperand Chain = Op.getOperand(0);
1514 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1515 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1516 SDOperand Callee = Op.getOperand(4);
1517 bool is64Bit = Subtarget->is64Bit();
1519 assert(isTailCall && PerformTailCallOpt && "Should only emit tail calls.");
1521 // Analyze operands of the call, assigning locations to each operand.
1522 SmallVector<CCValAssign, 16> ArgLocs;
1523 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1525 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1527 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1530 // Lower arguments at fp - stackoffset + fpdiff.
1531 MachineFunction &MF = DAG.getMachineFunction();
1533 unsigned NumBytesToBePushed =
1534 GetAlignedArgumentStackSize(CCInfo.getNextStackOffset(), DAG);
1536 unsigned NumBytesCallerPushed =
1537 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1538 int FPDiff = NumBytesCallerPushed - NumBytesToBePushed;
1540 // Set the delta of movement of the returnaddr stackslot.
1541 // But only set if delta is greater than previous delta.
1542 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1543 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1546 getCALLSEQ_START(Chain, DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1548 // Adjust the Return address stack slot.
1549 SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
1551 MVT::ValueType VT = is64Bit ? MVT::i64 : MVT::i32;
1552 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1553 // Load the "old" Return address.
1555 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1556 // Calculate the new stack slot for the return address.
1557 int SlotSize = is64Bit ? 8 : 4;
1558 int NewReturnAddrFI =
1559 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1560 NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1561 Chain = SDOperand(RetAddrFrIdx.Val, 1);
1564 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1565 SmallVector<SDOperand, 8> MemOpChains;
1566 SmallVector<SDOperand, 8> MemOpChains2;
1567 SDOperand FramePtr, StackPtr;
1572 // Walk the register/memloc assignments, inserting copies/loads. Lower
1573 // arguments first to the stack slot where they would normally - in case of a
1574 // normal function call - be.
1575 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1576 CCValAssign &VA = ArgLocs[i];
1577 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1579 // Promote the value if needed.
1580 switch (VA.getLocInfo()) {
1581 default: assert(0 && "Unknown loc info!");
1582 case CCValAssign::Full: break;
1583 case CCValAssign::SExt:
1584 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1586 case CCValAssign::ZExt:
1587 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1589 case CCValAssign::AExt:
1590 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1594 if (VA.isRegLoc()) {
1595 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1597 assert(VA.isMemLoc());
1598 if (StackPtr.Val == 0)
1599 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1601 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1606 if (!MemOpChains.empty())
1607 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1608 &MemOpChains[0], MemOpChains.size());
1610 // Build a sequence of copy-to-reg nodes chained together with token chain
1611 // and flag operands which copy the outgoing args into registers.
1613 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1614 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1616 InFlag = Chain.getValue(1);
1618 InFlag = SDOperand();
1620 // Copy from stack slots to stack slot of a tail called function. This needs
1621 // to be done because if we would lower the arguments directly to their real
1622 // stack slot we might end up overwriting each other.
1623 // TODO: To make this more efficient (sometimes saving a store/load) we could
1624 // analyse the arguments and emit this store/load/store sequence only for
1625 // arguments which would be overwritten otherwise.
1626 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1627 CCValAssign &VA = ArgLocs[i];
1628 if (!VA.isRegLoc()) {
1629 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1630 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1632 // Get source stack slot.
1633 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1634 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1635 // Create frame index.
1636 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1637 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1638 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1639 FIN = DAG.getFrameIndex(FI, MVT::i32);
1640 if (Flags & ISD::ParamFlags::ByVal) {
1641 // Copy relative to framepointer.
1642 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1643 ISD::ParamFlags::ByValAlignOffs);
1645 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1646 ISD::ParamFlags::ByValSizeOffs;
1648 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1649 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1650 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i1);
1652 MemOpChains2.push_back(DAG.getMemcpy(Chain, FIN, PtrOff, SizeNode,
1653 AlignNode,AlwaysInline));
1655 SDOperand LoadedArg = DAG.getLoad(VA.getValVT(), Chain, PtrOff, NULL,0);
1656 // Store relative to framepointer.
1657 MemOpChains2.push_back(DAG.getStore(Chain, LoadedArg, FIN, NULL, 0));
1662 if (!MemOpChains2.empty())
1663 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1664 &MemOpChains2[0], MemOpChains.size());
1666 // Store the return address to the appropriate stack slot.
1668 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1670 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1672 // Does not work with tail call since ebx is not restored correctly by
1673 // tailcaller. TODO: at least for x86 - verify for x86-64
1675 // If the callee is a GlobalAddress node (quite common, every direct call is)
1676 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1677 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1678 // We should use extra load for direct calls to dllimported functions in
1680 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1681 getTargetMachine(), true))
1682 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1683 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1684 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1686 assert(Callee.getOpcode() == ISD::LOAD &&
1687 "Function destination must be loaded into virtual register");
1688 unsigned Opc = is64Bit ? X86::R9 : X86::ECX;
1690 Chain = DAG.getCopyToReg(Chain,
1691 DAG.getRegister(Opc, getPointerTy()) ,
1693 Callee = DAG.getRegister(Opc, getPointerTy());
1694 // Add register as live out.
1695 DAG.getMachineFunction().addLiveOut(Opc);
1698 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1699 SmallVector<SDOperand, 8> Ops;
1701 Ops.push_back(Chain);
1702 Ops.push_back(DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1703 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1705 Ops.push_back(InFlag);
1706 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1707 InFlag = Chain.getValue(1);
1709 // Returns a chain & a flag for retval copy to use.
1710 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1712 Ops.push_back(Chain);
1713 Ops.push_back(Callee);
1714 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1715 // Add argument registers to the end of the list so that they are known live
1717 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1718 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1719 RegsToPass[i].second.getValueType()));
1721 Ops.push_back(InFlag);
1722 assert(InFlag.Val &&
1723 "Flag must be set. Depend on flag being set in LowerRET");
1724 Chain = DAG.getNode(X86ISD::TAILCALL,
1725 Op.Val->getVTList(), &Ops[0], Ops.size());
1727 return SDOperand(Chain.Val, Op.ResNo);
1730 //===----------------------------------------------------------------------===//
1731 // X86-64 C Calling Convention implementation
1732 //===----------------------------------------------------------------------===//
1735 X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1736 MachineFunction &MF = DAG.getMachineFunction();
1737 MachineFrameInfo *MFI = MF.getFrameInfo();
1738 SDOperand Root = Op.getOperand(0);
1739 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1740 unsigned CC= MF.getFunction()->getCallingConv();
1742 static const unsigned GPR64ArgRegs[] = {
1743 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1745 static const unsigned XMMArgRegs[] = {
1746 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1747 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1751 // Assign locations to all of the incoming arguments.
1752 SmallVector<CCValAssign, 16> ArgLocs;
1753 CCState CCInfo(CC, isVarArg,
1754 getTargetMachine(), ArgLocs);
1755 if (CC == CallingConv::Fast && PerformTailCallOpt)
1756 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_TailCall);
1758 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
1760 SmallVector<SDOperand, 8> ArgValues;
1761 unsigned LastVal = ~0U;
1762 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1763 CCValAssign &VA = ArgLocs[i];
1764 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1766 assert(VA.getValNo() != LastVal &&
1767 "Don't support value assigned to multiple locs yet");
1768 LastVal = VA.getValNo();
1770 if (VA.isRegLoc()) {
1771 MVT::ValueType RegVT = VA.getLocVT();
1772 TargetRegisterClass *RC;
1773 if (RegVT == MVT::i32)
1774 RC = X86::GR32RegisterClass;
1775 else if (RegVT == MVT::i64)
1776 RC = X86::GR64RegisterClass;
1777 else if (RegVT == MVT::f32)
1778 RC = X86::FR32RegisterClass;
1779 else if (RegVT == MVT::f64)
1780 RC = X86::FR64RegisterClass;
1782 assert(MVT::isVector(RegVT));
1783 if (MVT::getSizeInBits(RegVT) == 64) {
1784 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1787 RC = X86::VR128RegisterClass;
1790 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1791 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1793 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1794 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1796 if (VA.getLocInfo() == CCValAssign::SExt)
1797 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1798 DAG.getValueType(VA.getValVT()));
1799 else if (VA.getLocInfo() == CCValAssign::ZExt)
1800 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1801 DAG.getValueType(VA.getValVT()));
1803 if (VA.getLocInfo() != CCValAssign::Full)
1804 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1806 // Handle MMX values passed in GPRs.
1807 if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1808 MVT::getSizeInBits(RegVT) == 64)
1809 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1811 ArgValues.push_back(ArgValue);
1813 assert(VA.isMemLoc());
1814 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1818 unsigned StackSize = CCInfo.getNextStackOffset();
1819 if (CC==CallingConv::Fast)
1820 StackSize =GetAlignedArgumentStackSize(StackSize, DAG);
1822 // If the function takes variable number of arguments, make a frame index for
1823 // the start of the first vararg value... for expansion of llvm.va_start.
1825 assert(CC!=CallingConv::Fast
1826 && "Var arg not supported with calling convention fastcc");
1827 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1828 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1830 // For X86-64, if there are vararg parameters that are passed via
1831 // registers, then we must store them to their spots on the stack so they
1832 // may be loaded by deferencing the result of va_next.
1833 VarArgsGPOffset = NumIntRegs * 8;
1834 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1835 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1836 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1838 // Store the integer parameter registers.
1839 SmallVector<SDOperand, 8> MemOps;
1840 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1841 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1842 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1843 for (; NumIntRegs != 6; ++NumIntRegs) {
1844 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1845 X86::GR64RegisterClass);
1846 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1847 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1848 MemOps.push_back(Store);
1849 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1850 DAG.getConstant(8, getPointerTy()));
1853 // Now store the XMM (fp + vector) parameter registers.
1854 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1855 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1856 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1857 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1858 X86::VR128RegisterClass);
1859 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1860 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1861 MemOps.push_back(Store);
1862 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1863 DAG.getConstant(16, getPointerTy()));
1865 if (!MemOps.empty())
1866 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1867 &MemOps[0], MemOps.size());
1870 ArgValues.push_back(Root);
1871 // Tail call convention (fastcc) needs callee pop.
1872 if (CC == CallingConv::Fast && PerformTailCallOpt) {
1873 BytesToPopOnReturn = StackSize; // Callee pops everything.
1874 BytesCallerReserves = 0;
1876 BytesToPopOnReturn = 0; // Callee pops nothing.
1877 BytesCallerReserves = StackSize;
1879 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1880 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1882 // Return the new list of results.
1883 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1884 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1888 X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1890 SDOperand Chain = Op.getOperand(0);
1891 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1892 SDOperand Callee = Op.getOperand(4);
1894 // Analyze operands of the call, assigning locations to each operand.
1895 SmallVector<CCValAssign, 16> ArgLocs;
1896 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1897 if (CC==CallingConv::Fast && PerformTailCallOpt)
1898 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1900 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
1902 // Get a count of how many bytes are to be pushed on the stack.
1903 unsigned NumBytes = CCInfo.getNextStackOffset();
1904 if (CC == CallingConv::Fast)
1905 NumBytes = GetAlignedArgumentStackSize(NumBytes,DAG);
1907 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1909 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1910 SmallVector<SDOperand, 8> MemOpChains;
1914 // Walk the register/memloc assignments, inserting copies/loads.
1915 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1916 CCValAssign &VA = ArgLocs[i];
1917 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1919 // Promote the value if needed.
1920 switch (VA.getLocInfo()) {
1921 default: assert(0 && "Unknown loc info!");
1922 case CCValAssign::Full: break;
1923 case CCValAssign::SExt:
1924 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1926 case CCValAssign::ZExt:
1927 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1929 case CCValAssign::AExt:
1930 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1934 if (VA.isRegLoc()) {
1935 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1937 assert(VA.isMemLoc());
1938 if (StackPtr.Val == 0)
1939 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1941 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1946 if (!MemOpChains.empty())
1947 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1948 &MemOpChains[0], MemOpChains.size());
1950 // Build a sequence of copy-to-reg nodes chained together with token chain
1951 // and flag operands which copy the outgoing args into registers.
1953 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1954 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1956 InFlag = Chain.getValue(1);
1960 assert ( CallingConv::Fast != CC &&
1961 "Var args not supported with calling convention fastcc");
1963 // From AMD64 ABI document:
1964 // For calls that may call functions that use varargs or stdargs
1965 // (prototype-less calls or calls to functions containing ellipsis (...) in
1966 // the declaration) %al is used as hidden argument to specify the number
1967 // of SSE registers used. The contents of %al do not need to match exactly
1968 // the number of registers, but must be an ubound on the number of SSE
1969 // registers used and is in the range 0 - 8 inclusive.
1971 // Count the number of XMM registers allocated.
1972 static const unsigned XMMArgRegs[] = {
1973 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1974 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1976 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1978 Chain = DAG.getCopyToReg(Chain, X86::AL,
1979 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1980 InFlag = Chain.getValue(1);
1983 // If the callee is a GlobalAddress node (quite common, every direct call is)
1984 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1985 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1986 // We should use extra load for direct calls to dllimported functions in
1988 if (getTargetMachine().getCodeModel() != CodeModel::Large
1989 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1990 getTargetMachine(), true))
1991 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1992 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1993 if (getTargetMachine().getCodeModel() != CodeModel::Large)
1994 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1996 // Returns a chain & a flag for retval copy to use.
1997 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1998 SmallVector<SDOperand, 8> Ops;
1999 Ops.push_back(Chain);
2000 Ops.push_back(Callee);
2002 // Add argument registers to the end of the list so that they are known live
2004 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2005 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2006 RegsToPass[i].second.getValueType()));
2009 Ops.push_back(InFlag);
2011 Chain = DAG.getNode(X86ISD::CALL,
2012 NodeTys, &Ops[0], Ops.size());
2013 InFlag = Chain.getValue(1);
2014 int NumBytesForCalleeToPush = 0;
2015 if (CC==CallingConv::Fast && PerformTailCallOpt) {
2016 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2018 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2020 // Returns a flag for retval copy to use.
2021 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2023 Ops.push_back(Chain);
2024 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
2025 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
2026 Ops.push_back(InFlag);
2027 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
2028 InFlag = Chain.getValue(1);
2030 // Handle result values, copying them out of physregs into vregs that we
2032 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
2036 //===----------------------------------------------------------------------===//
2037 // Other Lowering Hooks
2038 //===----------------------------------------------------------------------===//
2041 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2042 MachineFunction &MF = DAG.getMachineFunction();
2043 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2044 int ReturnAddrIndex = FuncInfo->getRAIndex();
2046 if (ReturnAddrIndex == 0) {
2047 // Set up a frame object for the return address.
2048 if (Subtarget->is64Bit())
2049 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
2051 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
2053 FuncInfo->setRAIndex(ReturnAddrIndex);
2056 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2061 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
2062 /// specific condition code. It returns a false if it cannot do a direct
2063 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
2065 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2066 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
2067 SelectionDAG &DAG) {
2068 X86CC = X86::COND_INVALID;
2070 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2071 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2072 // X > -1 -> X == 0, jump !sign.
2073 RHS = DAG.getConstant(0, RHS.getValueType());
2074 X86CC = X86::COND_NS;
2076 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2077 // X < 0 -> X == 0, jump on sign.
2078 X86CC = X86::COND_S;
2080 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
2082 RHS = DAG.getConstant(0, RHS.getValueType());
2083 X86CC = X86::COND_LE;
2088 switch (SetCCOpcode) {
2090 case ISD::SETEQ: X86CC = X86::COND_E; break;
2091 case ISD::SETGT: X86CC = X86::COND_G; break;
2092 case ISD::SETGE: X86CC = X86::COND_GE; break;
2093 case ISD::SETLT: X86CC = X86::COND_L; break;
2094 case ISD::SETLE: X86CC = X86::COND_LE; break;
2095 case ISD::SETNE: X86CC = X86::COND_NE; break;
2096 case ISD::SETULT: X86CC = X86::COND_B; break;
2097 case ISD::SETUGT: X86CC = X86::COND_A; break;
2098 case ISD::SETULE: X86CC = X86::COND_BE; break;
2099 case ISD::SETUGE: X86CC = X86::COND_AE; break;
2102 // On a floating point condition, the flags are set as follows:
2104 // 0 | 0 | 0 | X > Y
2105 // 0 | 0 | 1 | X < Y
2106 // 1 | 0 | 0 | X == Y
2107 // 1 | 1 | 1 | unordered
2109 switch (SetCCOpcode) {
2112 case ISD::SETEQ: X86CC = X86::COND_E; break;
2113 case ISD::SETOLT: Flip = true; // Fallthrough
2115 case ISD::SETGT: X86CC = X86::COND_A; break;
2116 case ISD::SETOLE: Flip = true; // Fallthrough
2118 case ISD::SETGE: X86CC = X86::COND_AE; break;
2119 case ISD::SETUGT: Flip = true; // Fallthrough
2121 case ISD::SETLT: X86CC = X86::COND_B; break;
2122 case ISD::SETUGE: Flip = true; // Fallthrough
2124 case ISD::SETLE: X86CC = X86::COND_BE; break;
2126 case ISD::SETNE: X86CC = X86::COND_NE; break;
2127 case ISD::SETUO: X86CC = X86::COND_P; break;
2128 case ISD::SETO: X86CC = X86::COND_NP; break;
2131 std::swap(LHS, RHS);
2134 return X86CC != X86::COND_INVALID;
2137 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2138 /// code. Current x86 isa includes the following FP cmov instructions:
2139 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2140 static bool hasFPCMov(unsigned X86CC) {
2156 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2157 /// true if Op is undef or if its value falls within the specified range (L, H].
2158 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2159 if (Op.getOpcode() == ISD::UNDEF)
2162 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2163 return (Val >= Low && Val < Hi);
2166 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2167 /// true if Op is undef or if its value equal to the specified value.
2168 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2169 if (Op.getOpcode() == ISD::UNDEF)
2171 return cast<ConstantSDNode>(Op)->getValue() == Val;
2174 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2175 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2176 bool X86::isPSHUFDMask(SDNode *N) {
2177 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2179 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2182 // Check if the value doesn't reference the second vector.
2183 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2184 SDOperand Arg = N->getOperand(i);
2185 if (Arg.getOpcode() == ISD::UNDEF) continue;
2186 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2187 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2194 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2195 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2196 bool X86::isPSHUFHWMask(SDNode *N) {
2197 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2199 if (N->getNumOperands() != 8)
2202 // Lower quadword copied in order.
2203 for (unsigned i = 0; i != 4; ++i) {
2204 SDOperand Arg = N->getOperand(i);
2205 if (Arg.getOpcode() == ISD::UNDEF) continue;
2206 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2207 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2211 // Upper quadword shuffled.
2212 for (unsigned i = 4; i != 8; ++i) {
2213 SDOperand Arg = N->getOperand(i);
2214 if (Arg.getOpcode() == ISD::UNDEF) continue;
2215 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2216 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2217 if (Val < 4 || Val > 7)
2224 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2225 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2226 bool X86::isPSHUFLWMask(SDNode *N) {
2227 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2229 if (N->getNumOperands() != 8)
2232 // Upper quadword copied in order.
2233 for (unsigned i = 4; i != 8; ++i)
2234 if (!isUndefOrEqual(N->getOperand(i), i))
2237 // Lower quadword shuffled.
2238 for (unsigned i = 0; i != 4; ++i)
2239 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2245 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2246 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2247 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2248 if (NumElems != 2 && NumElems != 4) return false;
2250 unsigned Half = NumElems / 2;
2251 for (unsigned i = 0; i < Half; ++i)
2252 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2254 for (unsigned i = Half; i < NumElems; ++i)
2255 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2261 bool X86::isSHUFPMask(SDNode *N) {
2262 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2263 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2266 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2267 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2268 /// half elements to come from vector 1 (which would equal the dest.) and
2269 /// the upper half to come from vector 2.
2270 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2271 if (NumOps != 2 && NumOps != 4) return false;
2273 unsigned Half = NumOps / 2;
2274 for (unsigned i = 0; i < Half; ++i)
2275 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2277 for (unsigned i = Half; i < NumOps; ++i)
2278 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2283 static bool isCommutedSHUFP(SDNode *N) {
2284 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2285 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2288 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2289 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2290 bool X86::isMOVHLPSMask(SDNode *N) {
2291 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2293 if (N->getNumOperands() != 4)
2296 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2297 return isUndefOrEqual(N->getOperand(0), 6) &&
2298 isUndefOrEqual(N->getOperand(1), 7) &&
2299 isUndefOrEqual(N->getOperand(2), 2) &&
2300 isUndefOrEqual(N->getOperand(3), 3);
2303 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2304 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2306 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2307 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2309 if (N->getNumOperands() != 4)
2312 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2313 return isUndefOrEqual(N->getOperand(0), 2) &&
2314 isUndefOrEqual(N->getOperand(1), 3) &&
2315 isUndefOrEqual(N->getOperand(2), 2) &&
2316 isUndefOrEqual(N->getOperand(3), 3);
2319 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2320 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2321 bool X86::isMOVLPMask(SDNode *N) {
2322 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2324 unsigned NumElems = N->getNumOperands();
2325 if (NumElems != 2 && NumElems != 4)
2328 for (unsigned i = 0; i < NumElems/2; ++i)
2329 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2332 for (unsigned i = NumElems/2; i < NumElems; ++i)
2333 if (!isUndefOrEqual(N->getOperand(i), i))
2339 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2340 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2342 bool X86::isMOVHPMask(SDNode *N) {
2343 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2345 unsigned NumElems = N->getNumOperands();
2346 if (NumElems != 2 && NumElems != 4)
2349 for (unsigned i = 0; i < NumElems/2; ++i)
2350 if (!isUndefOrEqual(N->getOperand(i), i))
2353 for (unsigned i = 0; i < NumElems/2; ++i) {
2354 SDOperand Arg = N->getOperand(i + NumElems/2);
2355 if (!isUndefOrEqual(Arg, i + NumElems))
2362 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2363 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2364 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2365 bool V2IsSplat = false) {
2366 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2369 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2370 SDOperand BitI = Elts[i];
2371 SDOperand BitI1 = Elts[i+1];
2372 if (!isUndefOrEqual(BitI, j))
2375 if (isUndefOrEqual(BitI1, NumElts))
2378 if (!isUndefOrEqual(BitI1, j + NumElts))
2386 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2387 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2388 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2391 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2392 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2393 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2394 bool V2IsSplat = false) {
2395 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2398 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2399 SDOperand BitI = Elts[i];
2400 SDOperand BitI1 = Elts[i+1];
2401 if (!isUndefOrEqual(BitI, j + NumElts/2))
2404 if (isUndefOrEqual(BitI1, NumElts))
2407 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2415 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2416 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2417 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2420 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2421 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2423 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2424 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2426 unsigned NumElems = N->getNumOperands();
2427 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2430 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2431 SDOperand BitI = N->getOperand(i);
2432 SDOperand BitI1 = N->getOperand(i+1);
2434 if (!isUndefOrEqual(BitI, j))
2436 if (!isUndefOrEqual(BitI1, j))
2443 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2444 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2446 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2447 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2449 unsigned NumElems = N->getNumOperands();
2450 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2453 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2454 SDOperand BitI = N->getOperand(i);
2455 SDOperand BitI1 = N->getOperand(i + 1);
2457 if (!isUndefOrEqual(BitI, j))
2459 if (!isUndefOrEqual(BitI1, j))
2466 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2467 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2468 /// MOVSD, and MOVD, i.e. setting the lowest element.
2469 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2470 if (NumElts != 2 && NumElts != 4)
2473 if (!isUndefOrEqual(Elts[0], NumElts))
2476 for (unsigned i = 1; i < NumElts; ++i) {
2477 if (!isUndefOrEqual(Elts[i], i))
2484 bool X86::isMOVLMask(SDNode *N) {
2485 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2486 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2489 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2490 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2491 /// element of vector 2 and the other elements to come from vector 1 in order.
2492 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2493 bool V2IsSplat = false,
2494 bool V2IsUndef = false) {
2495 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2498 if (!isUndefOrEqual(Ops[0], 0))
2501 for (unsigned i = 1; i < NumOps; ++i) {
2502 SDOperand Arg = Ops[i];
2503 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2504 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2505 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2512 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2513 bool V2IsUndef = false) {
2514 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2515 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2516 V2IsSplat, V2IsUndef);
2519 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2520 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2521 bool X86::isMOVSHDUPMask(SDNode *N) {
2522 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2524 if (N->getNumOperands() != 4)
2527 // Expect 1, 1, 3, 3
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 != 1) 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 != 3) return false;
2546 // Don't use movshdup if it can be done with a shufps.
2550 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2551 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2552 bool X86::isMOVSLDUPMask(SDNode *N) {
2553 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2555 if (N->getNumOperands() != 4)
2558 // Expect 0, 0, 2, 2
2559 for (unsigned i = 0; i < 2; ++i) {
2560 SDOperand Arg = N->getOperand(i);
2561 if (Arg.getOpcode() == ISD::UNDEF) continue;
2562 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2563 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2564 if (Val != 0) return false;
2568 for (unsigned i = 2; i < 4; ++i) {
2569 SDOperand Arg = N->getOperand(i);
2570 if (Arg.getOpcode() == ISD::UNDEF) continue;
2571 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2572 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2573 if (Val != 2) return false;
2577 // Don't use movshdup if it can be done with a shufps.
2581 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2582 /// specifies a identity operation on the LHS or RHS.
2583 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2584 unsigned NumElems = N->getNumOperands();
2585 for (unsigned i = 0; i < NumElems; ++i)
2586 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2591 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2592 /// a splat of a single element.
2593 static bool isSplatMask(SDNode *N) {
2594 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2596 // This is a splat operation if each element of the permute is the same, and
2597 // if the value doesn't reference the second vector.
2598 unsigned NumElems = N->getNumOperands();
2599 SDOperand ElementBase;
2601 for (; i != NumElems; ++i) {
2602 SDOperand Elt = N->getOperand(i);
2603 if (isa<ConstantSDNode>(Elt)) {
2609 if (!ElementBase.Val)
2612 for (; i != NumElems; ++i) {
2613 SDOperand Arg = N->getOperand(i);
2614 if (Arg.getOpcode() == ISD::UNDEF) continue;
2615 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2616 if (Arg != ElementBase) return false;
2619 // Make sure it is a splat of the first vector operand.
2620 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2623 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2624 /// a splat of a single element and it's a 2 or 4 element mask.
2625 bool X86::isSplatMask(SDNode *N) {
2626 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2628 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2629 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2631 return ::isSplatMask(N);
2634 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2635 /// specifies a splat of zero element.
2636 bool X86::isSplatLoMask(SDNode *N) {
2637 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2639 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2640 if (!isUndefOrEqual(N->getOperand(i), 0))
2645 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2646 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2648 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2649 unsigned NumOperands = N->getNumOperands();
2650 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2652 for (unsigned i = 0; i < NumOperands; ++i) {
2654 SDOperand Arg = N->getOperand(NumOperands-i-1);
2655 if (Arg.getOpcode() != ISD::UNDEF)
2656 Val = cast<ConstantSDNode>(Arg)->getValue();
2657 if (Val >= NumOperands) Val -= NumOperands;
2659 if (i != NumOperands - 1)
2666 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2667 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2669 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2671 // 8 nodes, but we only care about the last 4.
2672 for (unsigned i = 7; i >= 4; --i) {
2674 SDOperand Arg = N->getOperand(i);
2675 if (Arg.getOpcode() != ISD::UNDEF)
2676 Val = cast<ConstantSDNode>(Arg)->getValue();
2685 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2686 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2688 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2690 // 8 nodes, but we only care about the first 4.
2691 for (int i = 3; i >= 0; --i) {
2693 SDOperand Arg = N->getOperand(i);
2694 if (Arg.getOpcode() != ISD::UNDEF)
2695 Val = cast<ConstantSDNode>(Arg)->getValue();
2704 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2705 /// specifies a 8 element shuffle that can be broken into a pair of
2706 /// PSHUFHW and PSHUFLW.
2707 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2708 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2710 if (N->getNumOperands() != 8)
2713 // Lower quadword shuffled.
2714 for (unsigned i = 0; i != 4; ++i) {
2715 SDOperand Arg = N->getOperand(i);
2716 if (Arg.getOpcode() == ISD::UNDEF) continue;
2717 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2718 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2723 // Upper quadword shuffled.
2724 for (unsigned i = 4; i != 8; ++i) {
2725 SDOperand Arg = N->getOperand(i);
2726 if (Arg.getOpcode() == ISD::UNDEF) continue;
2727 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2728 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2729 if (Val < 4 || Val > 7)
2736 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2737 /// values in ther permute mask.
2738 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2739 SDOperand &V2, SDOperand &Mask,
2740 SelectionDAG &DAG) {
2741 MVT::ValueType VT = Op.getValueType();
2742 MVT::ValueType MaskVT = Mask.getValueType();
2743 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2744 unsigned NumElems = Mask.getNumOperands();
2745 SmallVector<SDOperand, 8> MaskVec;
2747 for (unsigned i = 0; i != NumElems; ++i) {
2748 SDOperand Arg = Mask.getOperand(i);
2749 if (Arg.getOpcode() == ISD::UNDEF) {
2750 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2753 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2754 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2756 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2758 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2762 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2763 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2766 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2767 /// the two vector operands have swapped position.
2769 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2770 MVT::ValueType MaskVT = Mask.getValueType();
2771 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2772 unsigned NumElems = Mask.getNumOperands();
2773 SmallVector<SDOperand, 8> MaskVec;
2774 for (unsigned i = 0; i != NumElems; ++i) {
2775 SDOperand Arg = Mask.getOperand(i);
2776 if (Arg.getOpcode() == ISD::UNDEF) {
2777 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2780 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2781 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2783 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2785 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2787 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2791 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2792 /// match movhlps. The lower half elements should come from upper half of
2793 /// V1 (and in order), and the upper half elements should come from the upper
2794 /// half of V2 (and in order).
2795 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2796 unsigned NumElems = Mask->getNumOperands();
2799 for (unsigned i = 0, e = 2; i != e; ++i)
2800 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2802 for (unsigned i = 2; i != 4; ++i)
2803 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2808 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2809 /// is promoted to a vector.
2810 static inline bool isScalarLoadToVector(SDNode *N) {
2811 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2812 N = N->getOperand(0).Val;
2813 return ISD::isNON_EXTLoad(N);
2818 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2819 /// match movlp{s|d}. The lower half elements should come from lower half of
2820 /// V1 (and in order), and the upper half elements should come from the upper
2821 /// half of V2 (and in order). And since V1 will become the source of the
2822 /// MOVLP, it must be either a vector load or a scalar load to vector.
2823 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2824 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2826 // Is V2 is a vector load, don't do this transformation. We will try to use
2827 // load folding shufps op.
2828 if (ISD::isNON_EXTLoad(V2))
2831 unsigned NumElems = Mask->getNumOperands();
2832 if (NumElems != 2 && NumElems != 4)
2834 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2835 if (!isUndefOrEqual(Mask->getOperand(i), i))
2837 for (unsigned i = NumElems/2; i != NumElems; ++i)
2838 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2843 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2845 static bool isSplatVector(SDNode *N) {
2846 if (N->getOpcode() != ISD::BUILD_VECTOR)
2849 SDOperand SplatValue = N->getOperand(0);
2850 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2851 if (N->getOperand(i) != SplatValue)
2856 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2858 static bool isUndefShuffle(SDNode *N) {
2859 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2862 SDOperand V1 = N->getOperand(0);
2863 SDOperand V2 = N->getOperand(1);
2864 SDOperand Mask = N->getOperand(2);
2865 unsigned NumElems = Mask.getNumOperands();
2866 for (unsigned i = 0; i != NumElems; ++i) {
2867 SDOperand Arg = Mask.getOperand(i);
2868 if (Arg.getOpcode() != ISD::UNDEF) {
2869 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2870 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2872 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2879 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2881 static inline bool isZeroNode(SDOperand Elt) {
2882 return ((isa<ConstantSDNode>(Elt) &&
2883 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2884 (isa<ConstantFPSDNode>(Elt) &&
2885 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2888 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2889 /// to an zero vector.
2890 static bool isZeroShuffle(SDNode *N) {
2891 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2894 SDOperand V1 = N->getOperand(0);
2895 SDOperand V2 = N->getOperand(1);
2896 SDOperand Mask = N->getOperand(2);
2897 unsigned NumElems = Mask.getNumOperands();
2898 for (unsigned i = 0; i != NumElems; ++i) {
2899 SDOperand Arg = Mask.getOperand(i);
2900 if (Arg.getOpcode() == ISD::UNDEF)
2903 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2904 if (Idx < NumElems) {
2905 unsigned Opc = V1.Val->getOpcode();
2906 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2908 if (Opc != ISD::BUILD_VECTOR ||
2909 !isZeroNode(V1.Val->getOperand(Idx)))
2911 } else if (Idx >= NumElems) {
2912 unsigned Opc = V2.Val->getOpcode();
2913 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2915 if (Opc != ISD::BUILD_VECTOR ||
2916 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2923 /// getZeroVector - Returns a vector of specified type with all zero elements.
2925 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2926 assert(MVT::isVector(VT) && "Expected a vector type");
2928 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2929 // type. This ensures they get CSE'd.
2930 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2932 if (MVT::getSizeInBits(VT) == 64) // MMX
2933 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2935 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2936 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2939 /// getOnesVector - Returns a vector of specified type with all bits set.
2941 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2942 assert(MVT::isVector(VT) && "Expected a vector type");
2944 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2945 // type. This ensures they get CSE'd.
2946 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2948 if (MVT::getSizeInBits(VT) == 64) // MMX
2949 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2951 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2952 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2956 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2957 /// that point to V2 points to its first element.
2958 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2959 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2961 bool Changed = false;
2962 SmallVector<SDOperand, 8> MaskVec;
2963 unsigned NumElems = Mask.getNumOperands();
2964 for (unsigned i = 0; i != NumElems; ++i) {
2965 SDOperand Arg = Mask.getOperand(i);
2966 if (Arg.getOpcode() != ISD::UNDEF) {
2967 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2968 if (Val > NumElems) {
2969 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2973 MaskVec.push_back(Arg);
2977 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2978 &MaskVec[0], MaskVec.size());
2982 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2983 /// operation of specified width.
2984 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2985 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2986 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2988 SmallVector<SDOperand, 8> MaskVec;
2989 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2990 for (unsigned i = 1; i != NumElems; ++i)
2991 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2992 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2995 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2996 /// of specified width.
2997 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2998 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2999 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3000 SmallVector<SDOperand, 8> MaskVec;
3001 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3002 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3003 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
3005 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3008 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3009 /// of specified width.
3010 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
3011 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3012 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3013 unsigned Half = NumElems/2;
3014 SmallVector<SDOperand, 8> MaskVec;
3015 for (unsigned i = 0; i != Half; ++i) {
3016 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3017 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3019 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3022 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
3024 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
3025 SDOperand V1 = Op.getOperand(0);
3026 SDOperand Mask = Op.getOperand(2);
3027 MVT::ValueType VT = Op.getValueType();
3028 unsigned NumElems = Mask.getNumOperands();
3029 Mask = getUnpacklMask(NumElems, DAG);
3030 while (NumElems != 4) {
3031 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
3034 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
3036 Mask = getZeroVector(MVT::v4i32, DAG);
3037 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
3038 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
3039 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3042 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3043 /// vector of zero or undef vector. This produces a shuffle where the low
3044 /// element of V2 is swizzled into the zero/undef vector, landing at element
3045 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3046 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
3047 unsigned NumElems, unsigned Idx,
3048 bool isZero, SelectionDAG &DAG) {
3049 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
3050 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3051 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3052 SmallVector<SDOperand, 16> MaskVec;
3053 for (unsigned i = 0; i != NumElems; ++i)
3054 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3055 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3057 MaskVec.push_back(DAG.getConstant(i, EVT));
3058 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3059 &MaskVec[0], MaskVec.size());
3060 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3063 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3065 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
3066 unsigned NumNonZero, unsigned NumZero,
3067 SelectionDAG &DAG, TargetLowering &TLI) {
3073 for (unsigned i = 0; i < 16; ++i) {
3074 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3075 if (ThisIsNonZero && First) {
3077 V = getZeroVector(MVT::v8i16, DAG);
3079 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3084 SDOperand ThisElt(0, 0), LastElt(0, 0);
3085 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3086 if (LastIsNonZero) {
3087 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3089 if (ThisIsNonZero) {
3090 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3091 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3092 ThisElt, DAG.getConstant(8, MVT::i8));
3094 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3099 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3100 DAG.getConstant(i/2, TLI.getPointerTy()));
3104 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3107 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3109 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3110 unsigned NumNonZero, unsigned NumZero,
3111 SelectionDAG &DAG, TargetLowering &TLI) {
3117 for (unsigned i = 0; i < 8; ++i) {
3118 bool isNonZero = (NonZeros & (1 << i)) != 0;
3122 V = getZeroVector(MVT::v8i16, DAG);
3124 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3127 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3128 DAG.getConstant(i, TLI.getPointerTy()));
3135 /// is4WideVector - Returns true if the specific v8i16 or v16i8 vector is
3136 /// actually just a 4 wide vector. e.g. <a, a, y, y, d, d, x, x>
3138 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3139 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3140 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3141 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3142 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3143 // eliminated on x86-32 hosts.
3144 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3147 if (ISD::isBuildVectorAllOnes(Op.Val))
3148 return getOnesVector(Op.getValueType(), DAG);
3149 return getZeroVector(Op.getValueType(), DAG);
3152 MVT::ValueType VT = Op.getValueType();
3153 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3154 unsigned EVTBits = MVT::getSizeInBits(EVT);
3156 unsigned NumElems = Op.getNumOperands();
3157 unsigned NumZero = 0;
3158 unsigned NumNonZero = 0;
3159 unsigned NonZeros = 0;
3160 bool HasNonImms = false;
3161 SmallSet<SDOperand, 8> Values;
3162 for (unsigned i = 0; i < NumElems; ++i) {
3163 SDOperand Elt = Op.getOperand(i);
3164 if (Elt.getOpcode() == ISD::UNDEF)
3167 if (Elt.getOpcode() != ISD::Constant &&
3168 Elt.getOpcode() != ISD::ConstantFP)
3170 if (isZeroNode(Elt))
3173 NonZeros |= (1 << i);
3178 if (NumNonZero == 0) {
3179 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3180 return DAG.getNode(ISD::UNDEF, VT);
3183 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3184 if (Values.size() == 1)
3187 // Special case for single non-zero element.
3188 if (NumNonZero == 1 && NumElems <= 4) {
3189 unsigned Idx = CountTrailingZeros_32(NonZeros);
3190 SDOperand Item = Op.getOperand(Idx);
3191 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3193 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3194 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
3196 else if (!HasNonImms) // Otherwise, it's better to do a constpool load.
3199 if (EVTBits == 32) {
3200 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3201 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
3203 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3204 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3205 SmallVector<SDOperand, 8> MaskVec;
3206 for (unsigned i = 0; i < NumElems; i++)
3207 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3208 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3209 &MaskVec[0], MaskVec.size());
3210 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3211 DAG.getNode(ISD::UNDEF, VT), Mask);
3215 // A vector full of immediates; various special cases are already
3216 // handled, so this is best done with a single constant-pool load.
3220 // Let legalizer expand 2-wide build_vectors.
3224 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3225 if (EVTBits == 8 && NumElems == 16) {
3226 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3228 if (V.Val) return V;
3231 if (EVTBits == 16 && NumElems == 8) {
3232 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3234 if (V.Val) return V;
3237 // If element VT is == 32 bits, turn it into a number of shuffles.
3238 SmallVector<SDOperand, 8> V;
3240 if (NumElems == 4 && NumZero > 0) {
3241 for (unsigned i = 0; i < 4; ++i) {
3242 bool isZero = !(NonZeros & (1 << i));
3244 V[i] = getZeroVector(VT, DAG);
3246 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3249 for (unsigned i = 0; i < 2; ++i) {
3250 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3253 V[i] = V[i*2]; // Must be a zero vector.
3256 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3257 getMOVLMask(NumElems, DAG));
3260 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3261 getMOVLMask(NumElems, DAG));
3264 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3265 getUnpacklMask(NumElems, DAG));
3270 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3271 // clears the upper bits.
3272 // FIXME: we can do the same for v4f32 case when we know both parts of
3273 // the lower half come from scalar_to_vector (loadf32). We should do
3274 // that in post legalizer dag combiner with target specific hooks.
3275 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3277 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3278 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3279 SmallVector<SDOperand, 8> MaskVec;
3280 bool Reverse = (NonZeros & 0x3) == 2;
3281 for (unsigned i = 0; i < 2; ++i)
3283 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3285 MaskVec.push_back(DAG.getConstant(i, EVT));
3286 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3287 for (unsigned i = 0; i < 2; ++i)
3289 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3291 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3292 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3293 &MaskVec[0], MaskVec.size());
3294 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3297 if (Values.size() > 2) {
3298 // Expand into a number of unpckl*.
3300 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3301 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3302 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3303 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3304 for (unsigned i = 0; i < NumElems; ++i)
3305 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3307 while (NumElems != 0) {
3308 for (unsigned i = 0; i < NumElems; ++i)
3309 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3320 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3321 SDOperand PermMask, SelectionDAG &DAG,
3322 TargetLowering &TLI) {
3324 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3325 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3326 MVT::ValueType PtrVT = TLI.getPointerTy();
3327 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3328 PermMask.Val->op_end());
3330 // First record which half of which vector the low elements come from.
3331 SmallVector<unsigned, 4> LowQuad(4);
3332 for (unsigned i = 0; i < 4; ++i) {
3333 SDOperand Elt = MaskElts[i];
3334 if (Elt.getOpcode() == ISD::UNDEF)
3336 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3337 int QuadIdx = EltIdx / 4;
3340 int BestLowQuad = -1;
3341 unsigned MaxQuad = 1;
3342 for (unsigned i = 0; i < 4; ++i) {
3343 if (LowQuad[i] > MaxQuad) {
3345 MaxQuad = LowQuad[i];
3349 // Record which half of which vector the high elements come from.
3350 SmallVector<unsigned, 4> HighQuad(4);
3351 for (unsigned i = 4; i < 8; ++i) {
3352 SDOperand Elt = MaskElts[i];
3353 if (Elt.getOpcode() == ISD::UNDEF)
3355 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3356 int QuadIdx = EltIdx / 4;
3357 ++HighQuad[QuadIdx];
3359 int BestHighQuad = -1;
3361 for (unsigned i = 0; i < 4; ++i) {
3362 if (HighQuad[i] > MaxQuad) {
3364 MaxQuad = HighQuad[i];
3368 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3369 if (BestLowQuad != -1 || BestHighQuad != -1) {
3370 // First sort the 4 chunks in order using shufpd.
3371 SmallVector<SDOperand, 8> MaskVec;
3372 if (BestLowQuad != -1)
3373 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3375 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3376 if (BestHighQuad != -1)
3377 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3379 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3380 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3381 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3382 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3383 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3384 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3386 // Now sort high and low parts separately.
3387 BitVector InOrder(8);
3388 if (BestLowQuad != -1) {
3389 // Sort lower half in order using PSHUFLW.
3391 bool AnyOutOrder = false;
3392 for (unsigned i = 0; i != 4; ++i) {
3393 SDOperand Elt = MaskElts[i];
3394 if (Elt.getOpcode() == ISD::UNDEF) {
3395 MaskVec.push_back(Elt);
3398 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3401 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3402 // If this element is in the right place after this shuffle, then
3404 if ((int)(EltIdx / 4) == BestLowQuad)
3409 for (unsigned i = 4; i != 8; ++i)
3410 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3411 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3412 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3416 if (BestHighQuad != -1) {
3417 // Sort high half in order using PSHUFHW if possible.
3419 for (unsigned i = 0; i != 4; ++i)
3420 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3421 bool AnyOutOrder = false;
3422 for (unsigned i = 4; i != 8; ++i) {
3423 SDOperand Elt = MaskElts[i];
3424 if (Elt.getOpcode() == ISD::UNDEF) {
3425 MaskVec.push_back(Elt);
3428 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3431 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3432 // If this element is in the right place after this shuffle, then
3434 if ((int)(EltIdx / 4) == BestHighQuad)
3439 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3440 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3444 // The other elements are put in the right place using pextrw and pinsrw.
3445 for (unsigned i = 0; i != 8; ++i) {
3448 SDOperand Elt = MaskElts[i];
3449 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3452 SDOperand ExtOp = (EltIdx < 8)
3453 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3454 DAG.getConstant(EltIdx, PtrVT))
3455 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3456 DAG.getConstant(EltIdx - 8, PtrVT));
3457 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3458 DAG.getConstant(i, PtrVT));
3463 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3464 ///as few as possible.
3465 // First, let's find out how many elements are already in the right order.
3466 unsigned V1InOrder = 0;
3467 unsigned V1FromV1 = 0;
3468 unsigned V2InOrder = 0;
3469 unsigned V2FromV2 = 0;
3470 SmallVector<SDOperand, 8> V1Elts;
3471 SmallVector<SDOperand, 8> V2Elts;
3472 for (unsigned i = 0; i < 8; ++i) {
3473 SDOperand Elt = MaskElts[i];
3474 if (Elt.getOpcode() == ISD::UNDEF) {
3475 V1Elts.push_back(Elt);
3476 V2Elts.push_back(Elt);
3481 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3483 V1Elts.push_back(Elt);
3484 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3486 } else if (EltIdx == i+8) {
3487 V1Elts.push_back(Elt);
3488 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3490 } else if (EltIdx < 8) {
3491 V1Elts.push_back(Elt);
3494 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3499 if (V2InOrder > V1InOrder) {
3500 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3502 std::swap(V1Elts, V2Elts);
3503 std::swap(V1FromV1, V2FromV2);
3506 if ((V1FromV1 + V1InOrder) != 8) {
3507 // Some elements are from V2.
3509 // If there are elements that are from V1 but out of place,
3510 // then first sort them in place
3511 SmallVector<SDOperand, 8> MaskVec;
3512 for (unsigned i = 0; i < 8; ++i) {
3513 SDOperand Elt = V1Elts[i];
3514 if (Elt.getOpcode() == ISD::UNDEF) {
3515 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3518 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3520 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3522 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3524 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3525 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3529 for (unsigned i = 0; i < 8; ++i) {
3530 SDOperand Elt = V1Elts[i];
3531 if (Elt.getOpcode() == ISD::UNDEF)
3533 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3536 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3537 DAG.getConstant(EltIdx - 8, PtrVT));
3538 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3539 DAG.getConstant(i, PtrVT));
3543 // All elements are from V1.
3545 for (unsigned i = 0; i < 8; ++i) {
3546 SDOperand Elt = V1Elts[i];
3547 if (Elt.getOpcode() == ISD::UNDEF)
3549 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3550 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3551 DAG.getConstant(EltIdx, PtrVT));
3552 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3553 DAG.getConstant(i, PtrVT));
3559 /// RewriteAs4WideShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3560 /// ones if possible. This can be done when every pair / quad of shuffle mask
3561 /// elements point to elements in the right sequence. e.g.
3562 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3564 SDOperand RewriteAs4WideShuffle(SDOperand V1, SDOperand V2,
3565 SDOperand PermMask, SelectionDAG &DAG,
3566 TargetLowering &TLI) {
3567 unsigned NumElems = PermMask.getNumOperands();
3568 unsigned Scale = NumElems / 4;
3569 SmallVector<SDOperand, 4> MaskVec;
3570 for (unsigned i = 0; i < NumElems; i += Scale) {
3571 unsigned StartIdx = ~0U;
3572 for (unsigned j = 0; j < Scale; ++j) {
3573 SDOperand Elt = PermMask.getOperand(i+j);
3574 if (Elt.getOpcode() == ISD::UNDEF)
3576 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3577 if (StartIdx == ~0U)
3578 StartIdx = EltIdx - (EltIdx % Scale);
3579 if (EltIdx != StartIdx + j)
3582 if (StartIdx == ~0U)
3583 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3585 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3588 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
3589 V2 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V2);
3590 return DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1, V2,
3591 DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, &MaskVec[0],4));
3595 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3596 SDOperand V1 = Op.getOperand(0);
3597 SDOperand V2 = Op.getOperand(1);
3598 SDOperand PermMask = Op.getOperand(2);
3599 MVT::ValueType VT = Op.getValueType();
3600 unsigned NumElems = PermMask.getNumOperands();
3601 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3602 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3603 bool V1IsSplat = false;
3604 bool V2IsSplat = false;
3606 if (isUndefShuffle(Op.Val))
3607 return DAG.getNode(ISD::UNDEF, VT);
3609 if (isZeroShuffle(Op.Val))
3610 return getZeroVector(VT, DAG);
3612 if (isIdentityMask(PermMask.Val))
3614 else if (isIdentityMask(PermMask.Val, true))
3617 if (isSplatMask(PermMask.Val)) {
3618 if (NumElems <= 4) return Op;
3619 // Promote it to a v4i32 splat.
3620 return PromoteSplat(Op, DAG);
3623 if (X86::isMOVLMask(PermMask.Val))
3624 return (V1IsUndef) ? V2 : Op;
3626 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3627 X86::isMOVSLDUPMask(PermMask.Val) ||
3628 X86::isMOVHLPSMask(PermMask.Val) ||
3629 X86::isMOVHPMask(PermMask.Val) ||
3630 X86::isMOVLPMask(PermMask.Val))
3633 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3634 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3635 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3637 bool Commuted = false;
3638 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3639 // 1,1,1,1 -> v8i16 though.
3640 V1IsSplat = isSplatVector(V1.Val);
3641 V2IsSplat = isSplatVector(V2.Val);
3643 // Canonicalize the splat or undef, if present, to be on the RHS.
3644 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3645 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3646 std::swap(V1IsSplat, V2IsSplat);
3647 std::swap(V1IsUndef, V2IsUndef);
3651 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3652 if (V2IsUndef) return V1;
3653 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3655 // V2 is a splat, so the mask may be malformed. That is, it may point
3656 // to any V2 element. The instruction selectior won't like this. Get
3657 // a corrected mask and commute to form a proper MOVS{S|D}.
3658 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3659 if (NewMask.Val != PermMask.Val)
3660 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3665 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3666 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3667 X86::isUNPCKLMask(PermMask.Val) ||
3668 X86::isUNPCKHMask(PermMask.Val))
3672 // Normalize mask so all entries that point to V2 points to its first
3673 // element then try to match unpck{h|l} again. If match, return a
3674 // new vector_shuffle with the corrected mask.
3675 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3676 if (NewMask.Val != PermMask.Val) {
3677 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3678 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3679 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3680 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3681 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3682 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3687 // Normalize the node to match x86 shuffle ops if needed
3688 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3689 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3692 // Commute is back and try unpck* again.
3693 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3694 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3695 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3696 X86::isUNPCKLMask(PermMask.Val) ||
3697 X86::isUNPCKHMask(PermMask.Val))
3701 // If VT is integer, try PSHUF* first, then SHUFP*.
3702 if (MVT::isInteger(VT)) {
3703 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3704 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3705 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3706 X86::isPSHUFDMask(PermMask.Val)) ||
3707 X86::isPSHUFHWMask(PermMask.Val) ||
3708 X86::isPSHUFLWMask(PermMask.Val)) {
3709 if (V2.getOpcode() != ISD::UNDEF)
3710 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3711 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3715 if (X86::isSHUFPMask(PermMask.Val) &&
3716 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3719 // Floating point cases in the other order.
3720 if (X86::isSHUFPMask(PermMask.Val))
3722 if (X86::isPSHUFDMask(PermMask.Val) ||
3723 X86::isPSHUFHWMask(PermMask.Val) ||
3724 X86::isPSHUFLWMask(PermMask.Val)) {
3725 if (V2.getOpcode() != ISD::UNDEF)
3726 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3727 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3732 // If the shuffle can be rewritten as a 4 wide shuffle, then do it!
3733 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3734 SDOperand NewOp = RewriteAs4WideShuffle(V1, V2, PermMask, DAG, *this);
3736 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3739 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3740 if (VT == MVT::v8i16) {
3741 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3746 // Handle all 4 wide cases with a number of shuffles.
3747 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3748 // Don't do this for MMX.
3749 MVT::ValueType MaskVT = PermMask.getValueType();
3750 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3751 SmallVector<std::pair<int, int>, 8> Locs;
3752 Locs.reserve(NumElems);
3753 SmallVector<SDOperand, 8> Mask1(NumElems,
3754 DAG.getNode(ISD::UNDEF, MaskEVT));
3755 SmallVector<SDOperand, 8> Mask2(NumElems,
3756 DAG.getNode(ISD::UNDEF, MaskEVT));
3759 // If no more than two elements come from either vector. This can be
3760 // implemented with two shuffles. First shuffle gather the elements.
3761 // The second shuffle, which takes the first shuffle as both of its
3762 // vector operands, put the elements into the right order.
3763 for (unsigned i = 0; i != NumElems; ++i) {
3764 SDOperand Elt = PermMask.getOperand(i);
3765 if (Elt.getOpcode() == ISD::UNDEF) {
3766 Locs[i] = std::make_pair(-1, -1);
3768 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3769 if (Val < NumElems) {
3770 Locs[i] = std::make_pair(0, NumLo);
3774 Locs[i] = std::make_pair(1, NumHi);
3775 if (2+NumHi < NumElems)
3776 Mask1[2+NumHi] = Elt;
3781 if (NumLo <= 2 && NumHi <= 2) {
3782 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3783 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3784 &Mask1[0], Mask1.size()));
3785 for (unsigned i = 0; i != NumElems; ++i) {
3786 if (Locs[i].first == -1)
3789 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3790 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3791 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3795 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3796 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3797 &Mask2[0], Mask2.size()));
3800 // Break it into (shuffle shuffle_hi, shuffle_lo).
3802 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3803 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3804 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3805 unsigned MaskIdx = 0;
3807 unsigned HiIdx = NumElems/2;
3808 for (unsigned i = 0; i != NumElems; ++i) {
3809 if (i == NumElems/2) {
3815 SDOperand Elt = PermMask.getOperand(i);
3816 if (Elt.getOpcode() == ISD::UNDEF) {
3817 Locs[i] = std::make_pair(-1, -1);
3818 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3819 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3820 (*MaskPtr)[LoIdx] = Elt;
3823 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3824 (*MaskPtr)[HiIdx] = Elt;
3829 SDOperand LoShuffle =
3830 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3831 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3832 &LoMask[0], LoMask.size()));
3833 SDOperand HiShuffle =
3834 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3835 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3836 &HiMask[0], HiMask.size()));
3837 SmallVector<SDOperand, 8> MaskOps;
3838 for (unsigned i = 0; i != NumElems; ++i) {
3839 if (Locs[i].first == -1) {
3840 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3842 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3843 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3846 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3847 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3848 &MaskOps[0], MaskOps.size()));
3855 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3856 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3859 MVT::ValueType VT = Op.getValueType();
3860 // TODO: handle v16i8.
3861 if (MVT::getSizeInBits(VT) == 16) {
3862 SDOperand Vec = Op.getOperand(0);
3863 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3865 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3866 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3867 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3869 // Transform it so it match pextrw which produces a 32-bit result.
3870 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3871 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3872 Op.getOperand(0), Op.getOperand(1));
3873 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3874 DAG.getValueType(VT));
3875 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3876 } else if (MVT::getSizeInBits(VT) == 32) {
3877 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3880 // SHUFPS the element to the lowest double word, then movss.
3881 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3882 SmallVector<SDOperand, 8> IdxVec;
3884 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3886 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3888 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3890 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3891 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3892 &IdxVec[0], IdxVec.size());
3893 SDOperand Vec = Op.getOperand(0);
3894 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3895 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3896 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3897 DAG.getConstant(0, getPointerTy()));
3898 } else if (MVT::getSizeInBits(VT) == 64) {
3899 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3903 // UNPCKHPD the element to the lowest double word, then movsd.
3904 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3905 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3906 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3907 SmallVector<SDOperand, 8> IdxVec;
3908 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3910 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3911 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3912 &IdxVec[0], IdxVec.size());
3913 SDOperand Vec = Op.getOperand(0);
3914 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3915 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3916 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3917 DAG.getConstant(0, getPointerTy()));
3924 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3925 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3926 // as its second argument.
3927 MVT::ValueType VT = Op.getValueType();
3928 MVT::ValueType BaseVT = MVT::getVectorElementType(VT);
3929 SDOperand N0 = Op.getOperand(0);
3930 SDOperand N1 = Op.getOperand(1);
3931 SDOperand N2 = Op.getOperand(2);
3932 if (MVT::getSizeInBits(BaseVT) == 16) {
3933 if (N1.getValueType() != MVT::i32)
3934 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3935 if (N2.getValueType() != MVT::i32)
3936 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
3937 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3938 } else if (MVT::getSizeInBits(BaseVT) == 32) {
3939 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
3942 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
3943 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3944 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3945 SmallVector<SDOperand, 8> MaskVec;
3946 MaskVec.push_back(DAG.getConstant(4, BaseVT));
3947 for (unsigned i = 1; i <= 3; ++i)
3948 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3949 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
3950 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3951 &MaskVec[0], MaskVec.size()));
3953 // Use two pinsrw instructions to insert a 32 bit value.
3955 if (MVT::isFloatingPoint(N1.getValueType())) {
3956 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
3957 N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
3958 N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
3959 DAG.getConstant(0, getPointerTy()));
3961 N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
3962 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3963 DAG.getConstant(Idx, getPointerTy()));
3964 N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
3965 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3966 DAG.getConstant(Idx+1, getPointerTy()));
3967 return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3975 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3976 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3977 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3980 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3981 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3982 // one of the above mentioned nodes. It has to be wrapped because otherwise
3983 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3984 // be used to form addressing mode. These wrapped nodes will be selected
3987 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3988 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3989 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3991 CP->getAlignment());
3992 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3993 // With PIC, the address is actually $g + Offset.
3994 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3995 !Subtarget->isPICStyleRIPRel()) {
3996 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3997 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4005 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4006 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4007 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4008 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4009 // With PIC, the address is actually $g + Offset.
4010 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4011 !Subtarget->isPICStyleRIPRel()) {
4012 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4013 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4017 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4018 // load the value at address GV, not the value of GV itself. This means that
4019 // the GlobalAddress must be in the base or index register of the address, not
4020 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4021 // The same applies for external symbols during PIC codegen
4022 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4023 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
4028 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
4030 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4031 const MVT::ValueType PtrVT) {
4033 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4034 DAG.getNode(X86ISD::GlobalBaseReg,
4036 InFlag = Chain.getValue(1);
4038 // emit leal symbol@TLSGD(,%ebx,1), %eax
4039 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4040 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4041 GA->getValueType(0),
4043 SDOperand Ops[] = { Chain, TGA, InFlag };
4044 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4045 InFlag = Result.getValue(2);
4046 Chain = Result.getValue(1);
4048 // call ___tls_get_addr. This function receives its argument in
4049 // the register EAX.
4050 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4051 InFlag = Chain.getValue(1);
4053 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4054 SDOperand Ops1[] = { Chain,
4055 DAG.getTargetExternalSymbol("___tls_get_addr",
4057 DAG.getRegister(X86::EAX, PtrVT),
4058 DAG.getRegister(X86::EBX, PtrVT),
4060 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4061 InFlag = Chain.getValue(1);
4063 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4066 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4067 // "local exec" model.
4069 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4070 const MVT::ValueType PtrVT) {
4071 // Get the Thread Pointer
4072 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4073 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4075 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4076 GA->getValueType(0),
4078 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4080 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4081 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
4083 // The address of the thread local variable is the add of the thread
4084 // pointer with the offset of the variable.
4085 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4089 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4090 // TODO: implement the "local dynamic" model
4091 // TODO: implement the "initial exec"model for pic executables
4092 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4093 "TLS not implemented for non-ELF and 64-bit targets");
4094 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4095 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4096 // otherwise use the "Local Exec"TLS Model
4097 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4098 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4100 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4104 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4105 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4106 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4107 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4108 // With PIC, the address is actually $g + Offset.
4109 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4110 !Subtarget->isPICStyleRIPRel()) {
4111 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4112 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4119 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4120 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4121 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4122 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4123 // With PIC, the address is actually $g + Offset.
4124 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4125 !Subtarget->isPICStyleRIPRel()) {
4126 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4127 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4134 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4135 /// take a 2 x i32 value to shift plus a shift amount.
4136 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4137 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
4138 "Not an i64 shift!");
4139 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4140 SDOperand ShOpLo = Op.getOperand(0);
4141 SDOperand ShOpHi = Op.getOperand(1);
4142 SDOperand ShAmt = Op.getOperand(2);
4143 SDOperand Tmp1 = isSRA ?
4144 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
4145 DAG.getConstant(0, MVT::i32);
4147 SDOperand Tmp2, Tmp3;
4148 if (Op.getOpcode() == ISD::SHL_PARTS) {
4149 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
4150 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
4152 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
4153 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
4156 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4157 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4158 DAG.getConstant(32, MVT::i8));
4159 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
4160 AndNode, DAG.getConstant(0, MVT::i8));
4163 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4164 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
4165 SmallVector<SDOperand, 4> Ops;
4166 if (Op.getOpcode() == ISD::SHL_PARTS) {
4167 Ops.push_back(Tmp2);
4168 Ops.push_back(Tmp3);
4170 Ops.push_back(Cond);
4171 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4174 Ops.push_back(Tmp3);
4175 Ops.push_back(Tmp1);
4177 Ops.push_back(Cond);
4178 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4180 Ops.push_back(Tmp2);
4181 Ops.push_back(Tmp3);
4183 Ops.push_back(Cond);
4184 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4187 Ops.push_back(Tmp3);
4188 Ops.push_back(Tmp1);
4190 Ops.push_back(Cond);
4191 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4194 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
4198 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4201 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4202 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
4203 Op.getOperand(0).getValueType() >= MVT::i16 &&
4204 "Unknown SINT_TO_FP to lower!");
4207 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4208 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4209 MachineFunction &MF = DAG.getMachineFunction();
4210 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4211 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4212 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4213 StackSlot, NULL, 0);
4215 // These are really Legal; caller falls through into that case.
4216 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f32 && X86ScalarSSEf32)
4218 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f64 && X86ScalarSSEf64)
4220 if (SrcVT==MVT::i64 && Op.getValueType() != MVT::f80 &&
4221 Subtarget->is64Bit())
4226 bool useSSE = (X86ScalarSSEf32 && Op.getValueType() == MVT::f32) ||
4227 (X86ScalarSSEf64 && Op.getValueType() == MVT::f64);
4229 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4231 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4232 SmallVector<SDOperand, 8> Ops;
4233 Ops.push_back(Chain);
4234 Ops.push_back(StackSlot);
4235 Ops.push_back(DAG.getValueType(SrcVT));
4236 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
4237 Tys, &Ops[0], Ops.size());
4240 Chain = Result.getValue(1);
4241 SDOperand InFlag = Result.getValue(2);
4243 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4244 // shouldn't be necessary except that RFP cannot be live across
4245 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4246 MachineFunction &MF = DAG.getMachineFunction();
4247 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4248 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4249 Tys = DAG.getVTList(MVT::Other);
4250 SmallVector<SDOperand, 8> Ops;
4251 Ops.push_back(Chain);
4252 Ops.push_back(Result);
4253 Ops.push_back(StackSlot);
4254 Ops.push_back(DAG.getValueType(Op.getValueType()));
4255 Ops.push_back(InFlag);
4256 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4257 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
4263 std::pair<SDOperand,SDOperand> X86TargetLowering::
4264 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4265 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4266 "Unknown FP_TO_SINT to lower!");
4268 // These are really Legal.
4269 if (Op.getValueType() == MVT::i32 &&
4270 X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32)
4271 return std::make_pair(SDOperand(), SDOperand());
4272 if (Op.getValueType() == MVT::i32 &&
4273 X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)
4274 return std::make_pair(SDOperand(), SDOperand());
4275 if (Subtarget->is64Bit() &&
4276 Op.getValueType() == MVT::i64 &&
4277 Op.getOperand(0).getValueType() != MVT::f80)
4278 return std::make_pair(SDOperand(), SDOperand());
4280 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4282 MachineFunction &MF = DAG.getMachineFunction();
4283 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4284 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4285 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4287 switch (Op.getValueType()) {
4288 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4289 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4290 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4291 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4294 SDOperand Chain = DAG.getEntryNode();
4295 SDOperand Value = Op.getOperand(0);
4296 if ((X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32) ||
4297 (X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)) {
4298 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4299 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
4300 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4302 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4304 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4305 Chain = Value.getValue(1);
4306 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4307 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4310 // Build the FP_TO_INT*_IN_MEM
4311 SDOperand Ops[] = { Chain, Value, StackSlot };
4312 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4314 return std::make_pair(FIST, StackSlot);
4317 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4318 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4319 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4320 if (FIST.Val == 0) return SDOperand();
4323 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4326 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4327 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4328 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4329 if (FIST.Val == 0) return 0;
4331 // Return an i64 load from the stack slot.
4332 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4334 // Use a MERGE_VALUES node to drop the chain result value.
4335 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4338 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4339 MVT::ValueType VT = Op.getValueType();
4340 MVT::ValueType EltVT = VT;
4341 if (MVT::isVector(VT))
4342 EltVT = MVT::getVectorElementType(VT);
4343 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4344 std::vector<Constant*> CV;
4345 if (EltVT == MVT::f64) {
4346 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4350 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4356 Constant *C = ConstantVector::get(CV);
4357 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4358 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4360 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4363 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4364 MVT::ValueType VT = Op.getValueType();
4365 MVT::ValueType EltVT = VT;
4366 unsigned EltNum = 1;
4367 if (MVT::isVector(VT)) {
4368 EltVT = MVT::getVectorElementType(VT);
4369 EltNum = MVT::getVectorNumElements(VT);
4371 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4372 std::vector<Constant*> CV;
4373 if (EltVT == MVT::f64) {
4374 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4378 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4384 Constant *C = ConstantVector::get(CV);
4385 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4386 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4388 if (MVT::isVector(VT)) {
4389 return DAG.getNode(ISD::BIT_CONVERT, VT,
4390 DAG.getNode(ISD::XOR, MVT::v2i64,
4391 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4392 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4394 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4398 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4399 SDOperand Op0 = Op.getOperand(0);
4400 SDOperand Op1 = Op.getOperand(1);
4401 MVT::ValueType VT = Op.getValueType();
4402 MVT::ValueType SrcVT = Op1.getValueType();
4403 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4405 // If second operand is smaller, extend it first.
4406 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4407 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4409 SrcTy = MVT::getTypeForValueType(SrcVT);
4411 // And if it is bigger, shrink it first.
4412 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4413 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1);
4415 SrcTy = MVT::getTypeForValueType(SrcVT);
4418 // At this point the operands and the result should have the same
4419 // type, and that won't be f80 since that is not custom lowered.
4421 // First get the sign bit of second operand.
4422 std::vector<Constant*> CV;
4423 if (SrcVT == MVT::f64) {
4424 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4425 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4427 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4428 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4429 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4430 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4432 Constant *C = ConstantVector::get(CV);
4433 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4434 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx, NULL, 0,
4436 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4438 // Shift sign bit right or left if the two operands have different types.
4439 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4440 // Op0 is MVT::f32, Op1 is MVT::f64.
4441 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4442 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4443 DAG.getConstant(32, MVT::i32));
4444 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4445 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4446 DAG.getConstant(0, getPointerTy()));
4449 // Clear first operand sign bit.
4451 if (VT == MVT::f64) {
4452 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4453 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4455 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4456 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4457 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4458 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4460 C = ConstantVector::get(CV);
4461 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4462 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4464 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4466 // Or the value with the sign bit.
4467 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4470 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4471 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4473 SDOperand Op0 = Op.getOperand(0);
4474 SDOperand Op1 = Op.getOperand(1);
4475 SDOperand CC = Op.getOperand(2);
4476 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4477 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4480 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4482 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4483 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4484 DAG.getConstant(X86CC, MVT::i8), Cond);
4487 assert(isFP && "Illegal integer SetCC!");
4489 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4490 switch (SetCCOpcode) {
4491 default: assert(false && "Illegal floating point SetCC!");
4492 case ISD::SETOEQ: { // !PF & ZF
4493 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4494 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4495 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4496 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4497 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4499 case ISD::SETUNE: { // PF | !ZF
4500 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4501 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4502 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4503 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4504 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4510 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4511 bool addTest = true;
4512 SDOperand Cond = Op.getOperand(0);
4515 if (Cond.getOpcode() == ISD::SETCC)
4516 Cond = LowerSETCC(Cond, DAG);
4518 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4519 // setting operand in place of the X86ISD::SETCC.
4520 if (Cond.getOpcode() == X86ISD::SETCC) {
4521 CC = Cond.getOperand(0);
4523 SDOperand Cmp = Cond.getOperand(1);
4524 unsigned Opc = Cmp.getOpcode();
4525 MVT::ValueType VT = Op.getValueType();
4526 bool IllegalFPCMov = false;
4527 if (VT == MVT::f32 && !X86ScalarSSEf32)
4528 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4529 else if (VT == MVT::f64 && !X86ScalarSSEf64)
4530 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4531 else if (VT == MVT::f80)
4532 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4533 if ((Opc == X86ISD::CMP ||
4534 Opc == X86ISD::COMI ||
4535 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4542 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4543 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4546 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4548 SmallVector<SDOperand, 4> Ops;
4549 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4550 // condition is true.
4551 Ops.push_back(Op.getOperand(2));
4552 Ops.push_back(Op.getOperand(1));
4554 Ops.push_back(Cond);
4555 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4558 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4559 bool addTest = true;
4560 SDOperand Chain = Op.getOperand(0);
4561 SDOperand Cond = Op.getOperand(1);
4562 SDOperand Dest = Op.getOperand(2);
4565 if (Cond.getOpcode() == ISD::SETCC)
4566 Cond = LowerSETCC(Cond, DAG);
4568 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4569 // setting operand in place of the X86ISD::SETCC.
4570 if (Cond.getOpcode() == X86ISD::SETCC) {
4571 CC = Cond.getOperand(0);
4573 SDOperand Cmp = Cond.getOperand(1);
4574 unsigned Opc = Cmp.getOpcode();
4575 if (Opc == X86ISD::CMP ||
4576 Opc == X86ISD::COMI ||
4577 Opc == X86ISD::UCOMI) {
4584 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4585 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4587 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4588 Chain, Op.getOperand(2), CC, Cond);
4591 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
4592 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4593 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
4595 if (Subtarget->is64Bit())
4596 if(CallingConv==CallingConv::Fast && isTailCall && PerformTailCallOpt)
4597 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4599 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
4601 switch (CallingConv) {
4603 assert(0 && "Unsupported calling convention");
4604 case CallingConv::Fast:
4605 if (isTailCall && PerformTailCallOpt)
4606 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4608 return LowerCCCCallTo(Op,DAG, CallingConv);
4609 case CallingConv::C:
4610 case CallingConv::X86_StdCall:
4611 return LowerCCCCallTo(Op, DAG, CallingConv);
4612 case CallingConv::X86_FastCall:
4613 return LowerFastCCCallTo(Op, DAG, CallingConv);
4618 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4619 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4620 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4621 // that the guard pages used by the OS virtual memory manager are allocated in
4622 // correct sequence.
4624 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4625 SelectionDAG &DAG) {
4626 assert(Subtarget->isTargetCygMing() &&
4627 "This should be used only on Cygwin/Mingw targets");
4630 SDOperand Chain = Op.getOperand(0);
4631 SDOperand Size = Op.getOperand(1);
4632 // FIXME: Ensure alignment here
4636 MVT::ValueType IntPtr = getPointerTy();
4637 MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
4639 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4640 Flag = Chain.getValue(1);
4642 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4643 SDOperand Ops[] = { Chain,
4644 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4645 DAG.getRegister(X86::EAX, IntPtr),
4647 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4648 Flag = Chain.getValue(1);
4650 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4652 std::vector<MVT::ValueType> Tys;
4653 Tys.push_back(SPTy);
4654 Tys.push_back(MVT::Other);
4655 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4656 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4660 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
4661 MachineFunction &MF = DAG.getMachineFunction();
4662 const Function* Fn = MF.getFunction();
4663 if (Fn->hasExternalLinkage() &&
4664 Subtarget->isTargetCygMing() &&
4665 Fn->getName() == "main")
4666 MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
4668 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4669 if (Subtarget->is64Bit())
4670 return LowerX86_64CCCArguments(Op, DAG);
4674 assert(0 && "Unsupported calling convention");
4675 case CallingConv::Fast:
4676 return LowerCCCArguments(Op,DAG, true);
4678 case CallingConv::C:
4679 return LowerCCCArguments(Op, DAG);
4680 case CallingConv::X86_StdCall:
4681 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
4682 return LowerCCCArguments(Op, DAG, true);
4683 case CallingConv::X86_FastCall:
4684 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
4685 return LowerFastCCArguments(Op, DAG);
4689 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4690 SDOperand InFlag(0, 0);
4691 SDOperand Chain = Op.getOperand(0);
4693 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4694 if (Align == 0) Align = 1;
4696 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4697 // If not DWORD aligned or size is more than the threshold, call memset.
4698 // The libc version is likely to be faster for these cases. It can use the
4699 // address value and run time information about the CPU.
4700 if ((Align & 3) != 0 ||
4701 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4702 MVT::ValueType IntPtr = getPointerTy();
4703 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4704 TargetLowering::ArgListTy Args;
4705 TargetLowering::ArgListEntry Entry;
4706 Entry.Node = Op.getOperand(1);
4707 Entry.Ty = IntPtrTy;
4708 Args.push_back(Entry);
4709 // Extend the unsigned i8 argument to be an int value for the call.
4710 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4711 Entry.Ty = IntPtrTy;
4712 Args.push_back(Entry);
4713 Entry.Node = Op.getOperand(3);
4714 Args.push_back(Entry);
4715 std::pair<SDOperand,SDOperand> CallResult =
4716 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4717 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4718 return CallResult.second;
4723 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4724 unsigned BytesLeft = 0;
4725 bool TwoRepStos = false;
4728 uint64_t Val = ValC->getValue() & 255;
4730 // If the value is a constant, then we can potentially use larger sets.
4731 switch (Align & 3) {
4732 case 2: // WORD aligned
4735 Val = (Val << 8) | Val;
4737 case 0: // DWORD aligned
4740 Val = (Val << 8) | Val;
4741 Val = (Val << 16) | Val;
4742 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4745 Val = (Val << 32) | Val;
4748 default: // Byte aligned
4751 Count = Op.getOperand(3);
4755 if (AVT > MVT::i8) {
4757 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4758 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
4759 BytesLeft = I->getValue() % UBytes;
4761 assert(AVT >= MVT::i32 &&
4762 "Do not use rep;stos if not at least DWORD aligned");
4763 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4764 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4769 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4771 InFlag = Chain.getValue(1);
4774 Count = Op.getOperand(3);
4775 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4776 InFlag = Chain.getValue(1);
4779 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4781 InFlag = Chain.getValue(1);
4782 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4783 Op.getOperand(1), InFlag);
4784 InFlag = Chain.getValue(1);
4786 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4787 SmallVector<SDOperand, 8> Ops;
4788 Ops.push_back(Chain);
4789 Ops.push_back(DAG.getValueType(AVT));
4790 Ops.push_back(InFlag);
4791 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4794 InFlag = Chain.getValue(1);
4795 Count = Op.getOperand(3);
4796 MVT::ValueType CVT = Count.getValueType();
4797 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4798 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4799 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4801 InFlag = Chain.getValue(1);
4802 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4804 Ops.push_back(Chain);
4805 Ops.push_back(DAG.getValueType(MVT::i8));
4806 Ops.push_back(InFlag);
4807 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4808 } else if (BytesLeft) {
4809 // Issue stores for the last 1 - 7 bytes.
4811 unsigned Val = ValC->getValue() & 255;
4812 unsigned Offset = I->getValue() - BytesLeft;
4813 SDOperand DstAddr = Op.getOperand(1);
4814 MVT::ValueType AddrVT = DstAddr.getValueType();
4815 if (BytesLeft >= 4) {
4816 Val = (Val << 8) | Val;
4817 Val = (Val << 16) | Val;
4818 Value = DAG.getConstant(Val, MVT::i32);
4819 Chain = DAG.getStore(Chain, Value,
4820 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4821 DAG.getConstant(Offset, AddrVT)),
4826 if (BytesLeft >= 2) {
4827 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4828 Chain = DAG.getStore(Chain, Value,
4829 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4830 DAG.getConstant(Offset, AddrVT)),
4835 if (BytesLeft == 1) {
4836 Value = DAG.getConstant(Val, MVT::i8);
4837 Chain = DAG.getStore(Chain, Value,
4838 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4839 DAG.getConstant(Offset, AddrVT)),
4847 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4852 SelectionDAG &DAG) {
4854 unsigned BytesLeft = 0;
4855 switch (Align & 3) {
4856 case 2: // WORD aligned
4859 case 0: // DWORD aligned
4861 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4864 default: // Byte aligned
4869 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4870 SDOperand Count = DAG.getConstant(Size / UBytes, getPointerTy());
4871 BytesLeft = Size % UBytes;
4873 SDOperand InFlag(0, 0);
4874 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4876 InFlag = Chain.getValue(1);
4877 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4879 InFlag = Chain.getValue(1);
4880 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4882 InFlag = Chain.getValue(1);
4884 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4885 SmallVector<SDOperand, 8> Ops;
4886 Ops.push_back(Chain);
4887 Ops.push_back(DAG.getValueType(AVT));
4888 Ops.push_back(InFlag);
4889 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4892 // Issue loads and stores for the last 1 - 7 bytes.
4893 unsigned Offset = Size - BytesLeft;
4894 SDOperand DstAddr = Dest;
4895 MVT::ValueType DstVT = DstAddr.getValueType();
4896 SDOperand SrcAddr = Source;
4897 MVT::ValueType SrcVT = SrcAddr.getValueType();
4899 if (BytesLeft >= 4) {
4900 Value = DAG.getLoad(MVT::i32, Chain,
4901 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4902 DAG.getConstant(Offset, SrcVT)),
4904 Chain = Value.getValue(1);
4905 Chain = DAG.getStore(Chain, Value,
4906 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4907 DAG.getConstant(Offset, DstVT)),
4912 if (BytesLeft >= 2) {
4913 Value = DAG.getLoad(MVT::i16, Chain,
4914 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4915 DAG.getConstant(Offset, SrcVT)),
4917 Chain = Value.getValue(1);
4918 Chain = DAG.getStore(Chain, Value,
4919 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4920 DAG.getConstant(Offset, DstVT)),
4926 if (BytesLeft == 1) {
4927 Value = DAG.getLoad(MVT::i8, Chain,
4928 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4929 DAG.getConstant(Offset, SrcVT)),
4931 Chain = Value.getValue(1);
4932 Chain = DAG.getStore(Chain, Value,
4933 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4934 DAG.getConstant(Offset, DstVT)),
4942 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4943 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4944 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4945 SDOperand TheChain = N->getOperand(0);
4946 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4947 if (Subtarget->is64Bit()) {
4948 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4949 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4950 MVT::i64, rax.getValue(2));
4951 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4952 DAG.getConstant(32, MVT::i8));
4954 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4957 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4958 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4961 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4962 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4963 MVT::i32, eax.getValue(2));
4964 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4965 SDOperand Ops[] = { eax, edx };
4966 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4968 // Use a MERGE_VALUES to return the value and chain.
4969 Ops[1] = edx.getValue(1);
4970 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4971 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4974 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4975 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
4977 if (!Subtarget->is64Bit()) {
4978 // vastart just stores the address of the VarArgsFrameIndex slot into the
4979 // memory location argument.
4980 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4981 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
4986 // gp_offset (0 - 6 * 8)
4987 // fp_offset (48 - 48 + 8 * 16)
4988 // overflow_arg_area (point to parameters coming in memory).
4990 SmallVector<SDOperand, 8> MemOps;
4991 SDOperand FIN = Op.getOperand(1);
4993 SDOperand Store = DAG.getStore(Op.getOperand(0),
4994 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4995 FIN, SV->getValue(), SV->getOffset());
4996 MemOps.push_back(Store);
4999 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5000 DAG.getConstant(4, getPointerTy()));
5001 Store = DAG.getStore(Op.getOperand(0),
5002 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5003 FIN, SV->getValue(), SV->getOffset());
5004 MemOps.push_back(Store);
5006 // Store ptr to overflow_arg_area
5007 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5008 DAG.getConstant(4, getPointerTy()));
5009 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5010 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
5012 MemOps.push_back(Store);
5014 // Store ptr to reg_save_area.
5015 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5016 DAG.getConstant(8, getPointerTy()));
5017 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5018 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
5020 MemOps.push_back(Store);
5021 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5024 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
5025 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5026 SDOperand Chain = Op.getOperand(0);
5027 SDOperand DstPtr = Op.getOperand(1);
5028 SDOperand SrcPtr = Op.getOperand(2);
5029 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
5030 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
5032 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
5033 SrcSV->getValue(), SrcSV->getOffset());
5034 Chain = SrcPtr.getValue(1);
5035 for (unsigned i = 0; i < 3; ++i) {
5036 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
5037 SrcSV->getValue(), SrcSV->getOffset());
5038 Chain = Val.getValue(1);
5039 Chain = DAG.getStore(Chain, Val, DstPtr,
5040 DstSV->getValue(), DstSV->getOffset());
5043 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
5044 DAG.getConstant(8, getPointerTy()));
5045 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
5046 DAG.getConstant(8, getPointerTy()));
5052 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5053 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5055 default: return SDOperand(); // Don't custom lower most intrinsics.
5056 // Comparison intrinsics.
5057 case Intrinsic::x86_sse_comieq_ss:
5058 case Intrinsic::x86_sse_comilt_ss:
5059 case Intrinsic::x86_sse_comile_ss:
5060 case Intrinsic::x86_sse_comigt_ss:
5061 case Intrinsic::x86_sse_comige_ss:
5062 case Intrinsic::x86_sse_comineq_ss:
5063 case Intrinsic::x86_sse_ucomieq_ss:
5064 case Intrinsic::x86_sse_ucomilt_ss:
5065 case Intrinsic::x86_sse_ucomile_ss:
5066 case Intrinsic::x86_sse_ucomigt_ss:
5067 case Intrinsic::x86_sse_ucomige_ss:
5068 case Intrinsic::x86_sse_ucomineq_ss:
5069 case Intrinsic::x86_sse2_comieq_sd:
5070 case Intrinsic::x86_sse2_comilt_sd:
5071 case Intrinsic::x86_sse2_comile_sd:
5072 case Intrinsic::x86_sse2_comigt_sd:
5073 case Intrinsic::x86_sse2_comige_sd:
5074 case Intrinsic::x86_sse2_comineq_sd:
5075 case Intrinsic::x86_sse2_ucomieq_sd:
5076 case Intrinsic::x86_sse2_ucomilt_sd:
5077 case Intrinsic::x86_sse2_ucomile_sd:
5078 case Intrinsic::x86_sse2_ucomigt_sd:
5079 case Intrinsic::x86_sse2_ucomige_sd:
5080 case Intrinsic::x86_sse2_ucomineq_sd: {
5082 ISD::CondCode CC = ISD::SETCC_INVALID;
5085 case Intrinsic::x86_sse_comieq_ss:
5086 case Intrinsic::x86_sse2_comieq_sd:
5090 case Intrinsic::x86_sse_comilt_ss:
5091 case Intrinsic::x86_sse2_comilt_sd:
5095 case Intrinsic::x86_sse_comile_ss:
5096 case Intrinsic::x86_sse2_comile_sd:
5100 case Intrinsic::x86_sse_comigt_ss:
5101 case Intrinsic::x86_sse2_comigt_sd:
5105 case Intrinsic::x86_sse_comige_ss:
5106 case Intrinsic::x86_sse2_comige_sd:
5110 case Intrinsic::x86_sse_comineq_ss:
5111 case Intrinsic::x86_sse2_comineq_sd:
5115 case Intrinsic::x86_sse_ucomieq_ss:
5116 case Intrinsic::x86_sse2_ucomieq_sd:
5117 Opc = X86ISD::UCOMI;
5120 case Intrinsic::x86_sse_ucomilt_ss:
5121 case Intrinsic::x86_sse2_ucomilt_sd:
5122 Opc = X86ISD::UCOMI;
5125 case Intrinsic::x86_sse_ucomile_ss:
5126 case Intrinsic::x86_sse2_ucomile_sd:
5127 Opc = X86ISD::UCOMI;
5130 case Intrinsic::x86_sse_ucomigt_ss:
5131 case Intrinsic::x86_sse2_ucomigt_sd:
5132 Opc = X86ISD::UCOMI;
5135 case Intrinsic::x86_sse_ucomige_ss:
5136 case Intrinsic::x86_sse2_ucomige_sd:
5137 Opc = X86ISD::UCOMI;
5140 case Intrinsic::x86_sse_ucomineq_ss:
5141 case Intrinsic::x86_sse2_ucomineq_sd:
5142 Opc = X86ISD::UCOMI;
5148 SDOperand LHS = Op.getOperand(1);
5149 SDOperand RHS = Op.getOperand(2);
5150 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5152 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5153 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5154 DAG.getConstant(X86CC, MVT::i8), Cond);
5155 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5160 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5161 // Depths > 0 not supported yet!
5162 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5165 // Just load the return address
5166 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5167 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5170 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5171 // Depths > 0 not supported yet!
5172 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5175 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5176 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5177 DAG.getConstant(4, getPointerTy()));
5180 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5181 SelectionDAG &DAG) {
5182 // Is not yet supported on x86-64
5183 if (Subtarget->is64Bit())
5186 return DAG.getConstant(8, getPointerTy());
5189 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5191 assert(!Subtarget->is64Bit() &&
5192 "Lowering of eh_return builtin is not supported yet on x86-64");
5194 MachineFunction &MF = DAG.getMachineFunction();
5195 SDOperand Chain = Op.getOperand(0);
5196 SDOperand Offset = Op.getOperand(1);
5197 SDOperand Handler = Op.getOperand(2);
5199 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5202 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5203 DAG.getConstant(-4UL, getPointerTy()));
5204 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5205 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5206 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5207 MF.addLiveOut(X86::ECX);
5209 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5210 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5213 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5214 SelectionDAG &DAG) {
5215 SDOperand Root = Op.getOperand(0);
5216 SDOperand Trmp = Op.getOperand(1); // trampoline
5217 SDOperand FPtr = Op.getOperand(2); // nested function
5218 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5220 SrcValueSDNode *TrmpSV = cast<SrcValueSDNode>(Op.getOperand(4));
5222 if (Subtarget->is64Bit()) {
5223 return SDOperand(); // not yet supported
5225 Function *Func = (Function *)
5226 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5227 unsigned CC = Func->getCallingConv();
5232 assert(0 && "Unsupported calling convention");
5233 case CallingConv::C:
5234 case CallingConv::X86_StdCall: {
5235 // Pass 'nest' parameter in ECX.
5236 // Must be kept in sync with X86CallingConv.td
5239 // Check that ECX wasn't needed by an 'inreg' parameter.
5240 const FunctionType *FTy = Func->getFunctionType();
5241 const ParamAttrsList *Attrs = Func->getParamAttrs();
5243 if (Attrs && !Func->isVarArg()) {
5244 unsigned InRegCount = 0;
5247 for (FunctionType::param_iterator I = FTy->param_begin(),
5248 E = FTy->param_end(); I != E; ++I, ++Idx)
5249 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5250 // FIXME: should only count parameters that are lowered to integers.
5251 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5253 if (InRegCount > 2) {
5254 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5260 case CallingConv::X86_FastCall:
5261 // Pass 'nest' parameter in EAX.
5262 // Must be kept in sync with X86CallingConv.td
5267 const X86InstrInfo *TII =
5268 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5270 SDOperand OutChains[4];
5271 SDOperand Addr, Disp;
5273 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5274 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5276 unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5277 unsigned char N86Reg = ((X86RegisterInfo&)RegInfo).getX86RegNum(NestReg);
5278 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5279 Trmp, TrmpSV->getValue(), TrmpSV->getOffset());
5281 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5282 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpSV->getValue(),
5283 TrmpSV->getOffset() + 1, false, 1);
5285 unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5286 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5287 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5288 TrmpSV->getValue() + 5, TrmpSV->getOffset());
5290 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5291 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpSV->getValue(),
5292 TrmpSV->getOffset() + 6, false, 1);
5295 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5296 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5300 SDOperand X86TargetLowering::LowerFLT_ROUNDS(SDOperand Op, SelectionDAG &DAG) {
5302 The rounding mode is in bits 11:10 of FPSR, and has the following
5309 FLT_ROUNDS, on the other hand, expects the following:
5316 To perform the conversion, we do:
5317 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5320 MachineFunction &MF = DAG.getMachineFunction();
5321 const TargetMachine &TM = MF.getTarget();
5322 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5323 unsigned StackAlignment = TFI.getStackAlignment();
5324 MVT::ValueType VT = Op.getValueType();
5326 // Save FP Control Word to stack slot
5327 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5328 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5330 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5331 DAG.getEntryNode(), StackSlot);
5333 // Load FP Control Word from stack slot
5334 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5336 // Transform as necessary
5338 DAG.getNode(ISD::SRL, MVT::i16,
5339 DAG.getNode(ISD::AND, MVT::i16,
5340 CWD, DAG.getConstant(0x800, MVT::i16)),
5341 DAG.getConstant(11, MVT::i8));
5343 DAG.getNode(ISD::SRL, MVT::i16,
5344 DAG.getNode(ISD::AND, MVT::i16,
5345 CWD, DAG.getConstant(0x400, MVT::i16)),
5346 DAG.getConstant(9, MVT::i8));
5349 DAG.getNode(ISD::AND, MVT::i16,
5350 DAG.getNode(ISD::ADD, MVT::i16,
5351 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5352 DAG.getConstant(1, MVT::i16)),
5353 DAG.getConstant(3, MVT::i16));
5356 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5357 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5360 /// LowerOperation - Provide custom lowering hooks for some operations.
5362 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5363 switch (Op.getOpcode()) {
5364 default: assert(0 && "Should not custom lower this!");
5365 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5366 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5367 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5368 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5369 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5370 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5371 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5372 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5373 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5374 case ISD::SHL_PARTS:
5375 case ISD::SRA_PARTS:
5376 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5377 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5378 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5379 case ISD::FABS: return LowerFABS(Op, DAG);
5380 case ISD::FNEG: return LowerFNEG(Op, DAG);
5381 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5382 case ISD::SETCC: return LowerSETCC(Op, DAG);
5383 case ISD::SELECT: return LowerSELECT(Op, DAG);
5384 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5385 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5386 case ISD::CALL: return LowerCALL(Op, DAG);
5387 case ISD::RET: return LowerRET(Op, DAG);
5388 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5389 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5390 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
5391 case ISD::VASTART: return LowerVASTART(Op, DAG);
5392 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5393 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5394 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5395 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5396 case ISD::FRAME_TO_ARGS_OFFSET:
5397 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5398 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5399 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5400 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5401 case ISD::FLT_ROUNDS: return LowerFLT_ROUNDS(Op, DAG);
5404 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5405 case ISD::READCYCLECOUNTER:
5406 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5410 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5411 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5412 switch (N->getOpcode()) {
5413 default: assert(0 && "Should not custom lower this!");
5414 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5415 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5419 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5421 default: return NULL;
5422 case X86ISD::SHLD: return "X86ISD::SHLD";
5423 case X86ISD::SHRD: return "X86ISD::SHRD";
5424 case X86ISD::FAND: return "X86ISD::FAND";
5425 case X86ISD::FOR: return "X86ISD::FOR";
5426 case X86ISD::FXOR: return "X86ISD::FXOR";
5427 case X86ISD::FSRL: return "X86ISD::FSRL";
5428 case X86ISD::FILD: return "X86ISD::FILD";
5429 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5430 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5431 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5432 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5433 case X86ISD::FLD: return "X86ISD::FLD";
5434 case X86ISD::FST: return "X86ISD::FST";
5435 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5436 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5437 case X86ISD::CALL: return "X86ISD::CALL";
5438 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5439 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5440 case X86ISD::CMP: return "X86ISD::CMP";
5441 case X86ISD::COMI: return "X86ISD::COMI";
5442 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5443 case X86ISD::SETCC: return "X86ISD::SETCC";
5444 case X86ISD::CMOV: return "X86ISD::CMOV";
5445 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5446 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5447 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5448 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5449 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5450 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5451 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5452 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5453 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5454 case X86ISD::FMAX: return "X86ISD::FMAX";
5455 case X86ISD::FMIN: return "X86ISD::FMIN";
5456 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5457 case X86ISD::FRCP: return "X86ISD::FRCP";
5458 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5459 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5460 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5461 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5462 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5466 // isLegalAddressingMode - Return true if the addressing mode represented
5467 // by AM is legal for this target, for a load/store of the specified type.
5468 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5469 const Type *Ty) const {
5470 // X86 supports extremely general addressing modes.
5472 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5473 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5477 // We can only fold this if we don't need an extra load.
5478 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5481 // X86-64 only supports addr of globals in small code model.
5482 if (Subtarget->is64Bit()) {
5483 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5485 // If lower 4G is not available, then we must use rip-relative addressing.
5486 if (AM.BaseOffs || AM.Scale > 1)
5497 // These scales always work.
5502 // These scales are formed with basereg+scalereg. Only accept if there is
5507 default: // Other stuff never works.
5515 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5516 if (!Ty1->isInteger() || !Ty2->isInteger())
5518 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5519 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5520 if (NumBits1 <= NumBits2)
5522 return Subtarget->is64Bit() || NumBits1 < 64;
5525 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5526 MVT::ValueType VT2) const {
5527 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5529 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5530 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5531 if (NumBits1 <= NumBits2)
5533 return Subtarget->is64Bit() || NumBits1 < 64;
5536 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5537 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5538 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5539 /// are assumed to be legal.
5541 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5542 // Only do shuffles on 128-bit vector types for now.
5543 if (MVT::getSizeInBits(VT) == 64) return false;
5544 return (Mask.Val->getNumOperands() <= 4 ||
5545 isIdentityMask(Mask.Val) ||
5546 isIdentityMask(Mask.Val, true) ||
5547 isSplatMask(Mask.Val) ||
5548 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5549 X86::isUNPCKLMask(Mask.Val) ||
5550 X86::isUNPCKHMask(Mask.Val) ||
5551 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5552 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5555 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5557 SelectionDAG &DAG) const {
5558 unsigned NumElts = BVOps.size();
5559 // Only do shuffles on 128-bit vector types for now.
5560 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5561 if (NumElts == 2) return true;
5563 return (isMOVLMask(&BVOps[0], 4) ||
5564 isCommutedMOVL(&BVOps[0], 4, true) ||
5565 isSHUFPMask(&BVOps[0], 4) ||
5566 isCommutedSHUFP(&BVOps[0], 4));
5571 //===----------------------------------------------------------------------===//
5572 // X86 Scheduler Hooks
5573 //===----------------------------------------------------------------------===//
5576 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
5577 MachineBasicBlock *BB) {
5578 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5579 switch (MI->getOpcode()) {
5580 default: assert(false && "Unexpected instr type to insert");
5581 case X86::CMOV_FR32:
5582 case X86::CMOV_FR64:
5583 case X86::CMOV_V4F32:
5584 case X86::CMOV_V2F64:
5585 case X86::CMOV_V2I64: {
5586 // To "insert" a SELECT_CC instruction, we actually have to insert the
5587 // diamond control-flow pattern. The incoming instruction knows the
5588 // destination vreg to set, the condition code register to branch on, the
5589 // true/false values to select between, and a branch opcode to use.
5590 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5591 ilist<MachineBasicBlock>::iterator It = BB;
5597 // cmpTY ccX, r1, r2
5599 // fallthrough --> copy0MBB
5600 MachineBasicBlock *thisMBB = BB;
5601 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5602 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5604 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5605 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5606 MachineFunction *F = BB->getParent();
5607 F->getBasicBlockList().insert(It, copy0MBB);
5608 F->getBasicBlockList().insert(It, sinkMBB);
5609 // Update machine-CFG edges by first adding all successors of the current
5610 // block to the new block which will contain the Phi node for the select.
5611 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5612 e = BB->succ_end(); i != e; ++i)
5613 sinkMBB->addSuccessor(*i);
5614 // Next, remove all successors of the current block, and add the true
5615 // and fallthrough blocks as its successors.
5616 while(!BB->succ_empty())
5617 BB->removeSuccessor(BB->succ_begin());
5618 BB->addSuccessor(copy0MBB);
5619 BB->addSuccessor(sinkMBB);
5622 // %FalseValue = ...
5623 // # fallthrough to sinkMBB
5626 // Update machine-CFG edges
5627 BB->addSuccessor(sinkMBB);
5630 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5633 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5634 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5635 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5637 delete MI; // The pseudo instruction is gone now.
5641 case X86::FP32_TO_INT16_IN_MEM:
5642 case X86::FP32_TO_INT32_IN_MEM:
5643 case X86::FP32_TO_INT64_IN_MEM:
5644 case X86::FP64_TO_INT16_IN_MEM:
5645 case X86::FP64_TO_INT32_IN_MEM:
5646 case X86::FP64_TO_INT64_IN_MEM:
5647 case X86::FP80_TO_INT16_IN_MEM:
5648 case X86::FP80_TO_INT32_IN_MEM:
5649 case X86::FP80_TO_INT64_IN_MEM: {
5650 // Change the floating point control register to use "round towards zero"
5651 // mode when truncating to an integer value.
5652 MachineFunction *F = BB->getParent();
5653 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5654 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5656 // Load the old value of the high byte of the control word...
5658 F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
5659 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5661 // Set the high part to be round to zero...
5662 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5665 // Reload the modified control word now...
5666 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5668 // Restore the memory image of control word to original value
5669 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5672 // Get the X86 opcode to use.
5674 switch (MI->getOpcode()) {
5675 default: assert(0 && "illegal opcode!");
5676 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5677 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5678 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5679 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5680 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5681 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5682 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5683 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5684 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5688 MachineOperand &Op = MI->getOperand(0);
5689 if (Op.isRegister()) {
5690 AM.BaseType = X86AddressMode::RegBase;
5691 AM.Base.Reg = Op.getReg();
5693 AM.BaseType = X86AddressMode::FrameIndexBase;
5694 AM.Base.FrameIndex = Op.getFrameIndex();
5696 Op = MI->getOperand(1);
5697 if (Op.isImmediate())
5698 AM.Scale = Op.getImm();
5699 Op = MI->getOperand(2);
5700 if (Op.isImmediate())
5701 AM.IndexReg = Op.getImm();
5702 Op = MI->getOperand(3);
5703 if (Op.isGlobalAddress()) {
5704 AM.GV = Op.getGlobal();
5706 AM.Disp = Op.getImm();
5708 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5709 .addReg(MI->getOperand(4).getReg());
5711 // Reload the original control word now.
5712 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5714 delete MI; // The pseudo instruction is gone now.
5720 //===----------------------------------------------------------------------===//
5721 // X86 Optimization Hooks
5722 //===----------------------------------------------------------------------===//
5724 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5726 uint64_t &KnownZero,
5728 const SelectionDAG &DAG,
5729 unsigned Depth) const {
5730 unsigned Opc = Op.getOpcode();
5731 assert((Opc >= ISD::BUILTIN_OP_END ||
5732 Opc == ISD::INTRINSIC_WO_CHAIN ||
5733 Opc == ISD::INTRINSIC_W_CHAIN ||
5734 Opc == ISD::INTRINSIC_VOID) &&
5735 "Should use MaskedValueIsZero if you don't know whether Op"
5736 " is a target node!");
5738 KnownZero = KnownOne = 0; // Don't know anything.
5742 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5747 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5748 /// element of the result of the vector shuffle.
5749 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5750 MVT::ValueType VT = N->getValueType(0);
5751 SDOperand PermMask = N->getOperand(2);
5752 unsigned NumElems = PermMask.getNumOperands();
5753 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5755 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5757 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5758 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5759 SDOperand Idx = PermMask.getOperand(i);
5760 if (Idx.getOpcode() == ISD::UNDEF)
5761 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5762 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5767 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5768 /// node is a GlobalAddress + an offset.
5769 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5770 unsigned Opc = N->getOpcode();
5771 if (Opc == X86ISD::Wrapper) {
5772 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5773 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5776 } else if (Opc == ISD::ADD) {
5777 SDOperand N1 = N->getOperand(0);
5778 SDOperand N2 = N->getOperand(1);
5779 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5780 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5782 Offset += V->getSignExtended();
5785 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5786 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5788 Offset += V->getSignExtended();
5796 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5798 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5799 MachineFrameInfo *MFI) {
5800 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5803 SDOperand Loc = N->getOperand(1);
5804 SDOperand BaseLoc = Base->getOperand(1);
5805 if (Loc.getOpcode() == ISD::FrameIndex) {
5806 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5808 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5809 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5810 int FS = MFI->getObjectSize(FI);
5811 int BFS = MFI->getObjectSize(BFI);
5812 if (FS != BFS || FS != Size) return false;
5813 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5815 GlobalValue *GV1 = NULL;
5816 GlobalValue *GV2 = NULL;
5817 int64_t Offset1 = 0;
5818 int64_t Offset2 = 0;
5819 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5820 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5821 if (isGA1 && isGA2 && GV1 == GV2)
5822 return Offset1 == (Offset2 + Dist*Size);
5828 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5829 const X86Subtarget *Subtarget) {
5832 if (isGAPlusOffset(Base, GV, Offset))
5833 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5835 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
5836 int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
5838 // Fixed objects do not specify alignment, however the offsets are known.
5839 return ((Subtarget->getStackAlignment() % 16) == 0 &&
5840 (MFI->getObjectOffset(BFI) % 16) == 0);
5842 return MFI->getObjectAlignment(BFI) >= 16;
5848 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5849 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5850 /// if the load addresses are consecutive, non-overlapping, and in the right
5852 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5853 const X86Subtarget *Subtarget) {
5854 MachineFunction &MF = DAG.getMachineFunction();
5855 MachineFrameInfo *MFI = MF.getFrameInfo();
5856 MVT::ValueType VT = N->getValueType(0);
5857 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5858 SDOperand PermMask = N->getOperand(2);
5859 int NumElems = (int)PermMask.getNumOperands();
5860 SDNode *Base = NULL;
5861 for (int i = 0; i < NumElems; ++i) {
5862 SDOperand Idx = PermMask.getOperand(i);
5863 if (Idx.getOpcode() == ISD::UNDEF) {
5864 if (!Base) return SDOperand();
5867 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5868 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5872 else if (!isConsecutiveLoad(Arg.Val, Base,
5873 i, MVT::getSizeInBits(EVT)/8,MFI))
5878 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5879 LoadSDNode *LD = cast<LoadSDNode>(Base);
5881 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5882 LD->getSrcValueOffset(), LD->isVolatile());
5884 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5885 LD->getSrcValueOffset(), LD->isVolatile(),
5886 LD->getAlignment());
5890 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5891 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5892 const X86Subtarget *Subtarget) {
5893 SDOperand Cond = N->getOperand(0);
5895 // If we have SSE[12] support, try to form min/max nodes.
5896 if (Subtarget->hasSSE2() &&
5897 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5898 if (Cond.getOpcode() == ISD::SETCC) {
5899 // Get the LHS/RHS of the select.
5900 SDOperand LHS = N->getOperand(1);
5901 SDOperand RHS = N->getOperand(2);
5902 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5904 unsigned Opcode = 0;
5905 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5908 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5911 if (!UnsafeFPMath) break;
5913 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
5915 Opcode = X86ISD::FMIN;
5918 case ISD::SETOGT: // (X > Y) ? X : Y -> max
5921 if (!UnsafeFPMath) break;
5923 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
5925 Opcode = X86ISD::FMAX;
5928 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5931 case ISD::SETOGT: // (X > Y) ? Y : X -> min
5934 if (!UnsafeFPMath) break;
5936 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
5938 Opcode = X86ISD::FMIN;
5941 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
5944 if (!UnsafeFPMath) break;
5946 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
5948 Opcode = X86ISD::FMAX;
5954 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5963 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5964 DAGCombinerInfo &DCI) const {
5965 SelectionDAG &DAG = DCI.DAG;
5966 switch (N->getOpcode()) {
5968 case ISD::VECTOR_SHUFFLE:
5969 return PerformShuffleCombine(N, DAG, Subtarget);
5971 return PerformSELECTCombine(N, DAG, Subtarget);
5977 //===----------------------------------------------------------------------===//
5978 // X86 Inline Assembly Support
5979 //===----------------------------------------------------------------------===//
5981 /// getConstraintType - Given a constraint letter, return the type of
5982 /// constraint it is for this target.
5983 X86TargetLowering::ConstraintType
5984 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
5985 if (Constraint.size() == 1) {
5986 switch (Constraint[0]) {
5995 return C_RegisterClass;
6000 return TargetLowering::getConstraintType(Constraint);
6003 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6004 /// vector. If it is invalid, don't add anything to Ops.
6005 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6007 std::vector<SDOperand>&Ops,
6008 SelectionDAG &DAG) {
6009 SDOperand Result(0, 0);
6011 switch (Constraint) {
6014 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6015 if (C->getValue() <= 31) {
6016 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6022 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6023 if (C->getValue() <= 255) {
6024 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6030 // Literal immediates are always ok.
6031 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6032 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6036 // If we are in non-pic codegen mode, we allow the address of a global (with
6037 // an optional displacement) to be used with 'i'.
6038 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6041 // Match either (GA) or (GA+C)
6043 Offset = GA->getOffset();
6044 } else if (Op.getOpcode() == ISD::ADD) {
6045 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6046 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6048 Offset = GA->getOffset()+C->getValue();
6050 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6051 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6053 Offset = GA->getOffset()+C->getValue();
6060 // If addressing this global requires a load (e.g. in PIC mode), we can't
6062 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6066 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6072 // Otherwise, not valid for this mode.
6078 Ops.push_back(Result);
6081 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6084 std::vector<unsigned> X86TargetLowering::
6085 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6086 MVT::ValueType VT) const {
6087 if (Constraint.size() == 1) {
6088 // FIXME: not handling fp-stack yet!
6089 switch (Constraint[0]) { // GCC X86 Constraint Letters
6090 default: break; // Unknown constraint letter
6091 case 'A': // EAX/EDX
6092 if (VT == MVT::i32 || VT == MVT::i64)
6093 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6095 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6098 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6099 else if (VT == MVT::i16)
6100 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6101 else if (VT == MVT::i8)
6102 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6103 else if (VT == MVT::i64)
6104 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6109 return std::vector<unsigned>();
6112 std::pair<unsigned, const TargetRegisterClass*>
6113 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6114 MVT::ValueType VT) const {
6115 // First, see if this is a constraint that directly corresponds to an LLVM
6117 if (Constraint.size() == 1) {
6118 // GCC Constraint Letters
6119 switch (Constraint[0]) {
6121 case 'r': // GENERAL_REGS
6122 case 'R': // LEGACY_REGS
6123 case 'l': // INDEX_REGS
6124 if (VT == MVT::i64 && Subtarget->is64Bit())
6125 return std::make_pair(0U, X86::GR64RegisterClass);
6127 return std::make_pair(0U, X86::GR32RegisterClass);
6128 else if (VT == MVT::i16)
6129 return std::make_pair(0U, X86::GR16RegisterClass);
6130 else if (VT == MVT::i8)
6131 return std::make_pair(0U, X86::GR8RegisterClass);
6133 case 'y': // MMX_REGS if MMX allowed.
6134 if (!Subtarget->hasMMX()) break;
6135 return std::make_pair(0U, X86::VR64RegisterClass);
6137 case 'Y': // SSE_REGS if SSE2 allowed
6138 if (!Subtarget->hasSSE2()) break;
6140 case 'x': // SSE_REGS if SSE1 allowed
6141 if (!Subtarget->hasSSE1()) break;
6145 // Scalar SSE types.
6148 return std::make_pair(0U, X86::FR32RegisterClass);
6151 return std::make_pair(0U, X86::FR64RegisterClass);
6159 return std::make_pair(0U, X86::VR128RegisterClass);
6165 // Use the default implementation in TargetLowering to convert the register
6166 // constraint into a member of a register class.
6167 std::pair<unsigned, const TargetRegisterClass*> Res;
6168 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6170 // Not found as a standard register?
6171 if (Res.second == 0) {
6172 // GCC calls "st(0)" just plain "st".
6173 if (StringsEqualNoCase("{st}", Constraint)) {
6174 Res.first = X86::ST0;
6175 Res.second = X86::RFP80RegisterClass;
6181 // Otherwise, check to see if this is a register class of the wrong value
6182 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6183 // turn into {ax},{dx}.
6184 if (Res.second->hasType(VT))
6185 return Res; // Correct type already, nothing to do.
6187 // All of the single-register GCC register classes map their values onto
6188 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6189 // really want an 8-bit or 32-bit register, map to the appropriate register
6190 // class and return the appropriate register.
6191 if (Res.second != X86::GR16RegisterClass)
6194 if (VT == MVT::i8) {
6195 unsigned DestReg = 0;
6196 switch (Res.first) {
6198 case X86::AX: DestReg = X86::AL; break;
6199 case X86::DX: DestReg = X86::DL; break;
6200 case X86::CX: DestReg = X86::CL; break;
6201 case X86::BX: DestReg = X86::BL; break;
6204 Res.first = DestReg;
6205 Res.second = Res.second = X86::GR8RegisterClass;
6207 } else if (VT == MVT::i32) {
6208 unsigned DestReg = 0;
6209 switch (Res.first) {
6211 case X86::AX: DestReg = X86::EAX; break;
6212 case X86::DX: DestReg = X86::EDX; break;
6213 case X86::CX: DestReg = X86::ECX; break;
6214 case X86::BX: DestReg = X86::EBX; break;
6215 case X86::SI: DestReg = X86::ESI; break;
6216 case X86::DI: DestReg = X86::EDI; break;
6217 case X86::BP: DestReg = X86::EBP; break;
6218 case X86::SP: DestReg = X86::ESP; break;
6221 Res.first = DestReg;
6222 Res.second = Res.second = X86::GR32RegisterClass;
6224 } else if (VT == MVT::i64) {
6225 unsigned DestReg = 0;
6226 switch (Res.first) {
6228 case X86::AX: DestReg = X86::RAX; break;
6229 case X86::DX: DestReg = X86::RDX; break;
6230 case X86::CX: DestReg = X86::RCX; break;
6231 case X86::BX: DestReg = X86::RBX; break;
6232 case X86::SI: DestReg = X86::RSI; break;
6233 case X86::DI: DestReg = X86::RDI; break;
6234 case X86::BP: DestReg = X86::RBP; break;
6235 case X86::SP: DestReg = X86::RSP; break;
6238 Res.first = DestReg;
6239 Res.second = Res.second = X86::GR64RegisterClass;