blob: 3180e647033e3b5f470ee6bf99424bcd1ca664f6 [file] [log] [blame]
Arnold Schwaighofera70fe792007-10-12 21:53:12 +00001//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that X86 uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#include "X86.h"
16#include "X86InstrBuilder.h"
17#include "X86ISelLowering.h"
18#include "X86MachineFunctionInfo.h"
19#include "X86TargetMachine.h"
20#include "llvm/CallingConv.h"
21#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/Function.h"
25#include "llvm/Intrinsics.h"
26#include "llvm/ADT/VectorExtras.h"
27#include "llvm/Analysis/ScalarEvolutionExpressions.h"
28#include "llvm/CodeGen/CallingConvLower.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
32#include "llvm/CodeGen/SelectionDAG.h"
33#include "llvm/CodeGen/SSARegMap.h"
34#include "llvm/Support/MathExtras.h"
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037#include "llvm/Target/TargetOptions.h"
38#include "llvm/ADT/StringExtras.h"
Duncan Sandsd8455ca2007-07-27 20:02:49 +000039#include "llvm/ParameterAttributes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040using namespace llvm;
41
42X86TargetLowering::X86TargetLowering(TargetMachine &TM)
43 : TargetLowering(TM) {
44 Subtarget = &TM.getSubtarget<X86Subtarget>();
Dale Johannesene0e0fd02007-09-23 14:52:20 +000045 X86ScalarSSEf64 = Subtarget->hasSSE2();
46 X86ScalarSSEf32 = Subtarget->hasSSE1();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +000048
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049
50 RegInfo = TM.getRegisterInfo();
51
52 // Set up the TargetLowering object.
53
54 // X86 is weird, it always uses i8 for shift amounts and setcc results.
55 setShiftAmountType(MVT::i8);
56 setSetCCResultType(MVT::i8);
57 setSetCCResultContents(ZeroOrOneSetCCResult);
58 setSchedulingPreference(SchedulingForRegPressure);
59 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
60 setStackPointerRegisterToSaveRestore(X86StackPtr);
61
62 if (Subtarget->isTargetDarwin()) {
63 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
64 setUseUnderscoreSetJmp(false);
65 setUseUnderscoreLongJmp(false);
66 } else if (Subtarget->isTargetMingw()) {
67 // MS runtime is weird: it exports _setjmp, but longjmp!
68 setUseUnderscoreSetJmp(true);
69 setUseUnderscoreLongJmp(false);
70 } else {
71 setUseUnderscoreSetJmp(true);
72 setUseUnderscoreLongJmp(true);
73 }
74
75 // Set up the register classes.
76 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
77 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
78 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
79 if (Subtarget->is64Bit())
80 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
81
82 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
83
84 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
85 // operation.
86 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
87 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
88 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
89
90 if (Subtarget->is64Bit()) {
91 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
92 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
93 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +000094 if (X86ScalarSSEf64)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
96 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
97 else
98 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
99 }
100
101 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
102 // this operation.
103 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
104 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
105 // SSE has no i16 to fp conversion, only i32
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000106 if (X86ScalarSSEf32) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000108 // f32 and f64 cases are Legal, f80 case is not
109 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
110 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000111 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
112 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
113 }
114
Dale Johannesen958b08b2007-09-19 23:55:34 +0000115 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
116 // are Legal, f80 is custom lowered.
117 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
118 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119
120 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
121 // this operation.
122 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
123 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
124
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000125 if (X86ScalarSSEf32) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000126 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000127 // f32 and f64 cases are Legal, f80 case is not
128 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129 } else {
130 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
131 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
132 }
133
134 // Handle FP_TO_UINT by promoting the destination to a larger signed
135 // conversion.
136 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
137 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
138 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
139
140 if (Subtarget->is64Bit()) {
141 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
142 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
143 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000144 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 // Expand FP_TO_UINT into a select.
146 // FIXME: We would like to use a Custom expander here eventually to do
147 // the optimal thing for SSE vs. the default expansion in the legalizer.
148 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
149 else
150 // With SSE3 we can use fisttpll to convert to a signed i64.
151 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
152 }
153
154 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000155 if (!X86ScalarSSEf64) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
157 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
158 }
159
Dan Gohman5a199552007-10-08 18:33:35 +0000160 // Scalar integer multiply, multiply-high, divide, and remainder are
161 // lowered to use operations that produce two results, to match the
162 // available instructions. This exposes the two-result form to trivial
163 // CSE, which is able to combine x/y and x%y into a single instruction,
164 // for example. The single-result multiply instructions are introduced
165 // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
166 // is not needed.
167 setOperationAction(ISD::MUL , MVT::i8 , Expand);
168 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
169 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
170 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
171 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
172 setOperationAction(ISD::SREM , MVT::i8 , Expand);
173 setOperationAction(ISD::UREM , MVT::i8 , Expand);
174 setOperationAction(ISD::MUL , MVT::i16 , Expand);
175 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
176 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
177 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
178 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
179 setOperationAction(ISD::SREM , MVT::i16 , Expand);
180 setOperationAction(ISD::UREM , MVT::i16 , Expand);
181 setOperationAction(ISD::MUL , MVT::i32 , Expand);
182 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
183 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
184 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
185 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
186 setOperationAction(ISD::SREM , MVT::i32 , Expand);
187 setOperationAction(ISD::UREM , MVT::i32 , Expand);
188 setOperationAction(ISD::MUL , MVT::i64 , Expand);
189 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
190 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
191 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
192 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
193 setOperationAction(ISD::SREM , MVT::i64 , Expand);
194 setOperationAction(ISD::UREM , MVT::i64 , Expand);
Dan Gohman242a5ba2007-09-25 18:23:27 +0000195
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
197 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
198 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
199 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
200 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
201 if (Subtarget->is64Bit())
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
206 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
207 setOperationAction(ISD::FREM , MVT::f64 , Expand);
208
209 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i8 , Expand);
211 setOperationAction(ISD::CTLZ , MVT::i8 , Expand);
212 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
213 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
214 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
215 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
216 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
217 setOperationAction(ISD::CTLZ , MVT::i32 , Expand);
218 if (Subtarget->is64Bit()) {
219 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
220 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
221 setOperationAction(ISD::CTLZ , MVT::i64 , Expand);
222 }
223
224 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
225 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
226
227 // These should be promoted to a larger select which is supported.
228 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
229 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
230 // X86 wants to expand cmov itself.
231 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
232 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
233 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
234 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000235 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
237 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
238 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
239 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
240 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000241 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 if (Subtarget->is64Bit()) {
243 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
244 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
245 }
246 // X86 ret instruction may pop stack.
247 setOperationAction(ISD::RET , MVT::Other, Custom);
248 if (!Subtarget->is64Bit())
249 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
250
251 // Darwin ABI issue.
252 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
253 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
254 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
255 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
256 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
257 if (Subtarget->is64Bit()) {
258 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
259 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
260 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
261 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
262 }
263 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
264 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
265 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
266 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
267 // X86 wants to expand memset / memcpy itself.
268 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
269 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
270
Dan Gohman21442852007-09-25 15:10:49 +0000271 // Use the default ISD::LOCATION expansion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 // FIXME - use subtarget debug flags
274 if (!Subtarget->isTargetDarwin() &&
275 !Subtarget->isTargetELF() &&
276 !Subtarget->isTargetCygMing())
277 setOperationAction(ISD::LABEL, MVT::Other, Expand);
278
279 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
280 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
281 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
282 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
283 if (Subtarget->is64Bit()) {
284 // FIXME: Verify
285 setExceptionPointerRegister(X86::RAX);
286 setExceptionSelectorRegister(X86::RDX);
287 } else {
288 setExceptionPointerRegister(X86::EAX);
289 setExceptionSelectorRegister(X86::EDX);
290 }
Anton Korobeynikov23ca9c52007-09-03 00:36:06 +0000291 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292
Duncan Sands7407a9f2007-09-11 14:10:23 +0000293 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
Duncan Sandsd8455ca2007-07-27 20:02:49 +0000294
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
296 setOperationAction(ISD::VASTART , MVT::Other, Custom);
297 setOperationAction(ISD::VAARG , MVT::Other, Expand);
298 setOperationAction(ISD::VAEND , MVT::Other, Expand);
299 if (Subtarget->is64Bit())
300 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
301 else
302 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
303
304 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
305 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
306 if (Subtarget->is64Bit())
307 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
308 if (Subtarget->isTargetCygMing())
309 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
310 else
311 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
312
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000313 if (X86ScalarSSEf64) {
314 // f32 and f64 use SSE.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 // Set up the FP register classes.
316 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
317 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
318
319 // Use ANDPD to simulate FABS.
320 setOperationAction(ISD::FABS , MVT::f64, Custom);
321 setOperationAction(ISD::FABS , MVT::f32, Custom);
322
323 // Use XORP to simulate FNEG.
324 setOperationAction(ISD::FNEG , MVT::f64, Custom);
325 setOperationAction(ISD::FNEG , MVT::f32, Custom);
326
327 // Use ANDPD and ORPD to simulate FCOPYSIGN.
328 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
329 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
330
331 // We don't support sin/cos/fmod
332 setOperationAction(ISD::FSIN , MVT::f64, Expand);
333 setOperationAction(ISD::FCOS , MVT::f64, Expand);
334 setOperationAction(ISD::FREM , MVT::f64, Expand);
335 setOperationAction(ISD::FSIN , MVT::f32, Expand);
336 setOperationAction(ISD::FCOS , MVT::f32, Expand);
337 setOperationAction(ISD::FREM , MVT::f32, Expand);
338
339 // Expand FP immediates into loads from the stack, except for the special
340 // cases we handle.
341 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
342 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000343 addLegalFPImmediate(APFloat(+0.0)); // xorpd
344 addLegalFPImmediate(APFloat(+0.0f)); // xorps
Dale Johannesen8f83a6b2007-08-09 01:04:01 +0000345
346 // Conversions to long double (in X87) go through memory.
347 setConvertAction(MVT::f32, MVT::f80, Expand);
348 setConvertAction(MVT::f64, MVT::f80, Expand);
349
350 // Conversions from long double (in X87) go through memory.
351 setConvertAction(MVT::f80, MVT::f32, Expand);
352 setConvertAction(MVT::f80, MVT::f64, Expand);
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000353 } else if (X86ScalarSSEf32) {
354 // Use SSE for f32, x87 for f64.
355 // Set up the FP register classes.
356 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
357 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
358
359 // Use ANDPS to simulate FABS.
360 setOperationAction(ISD::FABS , MVT::f32, Custom);
361
362 // Use XORP to simulate FNEG.
363 setOperationAction(ISD::FNEG , MVT::f32, Custom);
364
365 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
366
367 // Use ANDPS and ORPS to simulate FCOPYSIGN.
368 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
369 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
370
371 // We don't support sin/cos/fmod
372 setOperationAction(ISD::FSIN , MVT::f32, Expand);
373 setOperationAction(ISD::FCOS , MVT::f32, Expand);
374 setOperationAction(ISD::FREM , MVT::f32, Expand);
375
376 // Expand FP immediates into loads from the stack, except for the special
377 // cases we handle.
378 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
379 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
380 addLegalFPImmediate(APFloat(+0.0f)); // xorps
381 addLegalFPImmediate(APFloat(+0.0)); // FLD0
382 addLegalFPImmediate(APFloat(+1.0)); // FLD1
383 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
384 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
385
386 // SSE->x87 conversions go through memory.
387 setConvertAction(MVT::f32, MVT::f64, Expand);
388 setConvertAction(MVT::f32, MVT::f80, Expand);
389
390 // x87->SSE truncations need to go through memory.
391 setConvertAction(MVT::f80, MVT::f32, Expand);
392 setConvertAction(MVT::f64, MVT::f32, Expand);
393 // And x87->x87 truncations also.
394 setConvertAction(MVT::f80, MVT::f64, Expand);
395
396 if (!UnsafeFPMath) {
397 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
398 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
399 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000400 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000401 // f32 and f64 in x87.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 // Set up the FP register classes.
403 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
404 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
405
406 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
407 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
408 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
409 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
Dale Johannesen8f83a6b2007-08-09 01:04:01 +0000410
411 // Floating truncations need to go through memory.
412 setConvertAction(MVT::f80, MVT::f32, Expand);
413 setConvertAction(MVT::f64, MVT::f32, Expand);
414 setConvertAction(MVT::f80, MVT::f64, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415
416 if (!UnsafeFPMath) {
417 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
418 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
419 }
420
421 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
422 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
Dale Johannesenbbe2b702007-08-30 00:23:21 +0000423 addLegalFPImmediate(APFloat(+0.0)); // FLD0
424 addLegalFPImmediate(APFloat(+1.0)); // FLD1
425 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
426 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000427 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
428 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
429 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
430 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431 }
432
Dale Johannesen4ab00bd2007-08-05 18:49:15 +0000433 // Long double always uses X87.
434 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000435 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
436 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
437 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
Dale Johannesen7f1076b2007-09-26 21:10:55 +0000438 if (!UnsafeFPMath) {
439 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
440 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
441 }
Dale Johannesen4ab00bd2007-08-05 18:49:15 +0000442
Dan Gohman2f7b1982007-10-11 23:21:31 +0000443 // Always use a library call for pow.
444 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
445 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
446 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
447
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448 // First set operation action for all vector types to expand. Then we
449 // will selectively turn on ones that can be effectively codegen'd.
450 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
451 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
452 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
453 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
454 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
455 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
456 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
457 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
458 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
459 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
460 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
461 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
462 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
463 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
464 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
465 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
466 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
467 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
468 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
469 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
470 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
471 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
472 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
473 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
474 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
Dan Gohman5a199552007-10-08 18:33:35 +0000475 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
476 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
477 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
478 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
Dan Gohman2f7b1982007-10-11 23:21:31 +0000479 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
Dan Gohman1d2dc2c2007-10-12 14:09:42 +0000480 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
481 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
482 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483 }
484
485 if (Subtarget->hasMMX()) {
486 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
487 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
488 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
489 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
490
491 // FIXME: add MMX packed arithmetics
492
493 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
494 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
495 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
496 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
497
498 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
499 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
500 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
Dale Johannesen6b65c332007-10-30 01:18:38 +0000501 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000502
503 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
504 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
505
506 setOperationAction(ISD::AND, MVT::v8i8, Promote);
507 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
508 setOperationAction(ISD::AND, MVT::v4i16, Promote);
509 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
510 setOperationAction(ISD::AND, MVT::v2i32, Promote);
511 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
512 setOperationAction(ISD::AND, MVT::v1i64, Legal);
513
514 setOperationAction(ISD::OR, MVT::v8i8, Promote);
515 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
516 setOperationAction(ISD::OR, MVT::v4i16, Promote);
517 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
518 setOperationAction(ISD::OR, MVT::v2i32, Promote);
519 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
520 setOperationAction(ISD::OR, MVT::v1i64, Legal);
521
522 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
523 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
524 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
525 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
526 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
527 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
528 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
529
530 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
531 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
532 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
533 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
534 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
535 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
536 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
537
538 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
539 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
540 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
541 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
542
543 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
544 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
545 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
546 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
547
548 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
549 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
550 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
551 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
552 }
553
554 if (Subtarget->hasSSE1()) {
555 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
556
557 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
558 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
559 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
560 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
561 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
562 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000563 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
564 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
565 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
566 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
567 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
568 }
569
570 if (Subtarget->hasSSE2()) {
571 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
572 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
573 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
574 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
575 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
576
577 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
578 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
579 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
580 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
581 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
582 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
583 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
584 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
585 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
586 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
587 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
588 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
589 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
590 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
591 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000592
593 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
594 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
595 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
596 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
597 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
598 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
599
600 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
601 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
602 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
603 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
604 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
605 }
606 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
607 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
608 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
609 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
610 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
Dale Johannesen2ff963d2007-10-31 00:32:36 +0000611 if (Subtarget->is64Bit())
612 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613
614 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
615 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
616 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
617 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
618 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
619 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
620 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
621 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
622 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
623 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
624 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
625 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
626 }
627
628 // Custom lower v2i64 and v2f64 selects.
629 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
630 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
631 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
632 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
633 }
634
635 // We want to custom lower some of our intrinsics.
636 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
637
638 // We have target-specific dag combine patterns for the following nodes:
639 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
640 setTargetDAGCombine(ISD::SELECT);
641
642 computeRegisterProperties();
643
644 // FIXME: These should be based on subtarget info. Plus, the values should
645 // be smaller when we are in optimizing for size mode.
646 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
647 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
648 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
649 allowUnalignedMemoryAccesses = true; // x86 supports it!
650}
651
652
653//===----------------------------------------------------------------------===//
654// Return Value Calling Convention Implementation
655//===----------------------------------------------------------------------===//
656
657#include "X86GenCallingConv.inc"
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000658
659/// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
660/// exists skip possible ISD:TokenFactor.
661static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
662 if (Chain.getOpcode()==X86ISD::TAILCALL) {
663 return Chain;
664 } else if (Chain.getOpcode()==ISD::TokenFactor) {
665 if (Chain.getNumOperands() &&
666 Chain.getOperand(0).getOpcode()==X86ISD::TAILCALL)
667 return Chain.getOperand(0);
668 }
669 return Chain;
670}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671
672/// LowerRET - Lower an ISD::RET node.
673SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
674 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
675
676 SmallVector<CCValAssign, 16> RVLocs;
677 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
678 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
679 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
680 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000681
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682 // If this is the first return lowered for this function, add the regs to the
683 // liveout set for the function.
684 if (DAG.getMachineFunction().liveout_empty()) {
685 for (unsigned i = 0; i != RVLocs.size(); ++i)
686 if (RVLocs[i].isRegLoc())
687 DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
688 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000689 SDOperand Chain = Op.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000691 // Handle tail call return.
692 Chain = GetPossiblePreceedingTailCall(Chain);
693 if (Chain.getOpcode() == X86ISD::TAILCALL) {
694 SDOperand TailCall = Chain;
695 SDOperand TargetAddress = TailCall.getOperand(1);
696 SDOperand StackAdjustment = TailCall.getOperand(2);
697 assert ( ((TargetAddress.getOpcode() == ISD::Register &&
698 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
699 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
700 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
701 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
702 "Expecting an global address, external symbol, or register");
703 assert( StackAdjustment.getOpcode() == ISD::Constant &&
704 "Expecting a const value");
705
706 SmallVector<SDOperand,8> Operands;
707 Operands.push_back(Chain.getOperand(0));
708 Operands.push_back(TargetAddress);
709 Operands.push_back(StackAdjustment);
710 // Copy registers used by the call. Last operand is a flag so it is not
711 // copied.
Arnold Schwaighofer10202b32007-10-16 09:05:00 +0000712 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000713 Operands.push_back(Chain.getOperand(i));
714 }
Arnold Schwaighofer10202b32007-10-16 09:05:00 +0000715 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
716 Operands.size());
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000717 }
718
719 // Regular return.
720 SDOperand Flag;
721
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000722 // Copy the result values into the output registers.
723 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
724 RVLocs[0].getLocReg() != X86::ST0) {
725 for (unsigned i = 0; i != RVLocs.size(); ++i) {
726 CCValAssign &VA = RVLocs[i];
727 assert(VA.isRegLoc() && "Can only return in registers!");
728 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
729 Flag);
730 Flag = Chain.getValue(1);
731 }
732 } else {
733 // We need to handle a destination of ST0 specially, because it isn't really
734 // a register.
735 SDOperand Value = Op.getOperand(1);
736
737 // If this is an FP return with ScalarSSE, we need to move the value from
738 // an XMM register onto the fp-stack.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000739 if ((X86ScalarSSEf32 && RVLocs[0].getValVT()==MVT::f32) ||
740 (X86ScalarSSEf64 && RVLocs[0].getValVT()==MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 SDOperand MemLoc;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000742
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743 // If this is a load into a scalarsse value, don't store the loaded value
744 // back to the stack, only to reload it: just replace the scalar-sse load.
745 if (ISD::isNON_EXTLoad(Value.Val) &&
746 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
747 Chain = Value.getOperand(0);
748 MemLoc = Value.getOperand(1);
749 } else {
750 // Spill the value to memory and reload it into top of stack.
751 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
752 MachineFunction &MF = DAG.getMachineFunction();
753 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
754 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
755 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
756 }
757 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
758 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
759 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
760 Chain = Value.getValue(1);
761 }
762
763 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
764 SDOperand Ops[] = { Chain, Value };
765 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
766 Flag = Chain.getValue(1);
767 }
768
769 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
770 if (Flag.Val)
771 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
772 else
773 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
774}
775
776
777/// LowerCallResult - Lower the result values of an ISD::CALL into the
778/// appropriate copies out of appropriate physical registers. This assumes that
779/// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
780/// being lowered. The returns a SDNode with the same number of values as the
781/// ISD::CALL.
782SDNode *X86TargetLowering::
783LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
784 unsigned CallingConv, SelectionDAG &DAG) {
785
786 // Assign locations to each value returned by this call.
787 SmallVector<CCValAssign, 16> RVLocs;
788 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
789 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
790 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
791
792
793 SmallVector<SDOperand, 8> ResultVals;
794
795 // Copy all of the result registers out of their specified physreg.
796 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
797 for (unsigned i = 0; i != RVLocs.size(); ++i) {
798 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
799 RVLocs[i].getValVT(), InFlag).getValue(1);
800 InFlag = Chain.getValue(2);
801 ResultVals.push_back(Chain.getValue(0));
802 }
803 } else {
804 // Copies from the FP stack are special, as ST0 isn't a valid register
805 // before the fp stackifier runs.
806
807 // Copy ST0 into an RFP register with FP_GET_RESULT.
808 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
809 SDOperand GROps[] = { Chain, InFlag };
810 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
811 Chain = RetVal.getValue(1);
812 InFlag = RetVal.getValue(2);
813
814 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
815 // an XMM register.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000816 if ((X86ScalarSSEf32 && RVLocs[0].getValVT() == MVT::f32) ||
817 (X86ScalarSSEf64 && RVLocs[0].getValVT() == MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000818 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
819 // shouldn't be necessary except that RFP cannot be live across
820 // multiple blocks. When stackifier is fixed, they can be uncoupled.
821 MachineFunction &MF = DAG.getMachineFunction();
822 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
823 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
824 SDOperand Ops[] = {
825 Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
826 };
827 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
828 RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
829 Chain = RetVal.getValue(1);
830 }
831 ResultVals.push_back(RetVal);
832 }
833
834 // Merge everything together with a MERGE_VALUES node.
835 ResultVals.push_back(Chain);
836 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
837 &ResultVals[0], ResultVals.size()).Val;
838}
839
840
841//===----------------------------------------------------------------------===//
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000842// C & StdCall & Fast Calling Convention implementation
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843//===----------------------------------------------------------------------===//
844// StdCall calling convention seems to be standard for many Windows' API
845// routines and around. It differs from C calling convention just a little:
846// callee should clean up the stack, not caller. Symbols should be also
847// decorated in some fancy way :) It doesn't support any vector arguments.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000848// For info on fast calling convention see Fast Calling Convention (tail call)
849// implementation LowerX86_32FastCCCallTo.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850
851/// AddLiveIn - This helper function adds the specified physical register to the
852/// MachineFunction as a live in value. It also creates a corresponding virtual
853/// register for it.
854static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
855 const TargetRegisterClass *RC) {
856 assert(RC->contains(PReg) && "Not the correct regclass!");
857 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
858 MF.addLiveIn(PReg, VReg);
859 return VReg;
860}
861
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000862// align stack arguments according to platform alignment needed for tail calls
863unsigned GetAlignedArgumentStackSize(unsigned StackSize, SelectionDAG& DAG);
864
Rafael Espindola03cbeb72007-09-14 15:48:13 +0000865SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
866 const CCValAssign &VA,
867 MachineFrameInfo *MFI,
868 SDOperand Root, unsigned i) {
869 // Create the nodes corresponding to a load from this parameter slot.
870 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
871 VA.getLocMemOffset());
872 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
873
874 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
875
876 if (Flags & ISD::ParamFlags::ByVal)
877 return FIN;
878 else
879 return DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0);
880}
881
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000882SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
883 bool isStdCall) {
884 unsigned NumArgs = Op.Val->getNumValues() - 1;
885 MachineFunction &MF = DAG.getMachineFunction();
886 MachineFrameInfo *MFI = MF.getFrameInfo();
887 SDOperand Root = Op.getOperand(0);
888 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000889 unsigned CC = MF.getFunction()->getCallingConv();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000890 // Assign locations to all of the incoming arguments.
891 SmallVector<CCValAssign, 16> ArgLocs;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000892 CCState CCInfo(CC, isVarArg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000894 // Check for possible tail call calling convention.
895 if (CC == CallingConv::Fast && PerformTailCallOpt)
896 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_TailCall);
897 else
898 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
899
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900 SmallVector<SDOperand, 8> ArgValues;
901 unsigned LastVal = ~0U;
902 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
903 CCValAssign &VA = ArgLocs[i];
904 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
905 // places.
906 assert(VA.getValNo() != LastVal &&
907 "Don't support value assigned to multiple locs yet");
908 LastVal = VA.getValNo();
909
910 if (VA.isRegLoc()) {
911 MVT::ValueType RegVT = VA.getLocVT();
912 TargetRegisterClass *RC;
913 if (RegVT == MVT::i32)
914 RC = X86::GR32RegisterClass;
915 else {
916 assert(MVT::isVector(RegVT));
917 RC = X86::VR128RegisterClass;
918 }
919
920 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
921 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
922
923 // If this is an 8 or 16-bit value, it is really passed promoted to 32
924 // bits. Insert an assert[sz]ext to capture this, then truncate to the
925 // right size.
926 if (VA.getLocInfo() == CCValAssign::SExt)
927 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
928 DAG.getValueType(VA.getValVT()));
929 else if (VA.getLocInfo() == CCValAssign::ZExt)
930 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
931 DAG.getValueType(VA.getValVT()));
932
933 if (VA.getLocInfo() != CCValAssign::Full)
934 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
935
936 ArgValues.push_back(ArgValue);
937 } else {
938 assert(VA.isMemLoc());
Rafael Espindola03cbeb72007-09-14 15:48:13 +0000939 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000940 }
941 }
942
943 unsigned StackSize = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000944 // align stack specially for tail calls
945 if (CC==CallingConv::Fast)
946 StackSize = GetAlignedArgumentStackSize(StackSize,DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947
948 ArgValues.push_back(Root);
949
950 // If the function takes variable number of arguments, make a frame index for
951 // the start of the first vararg value... for expansion of llvm.va_start.
952 if (isVarArg)
953 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
954
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000955 // Tail call calling convention (CallingConv::Fast) does not support varargs.
956 assert( !(isVarArg && CC == CallingConv::Fast) &&
957 "CallingConv::Fast does not support varargs.");
958
959 if (isStdCall && !isVarArg &&
960 (CC==CallingConv::Fast && PerformTailCallOpt || CC!=CallingConv::Fast)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961 BytesToPopOnReturn = StackSize; // Callee pops everything..
962 BytesCallerReserves = 0;
963 } else {
964 BytesToPopOnReturn = 0; // Callee pops nothing.
965
966 // If this is an sret function, the return should pop the hidden pointer.
967 if (NumArgs &&
968 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
969 ISD::ParamFlags::StructReturn))
970 BytesToPopOnReturn = 4;
971
972 BytesCallerReserves = StackSize;
973 }
Anton Korobeynikove844e472007-08-15 17:12:32 +0000974
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000975 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000976
Anton Korobeynikove844e472007-08-15 17:12:32 +0000977 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
978 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000979
980 // Return the new list of results.
981 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
982 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
983}
984
985SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
986 unsigned CC) {
987 SDOperand Chain = Op.getOperand(0);
988 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989 SDOperand Callee = Op.getOperand(4);
990 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000991
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992 // Analyze operands of the call, assigning locations to each operand.
993 SmallVector<CCValAssign, 16> ArgLocs;
994 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000995 if(CC==CallingConv::Fast && PerformTailCallOpt)
996 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
997 else
998 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000999
1000 // Get a count of how many bytes are to be pushed on the stack.
1001 unsigned NumBytes = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001002 if (CC==CallingConv::Fast)
1003 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001004
1005 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1006
1007 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1008 SmallVector<SDOperand, 8> MemOpChains;
1009
1010 SDOperand StackPtr;
1011
1012 // Walk the register/memloc assignments, inserting copies/loads.
1013 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1014 CCValAssign &VA = ArgLocs[i];
1015 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1016
1017 // Promote the value if needed.
1018 switch (VA.getLocInfo()) {
1019 default: assert(0 && "Unknown loc info!");
1020 case CCValAssign::Full: break;
1021 case CCValAssign::SExt:
1022 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1023 break;
1024 case CCValAssign::ZExt:
1025 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1026 break;
1027 case CCValAssign::AExt:
1028 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1029 break;
1030 }
1031
1032 if (VA.isRegLoc()) {
1033 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1034 } else {
1035 assert(VA.isMemLoc());
1036 if (StackPtr.Val == 0)
1037 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindola007b7142007-09-21 15:50:22 +00001038
1039 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1040 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041 }
1042 }
1043
1044 // If the first argument is an sret pointer, remember it.
1045 bool isSRet = NumOps &&
1046 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
1047 ISD::ParamFlags::StructReturn);
1048
1049 if (!MemOpChains.empty())
1050 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1051 &MemOpChains[0], MemOpChains.size());
1052
1053 // Build a sequence of copy-to-reg nodes chained together with token chain
1054 // and flag operands which copy the outgoing args into registers.
1055 SDOperand InFlag;
1056 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1057 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1058 InFlag);
1059 InFlag = Chain.getValue(1);
1060 }
1061
1062 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1063 // GOT pointer.
1064 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1065 Subtarget->isPICStyleGOT()) {
1066 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1067 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1068 InFlag);
1069 InFlag = Chain.getValue(1);
1070 }
1071
1072 // If the callee is a GlobalAddress node (quite common, every direct call is)
1073 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1074 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1075 // We should use extra load for direct calls to dllimported functions in
1076 // non-JIT mode.
1077 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1078 getTargetMachine(), true))
1079 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1080 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1081 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1082
1083 // Returns a chain & a flag for retval copy to use.
1084 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1085 SmallVector<SDOperand, 8> Ops;
1086 Ops.push_back(Chain);
1087 Ops.push_back(Callee);
1088
1089 // Add argument registers to the end of the list so that they are known live
1090 // into the call.
1091 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1092 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1093 RegsToPass[i].second.getValueType()));
1094
1095 // Add an implicit use GOT pointer in EBX.
1096 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1097 Subtarget->isPICStyleGOT())
1098 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1099
1100 if (InFlag.Val)
1101 Ops.push_back(InFlag);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001102
1103 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001104 InFlag = Chain.getValue(1);
1105
1106 // Create the CALLSEQ_END node.
1107 unsigned NumBytesForCalleeToPush = 0;
1108
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001109 if (CC == CallingConv::X86_StdCall ||
1110 (CC == CallingConv::Fast && PerformTailCallOpt)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001111 if (isVarArg)
1112 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1113 else
1114 NumBytesForCalleeToPush = NumBytes;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001115 assert(!(isVarArg && CC==CallingConv::Fast) &&
1116 "CallingConv::Fast does not support varargs.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001117 } else {
1118 // If this is is a call to a struct-return function, the callee
1119 // pops the hidden struct pointer, so we have to push it back.
1120 // This is common for Darwin/X86, Linux & Mingw32 targets.
1121 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1122 }
1123
1124 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1125 Ops.clear();
1126 Ops.push_back(Chain);
1127 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1128 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
1129 Ops.push_back(InFlag);
1130 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1131 InFlag = Chain.getValue(1);
1132
1133 // Handle result values, copying them out of physregs into vregs that we
1134 // return.
1135 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1136}
1137
1138
1139//===----------------------------------------------------------------------===//
1140// FastCall Calling Convention implementation
1141//===----------------------------------------------------------------------===//
1142//
1143// The X86 'fastcall' calling convention passes up to two integer arguments in
1144// registers (an appropriate portion of ECX/EDX), passes arguments in C order,
1145// and requires that the callee pop its arguments off the stack (allowing proper
1146// tail calls), and has the same return value conventions as C calling convs.
1147//
1148// This calling convention always arranges for the callee pop value to be 8n+4
1149// bytes, which is needed for tail recursion elimination and stack alignment
1150// reasons.
1151SDOperand
1152X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
1153 MachineFunction &MF = DAG.getMachineFunction();
1154 MachineFrameInfo *MFI = MF.getFrameInfo();
1155 SDOperand Root = Op.getOperand(0);
1156 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1157
1158 // Assign locations to all of the incoming arguments.
1159 SmallVector<CCValAssign, 16> ArgLocs;
1160 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
1161 getTargetMachine(), ArgLocs);
1162 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
1163
1164 SmallVector<SDOperand, 8> ArgValues;
1165 unsigned LastVal = ~0U;
1166 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1167 CCValAssign &VA = ArgLocs[i];
1168 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1169 // places.
1170 assert(VA.getValNo() != LastVal &&
1171 "Don't support value assigned to multiple locs yet");
1172 LastVal = VA.getValNo();
1173
1174 if (VA.isRegLoc()) {
1175 MVT::ValueType RegVT = VA.getLocVT();
1176 TargetRegisterClass *RC;
1177 if (RegVT == MVT::i32)
1178 RC = X86::GR32RegisterClass;
1179 else {
1180 assert(MVT::isVector(RegVT));
1181 RC = X86::VR128RegisterClass;
1182 }
1183
1184 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1185 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1186
1187 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1188 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1189 // right size.
1190 if (VA.getLocInfo() == CCValAssign::SExt)
1191 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1192 DAG.getValueType(VA.getValVT()));
1193 else if (VA.getLocInfo() == CCValAssign::ZExt)
1194 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1195 DAG.getValueType(VA.getValVT()));
1196
1197 if (VA.getLocInfo() != CCValAssign::Full)
1198 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1199
1200 ArgValues.push_back(ArgValue);
1201 } else {
1202 assert(VA.isMemLoc());
Rafael Espindolab53ef122007-09-21 14:55:38 +00001203 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 }
1205 }
1206
1207 ArgValues.push_back(Root);
1208
1209 unsigned StackSize = CCInfo.getNextStackOffset();
1210
1211 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1212 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001213 // arguments and the arguments after the retaddr has been pushed are
1214 // aligned.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001215 if ((StackSize & 7) == 0)
1216 StackSize += 4;
1217 }
1218
1219 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1220 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001221 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
1222 BytesCallerReserves = 0;
1223
Anton Korobeynikove844e472007-08-15 17:12:32 +00001224 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1225 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001226
1227 // Return the new list of results.
1228 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1229 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1230}
1231
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001232SDOperand
1233X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1234 const SDOperand &StackPtr,
1235 const CCValAssign &VA,
1236 SDOperand Chain,
1237 SDOperand Arg) {
1238 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1239 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1240 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1241 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1242 if (Flags & ISD::ParamFlags::ByVal) {
1243 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1244 ISD::ParamFlags::ByValAlignOffs);
1245
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001246 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1247 ISD::ParamFlags::ByValSizeOffs;
1248
1249 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1250 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
Rafael Espindola80825902007-10-19 10:41:11 +00001251 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i1);
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001252
Rafael Espindola80825902007-10-19 10:41:11 +00001253 return DAG.getMemcpy(Chain, PtrOff, Arg, SizeNode, AlignNode,
1254 AlwaysInline);
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001255 } else {
1256 return DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1257 }
1258}
1259
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1261 unsigned CC) {
1262 SDOperand Chain = Op.getOperand(0);
1263 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1264 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1265 SDOperand Callee = Op.getOperand(4);
1266
1267 // Analyze operands of the call, assigning locations to each operand.
1268 SmallVector<CCValAssign, 16> ArgLocs;
1269 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1270 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1271
1272 // Get a count of how many bytes are to be pushed on the stack.
1273 unsigned NumBytes = CCInfo.getNextStackOffset();
1274
1275 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1276 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001277 // arguments and the arguments after the retaddr has been pushed are
1278 // aligned.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001279 if ((NumBytes & 7) == 0)
1280 NumBytes += 4;
1281 }
1282
1283 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1284
1285 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1286 SmallVector<SDOperand, 8> MemOpChains;
1287
1288 SDOperand StackPtr;
1289
1290 // Walk the register/memloc assignments, inserting copies/loads.
1291 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1292 CCValAssign &VA = ArgLocs[i];
1293 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1294
1295 // Promote the value if needed.
1296 switch (VA.getLocInfo()) {
1297 default: assert(0 && "Unknown loc info!");
1298 case CCValAssign::Full: break;
1299 case CCValAssign::SExt:
1300 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1301 break;
1302 case CCValAssign::ZExt:
1303 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1304 break;
1305 case CCValAssign::AExt:
1306 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1307 break;
1308 }
1309
1310 if (VA.isRegLoc()) {
1311 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1312 } else {
1313 assert(VA.isMemLoc());
1314 if (StackPtr.Val == 0)
1315 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindola007b7142007-09-21 15:50:22 +00001316
1317 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1318 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001319 }
1320 }
1321
1322 if (!MemOpChains.empty())
1323 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1324 &MemOpChains[0], MemOpChains.size());
1325
1326 // Build a sequence of copy-to-reg nodes chained together with token chain
1327 // and flag operands which copy the outgoing args into registers.
1328 SDOperand InFlag;
1329 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1330 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1331 InFlag);
1332 InFlag = Chain.getValue(1);
1333 }
1334
1335 // If the callee is a GlobalAddress node (quite common, every direct call is)
1336 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1337 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1338 // We should use extra load for direct calls to dllimported functions in
1339 // non-JIT mode.
1340 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1341 getTargetMachine(), true))
1342 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1343 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1344 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1345
1346 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1347 // GOT pointer.
1348 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1349 Subtarget->isPICStyleGOT()) {
1350 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1351 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1352 InFlag);
1353 InFlag = Chain.getValue(1);
1354 }
1355
1356 // Returns a chain & a flag for retval copy to use.
1357 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1358 SmallVector<SDOperand, 8> Ops;
1359 Ops.push_back(Chain);
1360 Ops.push_back(Callee);
1361
1362 // Add argument registers to the end of the list so that they are known live
1363 // into the call.
1364 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1365 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1366 RegsToPass[i].second.getValueType()));
1367
1368 // Add an implicit use GOT pointer in EBX.
1369 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1370 Subtarget->isPICStyleGOT())
1371 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1372
1373 if (InFlag.Val)
1374 Ops.push_back(InFlag);
1375
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001376 assert(isTailCall==false && "no tail call here");
1377 Chain = DAG.getNode(X86ISD::CALL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001378 NodeTys, &Ops[0], Ops.size());
1379 InFlag = Chain.getValue(1);
1380
1381 // Returns a flag for retval copy to use.
1382 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1383 Ops.clear();
1384 Ops.push_back(Chain);
1385 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1386 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1387 Ops.push_back(InFlag);
1388 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1389 InFlag = Chain.getValue(1);
1390
1391 // Handle result values, copying them out of physregs into vregs that we
1392 // return.
1393 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1394}
1395
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001396//===----------------------------------------------------------------------===//
1397// Fast Calling Convention (tail call) implementation
1398//===----------------------------------------------------------------------===//
1399
1400// Like std call, callee cleans arguments, convention except that ECX is
1401// reserved for storing the tail called function address. Only 2 registers are
1402// free for argument passing (inreg). Tail call optimization is performed
1403// provided:
1404// * tailcallopt is enabled
1405// * caller/callee are fastcc
1406// * elf/pic is disabled OR
1407// * elf/pic enabled + callee is in module + callee has
1408// visibility protected or hidden
Arnold Schwaighofer373e8652007-10-12 21:30:57 +00001409// To keep the stack aligned according to platform abi the function
1410// GetAlignedArgumentStackSize ensures that argument delta is always multiples
1411// of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001412// If a tail called function callee has more arguments than the caller the
1413// caller needs to make sure that there is room to move the RETADDR to. This is
Arnold Schwaighofer373e8652007-10-12 21:30:57 +00001414// achieved by reserving an area the size of the argument delta right after the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001415// original REtADDR, but before the saved framepointer or the spilled registers
1416// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1417// stack layout:
1418// arg1
1419// arg2
1420// RETADDR
1421// [ new RETADDR
1422// move area ]
1423// (possible EBP)
1424// ESI
1425// EDI
1426// local1 ..
1427
1428/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1429/// for a 16 byte align requirement.
1430unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1431 SelectionDAG& DAG) {
1432 if (PerformTailCallOpt) {
1433 MachineFunction &MF = DAG.getMachineFunction();
1434 const TargetMachine &TM = MF.getTarget();
1435 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1436 unsigned StackAlignment = TFI.getStackAlignment();
1437 uint64_t AlignMask = StackAlignment - 1;
1438 int64_t Offset = StackSize;
1439 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1440 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1441 // Number smaller than 12 so just add the difference.
1442 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1443 } else {
1444 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1445 Offset = ((~AlignMask) & Offset) + StackAlignment +
1446 (StackAlignment-SlotSize);
1447 }
1448 StackSize = Offset;
1449 }
1450 return StackSize;
1451}
1452
1453/// IsEligibleForTailCallElimination - Check to see whether the next instruction
1454// following the call is a return. A function is eligible if caller/callee
1455// calling conventions match, currently only fastcc supports tail calls, and the
1456// function CALL is immediatly followed by a RET.
1457bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1458 SDOperand Ret,
1459 SelectionDAG& DAG) const {
1460 bool IsEligible = false;
1461
1462 // Check whether CALL node immediatly preceeds the RET node and whether the
1463 // return uses the result of the node or is a void return.
1464 if ((Ret.getNumOperands() == 1 &&
1465 (Ret.getOperand(0)== SDOperand(Call.Val,1) ||
1466 Ret.getOperand(0)== SDOperand(Call.Val,0))) ||
1467 (Ret.getOperand(0)== SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1468 Ret.getOperand(1)== SDOperand(Call.Val,0))) {
1469 MachineFunction &MF = DAG.getMachineFunction();
1470 unsigned CallerCC = MF.getFunction()->getCallingConv();
1471 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1472 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1473 SDOperand Callee = Call.getOperand(4);
1474 // On elf/pic %ebx needs to be livein.
1475 if(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1476 Subtarget->isPICStyleGOT()) {
1477 // Can only do local tail calls with PIC.
1478 GlobalValue * GV = 0;
1479 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1480 if(G != 0 &&
1481 (GV = G->getGlobal()) &&
1482 (GV->hasHiddenVisibility() || GV->hasProtectedVisibility()))
1483 IsEligible=true;
1484 } else {
1485 IsEligible=true;
1486 }
1487 }
1488 }
1489 return IsEligible;
1490}
1491
1492SDOperand X86TargetLowering::LowerX86_TailCallTo(SDOperand Op,
1493 SelectionDAG &DAG,
1494 unsigned CC) {
1495 SDOperand Chain = Op.getOperand(0);
1496 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1497 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1498 SDOperand Callee = Op.getOperand(4);
1499 bool is64Bit = Subtarget->is64Bit();
1500
1501 assert(isTailCall && PerformTailCallOpt && "Should only emit tail calls.");
1502
1503 // Analyze operands of the call, assigning locations to each operand.
1504 SmallVector<CCValAssign, 16> ArgLocs;
1505 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1506 if (is64Bit)
1507 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1508 else
1509 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1510
1511
1512 // Lower arguments at fp - stackoffset + fpdiff.
1513 MachineFunction &MF = DAG.getMachineFunction();
1514
1515 unsigned NumBytesToBePushed =
1516 GetAlignedArgumentStackSize(CCInfo.getNextStackOffset(), DAG);
1517
1518 unsigned NumBytesCallerPushed =
1519 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1520 int FPDiff = NumBytesCallerPushed - NumBytesToBePushed;
1521
1522 // Set the delta of movement of the returnaddr stackslot.
1523 // But only set if delta is greater than previous delta.
1524 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1525 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1526
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001527 Chain = DAG.
1528 getCALLSEQ_START(Chain, DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1529
1530 // Adjust the Return address stack slot.
1531 SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001532 if (FPDiff) {
1533 MVT::ValueType VT = is64Bit ? MVT::i64 : MVT::i32;
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001534 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1535 // Load the "old" Return address.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001536 RetAddrFrIdx =
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001537 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1538 // Calculate the new stack slot for the return address.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001539 int SlotSize = is64Bit ? 8 : 4;
1540 int NewReturnAddrFI =
1541 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001542 NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1543 Chain = SDOperand(RetAddrFrIdx.Val, 1);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001544 }
1545
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001546 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1547 SmallVector<SDOperand, 8> MemOpChains;
1548 SmallVector<SDOperand, 8> MemOpChains2;
1549 SDOperand FramePtr, StackPtr;
1550 SDOperand PtrOff;
1551 SDOperand FIN;
1552 int FI = 0;
1553
1554 // Walk the register/memloc assignments, inserting copies/loads. Lower
1555 // arguments first to the stack slot where they would normally - in case of a
1556 // normal function call - be.
1557 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1558 CCValAssign &VA = ArgLocs[i];
1559 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1560
1561 // Promote the value if needed.
1562 switch (VA.getLocInfo()) {
1563 default: assert(0 && "Unknown loc info!");
1564 case CCValAssign::Full: break;
1565 case CCValAssign::SExt:
1566 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1567 break;
1568 case CCValAssign::ZExt:
1569 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1570 break;
1571 case CCValAssign::AExt:
1572 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1573 break;
1574 }
1575
1576 if (VA.isRegLoc()) {
1577 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1578 } else {
1579 assert(VA.isMemLoc());
1580 if (StackPtr.Val == 0)
1581 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1582
1583 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1584 Arg));
1585 }
1586 }
1587
1588 if (!MemOpChains.empty())
1589 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1590 &MemOpChains[0], MemOpChains.size());
1591
1592 // Build a sequence of copy-to-reg nodes chained together with token chain
1593 // and flag operands which copy the outgoing args into registers.
1594 SDOperand InFlag;
1595 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1596 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1597 InFlag);
1598 InFlag = Chain.getValue(1);
1599 }
1600 InFlag = SDOperand();
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001601
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001602 // Copy from stack slots to stack slot of a tail called function. This needs
1603 // to be done because if we would lower the arguments directly to their real
1604 // stack slot we might end up overwriting each other.
1605 // TODO: To make this more efficient (sometimes saving a store/load) we could
1606 // analyse the arguments and emit this store/load/store sequence only for
1607 // arguments which would be overwritten otherwise.
1608 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1609 CCValAssign &VA = ArgLocs[i];
1610 if (!VA.isRegLoc()) {
1611 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1612 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1613
1614 // Get source stack slot.
1615 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1616 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1617 // Create frame index.
1618 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1619 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1620 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1621 FIN = DAG.getFrameIndex(FI, MVT::i32);
1622 if (Flags & ISD::ParamFlags::ByVal) {
1623 // Copy relative to framepointer.
1624 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1625 ISD::ParamFlags::ByValAlignOffs);
1626
1627 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1628 ISD::ParamFlags::ByValSizeOffs;
1629
1630 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1631 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1632 // Copy relative to framepointer.
1633 MemOpChains2.push_back(DAG.getNode(ISD::MEMCPY, MVT::Other, Chain, FIN,
1634 PtrOff, SizeNode, AlignNode));
1635 } else {
1636 SDOperand LoadedArg = DAG.getLoad(VA.getValVT(), Chain, PtrOff, NULL,0);
1637 // Store relative to framepointer.
1638 MemOpChains2.push_back(DAG.getStore(Chain, LoadedArg, FIN, NULL, 0));
1639 }
1640 }
1641 }
1642
1643 if (!MemOpChains2.empty())
1644 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1645 &MemOpChains2[0], MemOpChains.size());
1646
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001647 // Store the return address to the appropriate stack slot.
1648 if (FPDiff)
1649 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1650
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001651 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1652 // GOT pointer.
1653 // Does not work with tail call since ebx is not restored correctly by
1654 // tailcaller. TODO: at least for x86 - verify for x86-64
1655
1656 // If the callee is a GlobalAddress node (quite common, every direct call is)
1657 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1658 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1659 // We should use extra load for direct calls to dllimported functions in
1660 // non-JIT mode.
1661 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1662 getTargetMachine(), true))
1663 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1664 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1665 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1666 else {
1667 assert(Callee.getOpcode() == ISD::LOAD &&
1668 "Function destination must be loaded into virtual register");
1669 unsigned Opc = is64Bit ? X86::R9 : X86::ECX;
1670
1671 Chain = DAG.getCopyToReg(Chain,
1672 DAG.getRegister(Opc, getPointerTy()) ,
1673 Callee,InFlag);
1674 Callee = DAG.getRegister(Opc, getPointerTy());
1675 // Add register as live out.
1676 DAG.getMachineFunction().addLiveOut(Opc);
1677 }
1678
1679 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1680 SmallVector<SDOperand, 8> Ops;
1681
1682 Ops.push_back(Chain);
1683 Ops.push_back(DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1684 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1685 if (InFlag.Val)
1686 Ops.push_back(InFlag);
1687 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1688 InFlag = Chain.getValue(1);
1689
1690 // Returns a chain & a flag for retval copy to use.
1691 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1692 Ops.clear();
1693 Ops.push_back(Chain);
1694 Ops.push_back(Callee);
1695 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1696 // Add argument registers to the end of the list so that they are known live
1697 // into the call.
1698 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1699 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1700 RegsToPass[i].second.getValueType()));
1701 if (InFlag.Val)
1702 Ops.push_back(InFlag);
1703 assert(InFlag.Val &&
1704 "Flag must be set. Depend on flag being set in LowerRET");
1705 Chain = DAG.getNode(X86ISD::TAILCALL,
1706 Op.Val->getVTList(), &Ops[0], Ops.size());
1707
1708 return SDOperand(Chain.Val, Op.ResNo);
1709}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001710
1711//===----------------------------------------------------------------------===//
1712// X86-64 C Calling Convention implementation
1713//===----------------------------------------------------------------------===//
1714
1715SDOperand
1716X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1717 MachineFunction &MF = DAG.getMachineFunction();
1718 MachineFrameInfo *MFI = MF.getFrameInfo();
1719 SDOperand Root = Op.getOperand(0);
1720 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001721 unsigned CC= MF.getFunction()->getCallingConv();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001722
1723 static const unsigned GPR64ArgRegs[] = {
1724 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1725 };
1726 static const unsigned XMMArgRegs[] = {
1727 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1728 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1729 };
1730
1731
1732 // Assign locations to all of the incoming arguments.
1733 SmallVector<CCValAssign, 16> ArgLocs;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001734 CCState CCInfo(CC, isVarArg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001735 getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001736 if (CC == CallingConv::Fast && PerformTailCallOpt)
1737 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_TailCall);
1738 else
1739 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001740
1741 SmallVector<SDOperand, 8> ArgValues;
1742 unsigned LastVal = ~0U;
1743 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1744 CCValAssign &VA = ArgLocs[i];
1745 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1746 // places.
1747 assert(VA.getValNo() != LastVal &&
1748 "Don't support value assigned to multiple locs yet");
1749 LastVal = VA.getValNo();
1750
1751 if (VA.isRegLoc()) {
1752 MVT::ValueType RegVT = VA.getLocVT();
1753 TargetRegisterClass *RC;
1754 if (RegVT == MVT::i32)
1755 RC = X86::GR32RegisterClass;
1756 else if (RegVT == MVT::i64)
1757 RC = X86::GR64RegisterClass;
1758 else if (RegVT == MVT::f32)
1759 RC = X86::FR32RegisterClass;
1760 else if (RegVT == MVT::f64)
1761 RC = X86::FR64RegisterClass;
1762 else {
1763 assert(MVT::isVector(RegVT));
1764 if (MVT::getSizeInBits(RegVT) == 64) {
1765 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1766 RegVT = MVT::i64;
1767 } else
1768 RC = X86::VR128RegisterClass;
1769 }
1770
1771 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1772 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1773
1774 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1775 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1776 // right size.
1777 if (VA.getLocInfo() == CCValAssign::SExt)
1778 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1779 DAG.getValueType(VA.getValVT()));
1780 else if (VA.getLocInfo() == CCValAssign::ZExt)
1781 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1782 DAG.getValueType(VA.getValVT()));
1783
1784 if (VA.getLocInfo() != CCValAssign::Full)
1785 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1786
1787 // Handle MMX values passed in GPRs.
1788 if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1789 MVT::getSizeInBits(RegVT) == 64)
1790 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1791
1792 ArgValues.push_back(ArgValue);
1793 } else {
1794 assert(VA.isMemLoc());
Rafael Espindola03cbeb72007-09-14 15:48:13 +00001795 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796 }
1797 }
1798
1799 unsigned StackSize = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001800 if (CC==CallingConv::Fast)
1801 StackSize =GetAlignedArgumentStackSize(StackSize, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001802
1803 // If the function takes variable number of arguments, make a frame index for
1804 // the start of the first vararg value... for expansion of llvm.va_start.
1805 if (isVarArg) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001806 assert(CC!=CallingConv::Fast
1807 && "Var arg not supported with calling convention fastcc");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001808 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1809 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1810
1811 // For X86-64, if there are vararg parameters that are passed via
1812 // registers, then we must store them to their spots on the stack so they
1813 // may be loaded by deferencing the result of va_next.
1814 VarArgsGPOffset = NumIntRegs * 8;
1815 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1816 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1817 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1818
1819 // Store the integer parameter registers.
1820 SmallVector<SDOperand, 8> MemOps;
1821 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1822 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1823 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1824 for (; NumIntRegs != 6; ++NumIntRegs) {
1825 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1826 X86::GR64RegisterClass);
1827 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1828 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1829 MemOps.push_back(Store);
1830 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1831 DAG.getConstant(8, getPointerTy()));
1832 }
1833
1834 // Now store the XMM (fp + vector) parameter registers.
1835 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1836 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1837 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1838 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1839 X86::VR128RegisterClass);
1840 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1841 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1842 MemOps.push_back(Store);
1843 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1844 DAG.getConstant(16, getPointerTy()));
1845 }
1846 if (!MemOps.empty())
1847 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1848 &MemOps[0], MemOps.size());
1849 }
1850
1851 ArgValues.push_back(Root);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001852 // Tail call convention (fastcc) needs callee pop.
Evan Cheng778fa0f2007-10-14 10:09:39 +00001853 if (CC == CallingConv::Fast && PerformTailCallOpt) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001854 BytesToPopOnReturn = StackSize; // Callee pops everything.
1855 BytesCallerReserves = 0;
1856 } else {
1857 BytesToPopOnReturn = 0; // Callee pops nothing.
1858 BytesCallerReserves = StackSize;
1859 }
Anton Korobeynikove844e472007-08-15 17:12:32 +00001860 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1861 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1862
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001863 // Return the new list of results.
1864 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1865 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1866}
1867
1868SDOperand
1869X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1870 unsigned CC) {
1871 SDOperand Chain = Op.getOperand(0);
1872 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001873 SDOperand Callee = Op.getOperand(4);
1874
1875 // Analyze operands of the call, assigning locations to each operand.
1876 SmallVector<CCValAssign, 16> ArgLocs;
1877 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Evan Cheng778fa0f2007-10-14 10:09:39 +00001878 if (CC==CallingConv::Fast && PerformTailCallOpt)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001879 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1880 else
1881 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001882
1883 // Get a count of how many bytes are to be pushed on the stack.
1884 unsigned NumBytes = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001885 if (CC == CallingConv::Fast)
1886 NumBytes = GetAlignedArgumentStackSize(NumBytes,DAG);
1887
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001888 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1889
1890 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1891 SmallVector<SDOperand, 8> MemOpChains;
1892
1893 SDOperand StackPtr;
1894
1895 // Walk the register/memloc assignments, inserting copies/loads.
1896 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1897 CCValAssign &VA = ArgLocs[i];
1898 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1899
1900 // Promote the value if needed.
1901 switch (VA.getLocInfo()) {
1902 default: assert(0 && "Unknown loc info!");
1903 case CCValAssign::Full: break;
1904 case CCValAssign::SExt:
1905 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1906 break;
1907 case CCValAssign::ZExt:
1908 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1909 break;
1910 case CCValAssign::AExt:
1911 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1912 break;
1913 }
1914
1915 if (VA.isRegLoc()) {
1916 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1917 } else {
1918 assert(VA.isMemLoc());
1919 if (StackPtr.Val == 0)
1920 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindolab8bcfcd2007-08-20 15:18:24 +00001921
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001922 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1923 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001924 }
1925 }
1926
1927 if (!MemOpChains.empty())
1928 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1929 &MemOpChains[0], MemOpChains.size());
1930
1931 // Build a sequence of copy-to-reg nodes chained together with token chain
1932 // and flag operands which copy the outgoing args into registers.
1933 SDOperand InFlag;
1934 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1935 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1936 InFlag);
1937 InFlag = Chain.getValue(1);
1938 }
1939
1940 if (isVarArg) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001941 assert ( CallingConv::Fast != CC &&
1942 "Var args not supported with calling convention fastcc");
1943
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001944 // From AMD64 ABI document:
1945 // For calls that may call functions that use varargs or stdargs
1946 // (prototype-less calls or calls to functions containing ellipsis (...) in
1947 // the declaration) %al is used as hidden argument to specify the number
1948 // of SSE registers used. The contents of %al do not need to match exactly
1949 // the number of registers, but must be an ubound on the number of SSE
1950 // registers used and is in the range 0 - 8 inclusive.
1951
1952 // Count the number of XMM registers allocated.
1953 static const unsigned XMMArgRegs[] = {
1954 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1955 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1956 };
1957 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1958
1959 Chain = DAG.getCopyToReg(Chain, X86::AL,
1960 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1961 InFlag = Chain.getValue(1);
1962 }
1963
1964 // If the callee is a GlobalAddress node (quite common, every direct call is)
1965 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1966 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1967 // We should use extra load for direct calls to dllimported functions in
1968 // non-JIT mode.
1969 if (getTargetMachine().getCodeModel() != CodeModel::Large
1970 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1971 getTargetMachine(), true))
1972 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1973 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1974 if (getTargetMachine().getCodeModel() != CodeModel::Large)
1975 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1976
1977 // Returns a chain & a flag for retval copy to use.
1978 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1979 SmallVector<SDOperand, 8> Ops;
1980 Ops.push_back(Chain);
1981 Ops.push_back(Callee);
1982
1983 // Add argument registers to the end of the list so that they are known live
1984 // into the call.
1985 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1986 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1987 RegsToPass[i].second.getValueType()));
1988
1989 if (InFlag.Val)
1990 Ops.push_back(InFlag);
1991
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001992 Chain = DAG.getNode(X86ISD::CALL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001993 NodeTys, &Ops[0], Ops.size());
1994 InFlag = Chain.getValue(1);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001995 int NumBytesForCalleeToPush = 0;
Evan Cheng778fa0f2007-10-14 10:09:39 +00001996 if (CC==CallingConv::Fast && PerformTailCallOpt) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001997 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001998 } else {
1999 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2000 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002001 // Returns a flag for retval copy to use.
2002 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2003 Ops.clear();
2004 Ops.push_back(Chain);
2005 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002006 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002007 Ops.push_back(InFlag);
2008 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
2009 InFlag = Chain.getValue(1);
2010
2011 // Handle result values, copying them out of physregs into vregs that we
2012 // return.
2013 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
2014}
2015
2016
2017//===----------------------------------------------------------------------===//
2018// Other Lowering Hooks
2019//===----------------------------------------------------------------------===//
2020
2021
2022SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
Anton Korobeynikove844e472007-08-15 17:12:32 +00002023 MachineFunction &MF = DAG.getMachineFunction();
2024 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2025 int ReturnAddrIndex = FuncInfo->getRAIndex();
2026
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002027 if (ReturnAddrIndex == 0) {
2028 // Set up a frame object for the return address.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002029 if (Subtarget->is64Bit())
2030 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
2031 else
2032 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
Anton Korobeynikove844e472007-08-15 17:12:32 +00002033
2034 FuncInfo->setRAIndex(ReturnAddrIndex);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002035 }
2036
2037 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2038}
2039
2040
2041
2042/// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
2043/// specific condition code. It returns a false if it cannot do a direct
2044/// translation. X86CC is the translated CondCode. LHS/RHS are modified as
2045/// needed.
2046static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2047 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
2048 SelectionDAG &DAG) {
2049 X86CC = X86::COND_INVALID;
2050 if (!isFP) {
2051 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2052 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2053 // X > -1 -> X == 0, jump !sign.
2054 RHS = DAG.getConstant(0, RHS.getValueType());
2055 X86CC = X86::COND_NS;
2056 return true;
2057 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2058 // X < 0 -> X == 0, jump on sign.
2059 X86CC = X86::COND_S;
2060 return true;
Dan Gohman37b34262007-09-17 14:49:27 +00002061 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
2062 // X < 1 -> X <= 0
2063 RHS = DAG.getConstant(0, RHS.getValueType());
2064 X86CC = X86::COND_LE;
2065 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002066 }
2067 }
2068
2069 switch (SetCCOpcode) {
2070 default: break;
2071 case ISD::SETEQ: X86CC = X86::COND_E; break;
2072 case ISD::SETGT: X86CC = X86::COND_G; break;
2073 case ISD::SETGE: X86CC = X86::COND_GE; break;
2074 case ISD::SETLT: X86CC = X86::COND_L; break;
2075 case ISD::SETLE: X86CC = X86::COND_LE; break;
2076 case ISD::SETNE: X86CC = X86::COND_NE; break;
2077 case ISD::SETULT: X86CC = X86::COND_B; break;
2078 case ISD::SETUGT: X86CC = X86::COND_A; break;
2079 case ISD::SETULE: X86CC = X86::COND_BE; break;
2080 case ISD::SETUGE: X86CC = X86::COND_AE; break;
2081 }
2082 } else {
2083 // On a floating point condition, the flags are set as follows:
2084 // ZF PF CF op
2085 // 0 | 0 | 0 | X > Y
2086 // 0 | 0 | 1 | X < Y
2087 // 1 | 0 | 0 | X == Y
2088 // 1 | 1 | 1 | unordered
2089 bool Flip = false;
2090 switch (SetCCOpcode) {
2091 default: break;
2092 case ISD::SETUEQ:
2093 case ISD::SETEQ: X86CC = X86::COND_E; break;
2094 case ISD::SETOLT: Flip = true; // Fallthrough
2095 case ISD::SETOGT:
2096 case ISD::SETGT: X86CC = X86::COND_A; break;
2097 case ISD::SETOLE: Flip = true; // Fallthrough
2098 case ISD::SETOGE:
2099 case ISD::SETGE: X86CC = X86::COND_AE; break;
2100 case ISD::SETUGT: Flip = true; // Fallthrough
2101 case ISD::SETULT:
2102 case ISD::SETLT: X86CC = X86::COND_B; break;
2103 case ISD::SETUGE: Flip = true; // Fallthrough
2104 case ISD::SETULE:
2105 case ISD::SETLE: X86CC = X86::COND_BE; break;
2106 case ISD::SETONE:
2107 case ISD::SETNE: X86CC = X86::COND_NE; break;
2108 case ISD::SETUO: X86CC = X86::COND_P; break;
2109 case ISD::SETO: X86CC = X86::COND_NP; break;
2110 }
2111 if (Flip)
2112 std::swap(LHS, RHS);
2113 }
2114
2115 return X86CC != X86::COND_INVALID;
2116}
2117
2118/// hasFPCMov - is there a floating point cmov for the specific X86 condition
2119/// code. Current x86 isa includes the following FP cmov instructions:
2120/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2121static bool hasFPCMov(unsigned X86CC) {
2122 switch (X86CC) {
2123 default:
2124 return false;
2125 case X86::COND_B:
2126 case X86::COND_BE:
2127 case X86::COND_E:
2128 case X86::COND_P:
2129 case X86::COND_A:
2130 case X86::COND_AE:
2131 case X86::COND_NE:
2132 case X86::COND_NP:
2133 return true;
2134 }
2135}
2136
2137/// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2138/// true if Op is undef or if its value falls within the specified range (L, H].
2139static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2140 if (Op.getOpcode() == ISD::UNDEF)
2141 return true;
2142
2143 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2144 return (Val >= Low && Val < Hi);
2145}
2146
2147/// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2148/// true if Op is undef or if its value equal to the specified value.
2149static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2150 if (Op.getOpcode() == ISD::UNDEF)
2151 return true;
2152 return cast<ConstantSDNode>(Op)->getValue() == Val;
2153}
2154
2155/// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2156/// specifies a shuffle of elements that is suitable for input to PSHUFD.
2157bool X86::isPSHUFDMask(SDNode *N) {
2158 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2159
Dan Gohman7dc19012007-08-02 21:17:01 +00002160 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002161 return false;
2162
2163 // Check if the value doesn't reference the second vector.
2164 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2165 SDOperand Arg = N->getOperand(i);
2166 if (Arg.getOpcode() == ISD::UNDEF) continue;
2167 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Dan Gohman7dc19012007-08-02 21:17:01 +00002168 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002169 return false;
2170 }
2171
2172 return true;
2173}
2174
2175/// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2176/// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2177bool X86::isPSHUFHWMask(SDNode *N) {
2178 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2179
2180 if (N->getNumOperands() != 8)
2181 return false;
2182
2183 // Lower quadword copied in order.
2184 for (unsigned i = 0; i != 4; ++i) {
2185 SDOperand Arg = N->getOperand(i);
2186 if (Arg.getOpcode() == ISD::UNDEF) continue;
2187 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2188 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2189 return false;
2190 }
2191
2192 // Upper quadword shuffled.
2193 for (unsigned i = 4; i != 8; ++i) {
2194 SDOperand Arg = N->getOperand(i);
2195 if (Arg.getOpcode() == ISD::UNDEF) continue;
2196 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2197 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2198 if (Val < 4 || Val > 7)
2199 return false;
2200 }
2201
2202 return true;
2203}
2204
2205/// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2206/// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2207bool X86::isPSHUFLWMask(SDNode *N) {
2208 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2209
2210 if (N->getNumOperands() != 8)
2211 return false;
2212
2213 // Upper quadword copied in order.
2214 for (unsigned i = 4; i != 8; ++i)
2215 if (!isUndefOrEqual(N->getOperand(i), i))
2216 return false;
2217
2218 // Lower quadword shuffled.
2219 for (unsigned i = 0; i != 4; ++i)
2220 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2221 return false;
2222
2223 return true;
2224}
2225
2226/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2227/// specifies a shuffle of elements that is suitable for input to SHUFP*.
2228static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2229 if (NumElems != 2 && NumElems != 4) return false;
2230
2231 unsigned Half = NumElems / 2;
2232 for (unsigned i = 0; i < Half; ++i)
2233 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2234 return false;
2235 for (unsigned i = Half; i < NumElems; ++i)
2236 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2237 return false;
2238
2239 return true;
2240}
2241
2242bool X86::isSHUFPMask(SDNode *N) {
2243 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2244 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2245}
2246
2247/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2248/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2249/// half elements to come from vector 1 (which would equal the dest.) and
2250/// the upper half to come from vector 2.
2251static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2252 if (NumOps != 2 && NumOps != 4) return false;
2253
2254 unsigned Half = NumOps / 2;
2255 for (unsigned i = 0; i < Half; ++i)
2256 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2257 return false;
2258 for (unsigned i = Half; i < NumOps; ++i)
2259 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2260 return false;
2261 return true;
2262}
2263
2264static bool isCommutedSHUFP(SDNode *N) {
2265 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2266 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2267}
2268
2269/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2270/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2271bool X86::isMOVHLPSMask(SDNode *N) {
2272 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2273
2274 if (N->getNumOperands() != 4)
2275 return false;
2276
2277 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2278 return isUndefOrEqual(N->getOperand(0), 6) &&
2279 isUndefOrEqual(N->getOperand(1), 7) &&
2280 isUndefOrEqual(N->getOperand(2), 2) &&
2281 isUndefOrEqual(N->getOperand(3), 3);
2282}
2283
2284/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2285/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2286/// <2, 3, 2, 3>
2287bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2288 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2289
2290 if (N->getNumOperands() != 4)
2291 return false;
2292
2293 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2294 return isUndefOrEqual(N->getOperand(0), 2) &&
2295 isUndefOrEqual(N->getOperand(1), 3) &&
2296 isUndefOrEqual(N->getOperand(2), 2) &&
2297 isUndefOrEqual(N->getOperand(3), 3);
2298}
2299
2300/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2301/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2302bool X86::isMOVLPMask(SDNode *N) {
2303 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2304
2305 unsigned NumElems = N->getNumOperands();
2306 if (NumElems != 2 && NumElems != 4)
2307 return false;
2308
2309 for (unsigned i = 0; i < NumElems/2; ++i)
2310 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2311 return false;
2312
2313 for (unsigned i = NumElems/2; i < NumElems; ++i)
2314 if (!isUndefOrEqual(N->getOperand(i), i))
2315 return false;
2316
2317 return true;
2318}
2319
2320/// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2321/// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2322/// and MOVLHPS.
2323bool X86::isMOVHPMask(SDNode *N) {
2324 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2325
2326 unsigned NumElems = N->getNumOperands();
2327 if (NumElems != 2 && NumElems != 4)
2328 return false;
2329
2330 for (unsigned i = 0; i < NumElems/2; ++i)
2331 if (!isUndefOrEqual(N->getOperand(i), i))
2332 return false;
2333
2334 for (unsigned i = 0; i < NumElems/2; ++i) {
2335 SDOperand Arg = N->getOperand(i + NumElems/2);
2336 if (!isUndefOrEqual(Arg, i + NumElems))
2337 return false;
2338 }
2339
2340 return true;
2341}
2342
2343/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2344/// specifies a shuffle of elements that is suitable for input to UNPCKL.
2345bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2346 bool V2IsSplat = false) {
2347 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2348 return false;
2349
2350 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2351 SDOperand BitI = Elts[i];
2352 SDOperand BitI1 = Elts[i+1];
2353 if (!isUndefOrEqual(BitI, j))
2354 return false;
2355 if (V2IsSplat) {
2356 if (isUndefOrEqual(BitI1, NumElts))
2357 return false;
2358 } else {
2359 if (!isUndefOrEqual(BitI1, j + NumElts))
2360 return false;
2361 }
2362 }
2363
2364 return true;
2365}
2366
2367bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2368 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2369 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2370}
2371
2372/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2373/// specifies a shuffle of elements that is suitable for input to UNPCKH.
2374bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2375 bool V2IsSplat = false) {
2376 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2377 return false;
2378
2379 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2380 SDOperand BitI = Elts[i];
2381 SDOperand BitI1 = Elts[i+1];
2382 if (!isUndefOrEqual(BitI, j + NumElts/2))
2383 return false;
2384 if (V2IsSplat) {
2385 if (isUndefOrEqual(BitI1, NumElts))
2386 return false;
2387 } else {
2388 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2389 return false;
2390 }
2391 }
2392
2393 return true;
2394}
2395
2396bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2397 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2398 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2399}
2400
2401/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2402/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2403/// <0, 0, 1, 1>
2404bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2405 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2406
2407 unsigned NumElems = N->getNumOperands();
2408 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2409 return false;
2410
2411 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2412 SDOperand BitI = N->getOperand(i);
2413 SDOperand BitI1 = N->getOperand(i+1);
2414
2415 if (!isUndefOrEqual(BitI, j))
2416 return false;
2417 if (!isUndefOrEqual(BitI1, j))
2418 return false;
2419 }
2420
2421 return true;
2422}
2423
2424/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2425/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2426/// <2, 2, 3, 3>
2427bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2428 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2429
2430 unsigned NumElems = N->getNumOperands();
2431 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2432 return false;
2433
2434 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2435 SDOperand BitI = N->getOperand(i);
2436 SDOperand BitI1 = N->getOperand(i + 1);
2437
2438 if (!isUndefOrEqual(BitI, j))
2439 return false;
2440 if (!isUndefOrEqual(BitI1, j))
2441 return false;
2442 }
2443
2444 return true;
2445}
2446
2447/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2448/// specifies a shuffle of elements that is suitable for input to MOVSS,
2449/// MOVSD, and MOVD, i.e. setting the lowest element.
2450static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2451 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2452 return false;
2453
2454 if (!isUndefOrEqual(Elts[0], NumElts))
2455 return false;
2456
2457 for (unsigned i = 1; i < NumElts; ++i) {
2458 if (!isUndefOrEqual(Elts[i], i))
2459 return false;
2460 }
2461
2462 return true;
2463}
2464
2465bool X86::isMOVLMask(SDNode *N) {
2466 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2467 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2468}
2469
2470/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2471/// of what x86 movss want. X86 movs requires the lowest element to be lowest
2472/// element of vector 2 and the other elements to come from vector 1 in order.
2473static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2474 bool V2IsSplat = false,
2475 bool V2IsUndef = false) {
2476 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2477 return false;
2478
2479 if (!isUndefOrEqual(Ops[0], 0))
2480 return false;
2481
2482 for (unsigned i = 1; i < NumOps; ++i) {
2483 SDOperand Arg = Ops[i];
2484 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2485 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2486 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2487 return false;
2488 }
2489
2490 return true;
2491}
2492
2493static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2494 bool V2IsUndef = false) {
2495 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2496 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2497 V2IsSplat, V2IsUndef);
2498}
2499
2500/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2501/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2502bool X86::isMOVSHDUPMask(SDNode *N) {
2503 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2504
2505 if (N->getNumOperands() != 4)
2506 return false;
2507
2508 // Expect 1, 1, 3, 3
2509 for (unsigned i = 0; i < 2; ++i) {
2510 SDOperand Arg = N->getOperand(i);
2511 if (Arg.getOpcode() == ISD::UNDEF) continue;
2512 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2513 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2514 if (Val != 1) return false;
2515 }
2516
2517 bool HasHi = false;
2518 for (unsigned i = 2; i < 4; ++i) {
2519 SDOperand Arg = N->getOperand(i);
2520 if (Arg.getOpcode() == ISD::UNDEF) continue;
2521 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2522 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2523 if (Val != 3) return false;
2524 HasHi = true;
2525 }
2526
2527 // Don't use movshdup if it can be done with a shufps.
2528 return HasHi;
2529}
2530
2531/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2532/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2533bool X86::isMOVSLDUPMask(SDNode *N) {
2534 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2535
2536 if (N->getNumOperands() != 4)
2537 return false;
2538
2539 // Expect 0, 0, 2, 2
2540 for (unsigned i = 0; i < 2; ++i) {
2541 SDOperand Arg = N->getOperand(i);
2542 if (Arg.getOpcode() == ISD::UNDEF) continue;
2543 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2544 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2545 if (Val != 0) return false;
2546 }
2547
2548 bool HasHi = false;
2549 for (unsigned i = 2; i < 4; ++i) {
2550 SDOperand Arg = N->getOperand(i);
2551 if (Arg.getOpcode() == ISD::UNDEF) continue;
2552 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2553 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2554 if (Val != 2) return false;
2555 HasHi = true;
2556 }
2557
2558 // Don't use movshdup if it can be done with a shufps.
2559 return HasHi;
2560}
2561
2562/// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2563/// specifies a identity operation on the LHS or RHS.
2564static bool isIdentityMask(SDNode *N, bool RHS = false) {
2565 unsigned NumElems = N->getNumOperands();
2566 for (unsigned i = 0; i < NumElems; ++i)
2567 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2568 return false;
2569 return true;
2570}
2571
2572/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2573/// a splat of a single element.
2574static bool isSplatMask(SDNode *N) {
2575 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2576
2577 // This is a splat operation if each element of the permute is the same, and
2578 // if the value doesn't reference the second vector.
2579 unsigned NumElems = N->getNumOperands();
2580 SDOperand ElementBase;
2581 unsigned i = 0;
2582 for (; i != NumElems; ++i) {
2583 SDOperand Elt = N->getOperand(i);
2584 if (isa<ConstantSDNode>(Elt)) {
2585 ElementBase = Elt;
2586 break;
2587 }
2588 }
2589
2590 if (!ElementBase.Val)
2591 return false;
2592
2593 for (; i != NumElems; ++i) {
2594 SDOperand Arg = N->getOperand(i);
2595 if (Arg.getOpcode() == ISD::UNDEF) continue;
2596 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2597 if (Arg != ElementBase) return false;
2598 }
2599
2600 // Make sure it is a splat of the first vector operand.
2601 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2602}
2603
2604/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2605/// a splat of a single element and it's a 2 or 4 element mask.
2606bool X86::isSplatMask(SDNode *N) {
2607 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2608
2609 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2610 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2611 return false;
2612 return ::isSplatMask(N);
2613}
2614
2615/// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2616/// specifies a splat of zero element.
2617bool X86::isSplatLoMask(SDNode *N) {
2618 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2619
2620 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2621 if (!isUndefOrEqual(N->getOperand(i), 0))
2622 return false;
2623 return true;
2624}
2625
2626/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2627/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2628/// instructions.
2629unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2630 unsigned NumOperands = N->getNumOperands();
2631 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2632 unsigned Mask = 0;
2633 for (unsigned i = 0; i < NumOperands; ++i) {
2634 unsigned Val = 0;
2635 SDOperand Arg = N->getOperand(NumOperands-i-1);
2636 if (Arg.getOpcode() != ISD::UNDEF)
2637 Val = cast<ConstantSDNode>(Arg)->getValue();
2638 if (Val >= NumOperands) Val -= NumOperands;
2639 Mask |= Val;
2640 if (i != NumOperands - 1)
2641 Mask <<= Shift;
2642 }
2643
2644 return Mask;
2645}
2646
2647/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2648/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2649/// instructions.
2650unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2651 unsigned Mask = 0;
2652 // 8 nodes, but we only care about the last 4.
2653 for (unsigned i = 7; i >= 4; --i) {
2654 unsigned Val = 0;
2655 SDOperand Arg = N->getOperand(i);
2656 if (Arg.getOpcode() != ISD::UNDEF)
2657 Val = cast<ConstantSDNode>(Arg)->getValue();
2658 Mask |= (Val - 4);
2659 if (i != 4)
2660 Mask <<= 2;
2661 }
2662
2663 return Mask;
2664}
2665
2666/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2667/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2668/// instructions.
2669unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2670 unsigned Mask = 0;
2671 // 8 nodes, but we only care about the first 4.
2672 for (int i = 3; i >= 0; --i) {
2673 unsigned Val = 0;
2674 SDOperand Arg = N->getOperand(i);
2675 if (Arg.getOpcode() != ISD::UNDEF)
2676 Val = cast<ConstantSDNode>(Arg)->getValue();
2677 Mask |= Val;
2678 if (i != 0)
2679 Mask <<= 2;
2680 }
2681
2682 return Mask;
2683}
2684
2685/// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2686/// specifies a 8 element shuffle that can be broken into a pair of
2687/// PSHUFHW and PSHUFLW.
2688static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2689 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2690
2691 if (N->getNumOperands() != 8)
2692 return false;
2693
2694 // Lower quadword shuffled.
2695 for (unsigned i = 0; i != 4; ++i) {
2696 SDOperand Arg = N->getOperand(i);
2697 if (Arg.getOpcode() == ISD::UNDEF) continue;
2698 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2699 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2700 if (Val > 4)
2701 return false;
2702 }
2703
2704 // Upper quadword shuffled.
2705 for (unsigned i = 4; i != 8; ++i) {
2706 SDOperand Arg = N->getOperand(i);
2707 if (Arg.getOpcode() == ISD::UNDEF) continue;
2708 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2709 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2710 if (Val < 4 || Val > 7)
2711 return false;
2712 }
2713
2714 return true;
2715}
2716
2717/// CommuteVectorShuffle - Swap vector_shuffle operandsas well as
2718/// values in ther permute mask.
2719static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2720 SDOperand &V2, SDOperand &Mask,
2721 SelectionDAG &DAG) {
2722 MVT::ValueType VT = Op.getValueType();
2723 MVT::ValueType MaskVT = Mask.getValueType();
2724 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2725 unsigned NumElems = Mask.getNumOperands();
2726 SmallVector<SDOperand, 8> MaskVec;
2727
2728 for (unsigned i = 0; i != NumElems; ++i) {
2729 SDOperand Arg = Mask.getOperand(i);
2730 if (Arg.getOpcode() == ISD::UNDEF) {
2731 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2732 continue;
2733 }
2734 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2735 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2736 if (Val < NumElems)
2737 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2738 else
2739 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2740 }
2741
2742 std::swap(V1, V2);
2743 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2744 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2745}
2746
2747/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2748/// match movhlps. The lower half elements should come from upper half of
2749/// V1 (and in order), and the upper half elements should come from the upper
2750/// half of V2 (and in order).
2751static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2752 unsigned NumElems = Mask->getNumOperands();
2753 if (NumElems != 4)
2754 return false;
2755 for (unsigned i = 0, e = 2; i != e; ++i)
2756 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2757 return false;
2758 for (unsigned i = 2; i != 4; ++i)
2759 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2760 return false;
2761 return true;
2762}
2763
2764/// isScalarLoadToVector - Returns true if the node is a scalar load that
2765/// is promoted to a vector.
2766static inline bool isScalarLoadToVector(SDNode *N) {
2767 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2768 N = N->getOperand(0).Val;
2769 return ISD::isNON_EXTLoad(N);
2770 }
2771 return false;
2772}
2773
2774/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2775/// match movlp{s|d}. The lower half elements should come from lower half of
2776/// V1 (and in order), and the upper half elements should come from the upper
2777/// half of V2 (and in order). And since V1 will become the source of the
2778/// MOVLP, it must be either a vector load or a scalar load to vector.
2779static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2780 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2781 return false;
2782 // Is V2 is a vector load, don't do this transformation. We will try to use
2783 // load folding shufps op.
2784 if (ISD::isNON_EXTLoad(V2))
2785 return false;
2786
2787 unsigned NumElems = Mask->getNumOperands();
2788 if (NumElems != 2 && NumElems != 4)
2789 return false;
2790 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2791 if (!isUndefOrEqual(Mask->getOperand(i), i))
2792 return false;
2793 for (unsigned i = NumElems/2; i != NumElems; ++i)
2794 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2795 return false;
2796 return true;
2797}
2798
2799/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2800/// all the same.
2801static bool isSplatVector(SDNode *N) {
2802 if (N->getOpcode() != ISD::BUILD_VECTOR)
2803 return false;
2804
2805 SDOperand SplatValue = N->getOperand(0);
2806 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2807 if (N->getOperand(i) != SplatValue)
2808 return false;
2809 return true;
2810}
2811
2812/// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2813/// to an undef.
2814static bool isUndefShuffle(SDNode *N) {
2815 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2816 return false;
2817
2818 SDOperand V1 = N->getOperand(0);
2819 SDOperand V2 = N->getOperand(1);
2820 SDOperand Mask = N->getOperand(2);
2821 unsigned NumElems = Mask.getNumOperands();
2822 for (unsigned i = 0; i != NumElems; ++i) {
2823 SDOperand Arg = Mask.getOperand(i);
2824 if (Arg.getOpcode() != ISD::UNDEF) {
2825 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2826 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2827 return false;
2828 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2829 return false;
2830 }
2831 }
2832 return true;
2833}
2834
2835/// isZeroNode - Returns true if Elt is a constant zero or a floating point
2836/// constant +0.0.
2837static inline bool isZeroNode(SDOperand Elt) {
2838 return ((isa<ConstantSDNode>(Elt) &&
2839 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2840 (isa<ConstantFPSDNode>(Elt) &&
Dale Johannesendf8a8312007-08-31 04:03:46 +00002841 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002842}
2843
2844/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2845/// to an zero vector.
2846static bool isZeroShuffle(SDNode *N) {
2847 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2848 return false;
2849
2850 SDOperand V1 = N->getOperand(0);
2851 SDOperand V2 = N->getOperand(1);
2852 SDOperand Mask = N->getOperand(2);
2853 unsigned NumElems = Mask.getNumOperands();
2854 for (unsigned i = 0; i != NumElems; ++i) {
2855 SDOperand Arg = Mask.getOperand(i);
2856 if (Arg.getOpcode() != ISD::UNDEF) {
2857 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2858 if (Idx < NumElems) {
2859 unsigned Opc = V1.Val->getOpcode();
2860 if (Opc == ISD::UNDEF)
2861 continue;
2862 if (Opc != ISD::BUILD_VECTOR ||
2863 !isZeroNode(V1.Val->getOperand(Idx)))
2864 return false;
2865 } else if (Idx >= NumElems) {
2866 unsigned Opc = V2.Val->getOpcode();
2867 if (Opc == ISD::UNDEF)
2868 continue;
2869 if (Opc != ISD::BUILD_VECTOR ||
2870 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2871 return false;
2872 }
2873 }
2874 }
2875 return true;
2876}
2877
2878/// getZeroVector - Returns a vector of specified type with all zero elements.
2879///
2880static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2881 assert(MVT::isVector(VT) && "Expected a vector type");
2882 unsigned NumElems = MVT::getVectorNumElements(VT);
2883 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2884 bool isFP = MVT::isFloatingPoint(EVT);
2885 SDOperand Zero = isFP ? DAG.getConstantFP(0.0, EVT) : DAG.getConstant(0, EVT);
2886 SmallVector<SDOperand, 8> ZeroVec(NumElems, Zero);
2887 return DAG.getNode(ISD::BUILD_VECTOR, VT, &ZeroVec[0], ZeroVec.size());
2888}
2889
2890/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2891/// that point to V2 points to its first element.
2892static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2893 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2894
2895 bool Changed = false;
2896 SmallVector<SDOperand, 8> MaskVec;
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) {
2901 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2902 if (Val > NumElems) {
2903 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2904 Changed = true;
2905 }
2906 }
2907 MaskVec.push_back(Arg);
2908 }
2909
2910 if (Changed)
2911 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2912 &MaskVec[0], MaskVec.size());
2913 return Mask;
2914}
2915
2916/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2917/// operation of specified width.
2918static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2919 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2920 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2921
2922 SmallVector<SDOperand, 8> MaskVec;
2923 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2924 for (unsigned i = 1; i != NumElems; ++i)
2925 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2926 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2927}
2928
2929/// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2930/// of specified width.
2931static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2932 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2933 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2934 SmallVector<SDOperand, 8> MaskVec;
2935 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2936 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2937 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2938 }
2939 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2940}
2941
2942/// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2943/// of specified width.
2944static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2945 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2946 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2947 unsigned Half = NumElems/2;
2948 SmallVector<SDOperand, 8> MaskVec;
2949 for (unsigned i = 0; i != Half; ++i) {
2950 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2951 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2952 }
2953 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2954}
2955
2956/// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2957///
2958static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2959 SDOperand V1 = Op.getOperand(0);
2960 SDOperand Mask = Op.getOperand(2);
2961 MVT::ValueType VT = Op.getValueType();
2962 unsigned NumElems = Mask.getNumOperands();
2963 Mask = getUnpacklMask(NumElems, DAG);
2964 while (NumElems != 4) {
2965 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2966 NumElems >>= 1;
2967 }
2968 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2969
2970 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2971 Mask = getZeroVector(MaskVT, DAG);
2972 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2973 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2974 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2975}
2976
2977/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2978/// vector of zero or undef vector.
2979static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2980 unsigned NumElems, unsigned Idx,
2981 bool isZero, SelectionDAG &DAG) {
2982 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2983 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2984 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2985 SDOperand Zero = DAG.getConstant(0, EVT);
2986 SmallVector<SDOperand, 8> MaskVec(NumElems, Zero);
2987 MaskVec[Idx] = DAG.getConstant(NumElems, EVT);
2988 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2989 &MaskVec[0], MaskVec.size());
2990 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2991}
2992
2993/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2994///
2995static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2996 unsigned NumNonZero, unsigned NumZero,
2997 SelectionDAG &DAG, TargetLowering &TLI) {
2998 if (NumNonZero > 8)
2999 return SDOperand();
3000
3001 SDOperand V(0, 0);
3002 bool First = true;
3003 for (unsigned i = 0; i < 16; ++i) {
3004 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3005 if (ThisIsNonZero && First) {
3006 if (NumZero)
3007 V = getZeroVector(MVT::v8i16, DAG);
3008 else
3009 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3010 First = false;
3011 }
3012
3013 if ((i & 1) != 0) {
3014 SDOperand ThisElt(0, 0), LastElt(0, 0);
3015 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3016 if (LastIsNonZero) {
3017 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3018 }
3019 if (ThisIsNonZero) {
3020 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3021 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3022 ThisElt, DAG.getConstant(8, MVT::i8));
3023 if (LastIsNonZero)
3024 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3025 } else
3026 ThisElt = LastElt;
3027
3028 if (ThisElt.Val)
3029 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3030 DAG.getConstant(i/2, TLI.getPointerTy()));
3031 }
3032 }
3033
3034 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3035}
3036
3037/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3038///
3039static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3040 unsigned NumNonZero, unsigned NumZero,
3041 SelectionDAG &DAG, TargetLowering &TLI) {
3042 if (NumNonZero > 4)
3043 return SDOperand();
3044
3045 SDOperand V(0, 0);
3046 bool First = true;
3047 for (unsigned i = 0; i < 8; ++i) {
3048 bool isNonZero = (NonZeros & (1 << i)) != 0;
3049 if (isNonZero) {
3050 if (First) {
3051 if (NumZero)
3052 V = getZeroVector(MVT::v8i16, DAG);
3053 else
3054 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3055 First = false;
3056 }
3057 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3058 DAG.getConstant(i, TLI.getPointerTy()));
3059 }
3060 }
3061
3062 return V;
3063}
3064
3065SDOperand
3066X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3067 // All zero's are handled with pxor.
3068 if (ISD::isBuildVectorAllZeros(Op.Val))
3069 return Op;
3070
3071 // All one's are handled with pcmpeqd.
3072 if (ISD::isBuildVectorAllOnes(Op.Val))
3073 return Op;
3074
3075 MVT::ValueType VT = Op.getValueType();
3076 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3077 unsigned EVTBits = MVT::getSizeInBits(EVT);
3078
3079 unsigned NumElems = Op.getNumOperands();
3080 unsigned NumZero = 0;
3081 unsigned NumNonZero = 0;
3082 unsigned NonZeros = 0;
Dan Gohman21463242007-07-24 22:55:08 +00003083 unsigned NumNonZeroImms = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003084 std::set<SDOperand> Values;
3085 for (unsigned i = 0; i < NumElems; ++i) {
3086 SDOperand Elt = Op.getOperand(i);
3087 if (Elt.getOpcode() != ISD::UNDEF) {
3088 Values.insert(Elt);
3089 if (isZeroNode(Elt))
3090 NumZero++;
3091 else {
3092 NonZeros |= (1 << i);
3093 NumNonZero++;
Dan Gohman21463242007-07-24 22:55:08 +00003094 if (Elt.getOpcode() == ISD::Constant ||
3095 Elt.getOpcode() == ISD::ConstantFP)
3096 NumNonZeroImms++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003097 }
3098 }
3099 }
3100
3101 if (NumNonZero == 0) {
3102 if (NumZero == 0)
3103 // All undef vector. Return an UNDEF.
3104 return DAG.getNode(ISD::UNDEF, VT);
3105 else
3106 // A mix of zero and undef. Return a zero vector.
3107 return getZeroVector(VT, DAG);
3108 }
3109
3110 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3111 if (Values.size() == 1)
3112 return SDOperand();
3113
3114 // Special case for single non-zero element.
3115 if (NumNonZero == 1) {
3116 unsigned Idx = CountTrailingZeros_32(NonZeros);
3117 SDOperand Item = Op.getOperand(Idx);
3118 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3119 if (Idx == 0)
3120 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3121 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
3122 NumZero > 0, DAG);
3123
3124 if (EVTBits == 32) {
3125 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3126 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
3127 DAG);
3128 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3129 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3130 SmallVector<SDOperand, 8> MaskVec;
3131 for (unsigned i = 0; i < NumElems; i++)
3132 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3133 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3134 &MaskVec[0], MaskVec.size());
3135 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3136 DAG.getNode(ISD::UNDEF, VT), Mask);
3137 }
3138 }
3139
Dan Gohman21463242007-07-24 22:55:08 +00003140 // A vector full of immediates; various special cases are already
3141 // handled, so this is best done with a single constant-pool load.
3142 if (NumNonZero == NumNonZeroImms)
3143 return SDOperand();
3144
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003145 // Let legalizer expand 2-wide build_vectors.
3146 if (EVTBits == 64)
3147 return SDOperand();
3148
3149 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3150 if (EVTBits == 8 && NumElems == 16) {
3151 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3152 *this);
3153 if (V.Val) return V;
3154 }
3155
3156 if (EVTBits == 16 && NumElems == 8) {
3157 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3158 *this);
3159 if (V.Val) return V;
3160 }
3161
3162 // If element VT is == 32 bits, turn it into a number of shuffles.
3163 SmallVector<SDOperand, 8> V;
3164 V.resize(NumElems);
3165 if (NumElems == 4 && NumZero > 0) {
3166 for (unsigned i = 0; i < 4; ++i) {
3167 bool isZero = !(NonZeros & (1 << i));
3168 if (isZero)
3169 V[i] = getZeroVector(VT, DAG);
3170 else
3171 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3172 }
3173
3174 for (unsigned i = 0; i < 2; ++i) {
3175 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3176 default: break;
3177 case 0:
3178 V[i] = V[i*2]; // Must be a zero vector.
3179 break;
3180 case 1:
3181 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3182 getMOVLMask(NumElems, DAG));
3183 break;
3184 case 2:
3185 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3186 getMOVLMask(NumElems, DAG));
3187 break;
3188 case 3:
3189 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3190 getUnpacklMask(NumElems, DAG));
3191 break;
3192 }
3193 }
3194
3195 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3196 // clears the upper bits.
3197 // FIXME: we can do the same for v4f32 case when we know both parts of
3198 // the lower half come from scalar_to_vector (loadf32). We should do
3199 // that in post legalizer dag combiner with target specific hooks.
3200 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3201 return V[0];
3202 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3203 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3204 SmallVector<SDOperand, 8> MaskVec;
3205 bool Reverse = (NonZeros & 0x3) == 2;
3206 for (unsigned i = 0; i < 2; ++i)
3207 if (Reverse)
3208 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3209 else
3210 MaskVec.push_back(DAG.getConstant(i, EVT));
3211 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3212 for (unsigned i = 0; i < 2; ++i)
3213 if (Reverse)
3214 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3215 else
3216 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3217 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3218 &MaskVec[0], MaskVec.size());
3219 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3220 }
3221
3222 if (Values.size() > 2) {
3223 // Expand into a number of unpckl*.
3224 // e.g. for v4f32
3225 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3226 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3227 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3228 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3229 for (unsigned i = 0; i < NumElems; ++i)
3230 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3231 NumElems >>= 1;
3232 while (NumElems != 0) {
3233 for (unsigned i = 0; i < NumElems; ++i)
3234 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3235 UnpckMask);
3236 NumElems >>= 1;
3237 }
3238 return V[0];
3239 }
3240
3241 return SDOperand();
3242}
3243
3244SDOperand
3245X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3246 SDOperand V1 = Op.getOperand(0);
3247 SDOperand V2 = Op.getOperand(1);
3248 SDOperand PermMask = Op.getOperand(2);
3249 MVT::ValueType VT = Op.getValueType();
3250 unsigned NumElems = PermMask.getNumOperands();
3251 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3252 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3253 bool V1IsSplat = false;
3254 bool V2IsSplat = false;
3255
3256 if (isUndefShuffle(Op.Val))
3257 return DAG.getNode(ISD::UNDEF, VT);
3258
3259 if (isZeroShuffle(Op.Val))
3260 return getZeroVector(VT, DAG);
3261
3262 if (isIdentityMask(PermMask.Val))
3263 return V1;
3264 else if (isIdentityMask(PermMask.Val, true))
3265 return V2;
3266
3267 if (isSplatMask(PermMask.Val)) {
3268 if (NumElems <= 4) return Op;
3269 // Promote it to a v4i32 splat.
3270 return PromoteSplat(Op, DAG);
3271 }
3272
3273 if (X86::isMOVLMask(PermMask.Val))
3274 return (V1IsUndef) ? V2 : Op;
3275
3276 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3277 X86::isMOVSLDUPMask(PermMask.Val) ||
3278 X86::isMOVHLPSMask(PermMask.Val) ||
3279 X86::isMOVHPMask(PermMask.Val) ||
3280 X86::isMOVLPMask(PermMask.Val))
3281 return Op;
3282
3283 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3284 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3285 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3286
3287 bool Commuted = false;
3288 V1IsSplat = isSplatVector(V1.Val);
3289 V2IsSplat = isSplatVector(V2.Val);
3290 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3291 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3292 std::swap(V1IsSplat, V2IsSplat);
3293 std::swap(V1IsUndef, V2IsUndef);
3294 Commuted = true;
3295 }
3296
3297 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3298 if (V2IsUndef) return V1;
3299 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3300 if (V2IsSplat) {
3301 // V2 is a splat, so the mask may be malformed. That is, it may point
3302 // to any V2 element. The instruction selectior won't like this. Get
3303 // a corrected mask and commute to form a proper MOVS{S|D}.
3304 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3305 if (NewMask.Val != PermMask.Val)
3306 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3307 }
3308 return Op;
3309 }
3310
3311 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3312 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3313 X86::isUNPCKLMask(PermMask.Val) ||
3314 X86::isUNPCKHMask(PermMask.Val))
3315 return Op;
3316
3317 if (V2IsSplat) {
3318 // Normalize mask so all entries that point to V2 points to its first
3319 // element then try to match unpck{h|l} again. If match, return a
3320 // new vector_shuffle with the corrected mask.
3321 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3322 if (NewMask.Val != PermMask.Val) {
3323 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3324 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3325 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3326 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3327 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3328 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3329 }
3330 }
3331 }
3332
3333 // Normalize the node to match x86 shuffle ops if needed
3334 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3335 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3336
3337 if (Commuted) {
3338 // Commute is back and try unpck* again.
3339 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3340 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3341 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3342 X86::isUNPCKLMask(PermMask.Val) ||
3343 X86::isUNPCKHMask(PermMask.Val))
3344 return Op;
3345 }
3346
3347 // If VT is integer, try PSHUF* first, then SHUFP*.
3348 if (MVT::isInteger(VT)) {
Dan Gohman7dc19012007-08-02 21:17:01 +00003349 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3350 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3351 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3352 X86::isPSHUFDMask(PermMask.Val)) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003353 X86::isPSHUFHWMask(PermMask.Val) ||
3354 X86::isPSHUFLWMask(PermMask.Val)) {
3355 if (V2.getOpcode() != ISD::UNDEF)
3356 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3357 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3358 return Op;
3359 }
3360
3361 if (X86::isSHUFPMask(PermMask.Val) &&
3362 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3363 return Op;
3364
3365 // Handle v8i16 shuffle high / low shuffle node pair.
3366 if (VT == MVT::v8i16 && isPSHUFHW_PSHUFLWMask(PermMask.Val)) {
3367 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3368 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3369 SmallVector<SDOperand, 8> MaskVec;
3370 for (unsigned i = 0; i != 4; ++i)
3371 MaskVec.push_back(PermMask.getOperand(i));
3372 for (unsigned i = 4; i != 8; ++i)
3373 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3374 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3375 &MaskVec[0], MaskVec.size());
3376 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3377 MaskVec.clear();
3378 for (unsigned i = 0; i != 4; ++i)
3379 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3380 for (unsigned i = 4; i != 8; ++i)
3381 MaskVec.push_back(PermMask.getOperand(i));
3382 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0],MaskVec.size());
3383 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3384 }
3385 } else {
3386 // Floating point cases in the other order.
3387 if (X86::isSHUFPMask(PermMask.Val))
3388 return Op;
3389 if (X86::isPSHUFDMask(PermMask.Val) ||
3390 X86::isPSHUFHWMask(PermMask.Val) ||
3391 X86::isPSHUFLWMask(PermMask.Val)) {
3392 if (V2.getOpcode() != ISD::UNDEF)
3393 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3394 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3395 return Op;
3396 }
3397 }
3398
3399 if (NumElems == 4 &&
3400 // Don't do this for MMX.
3401 MVT::getSizeInBits(VT) != 64) {
3402 MVT::ValueType MaskVT = PermMask.getValueType();
3403 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3404 SmallVector<std::pair<int, int>, 8> Locs;
3405 Locs.reserve(NumElems);
3406 SmallVector<SDOperand, 8> Mask1(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3407 SmallVector<SDOperand, 8> Mask2(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3408 unsigned NumHi = 0;
3409 unsigned NumLo = 0;
3410 // If no more than two elements come from either vector. This can be
3411 // implemented with two shuffles. First shuffle gather the elements.
3412 // The second shuffle, which takes the first shuffle as both of its
3413 // vector operands, put the elements into the right order.
3414 for (unsigned i = 0; i != NumElems; ++i) {
3415 SDOperand Elt = PermMask.getOperand(i);
3416 if (Elt.getOpcode() == ISD::UNDEF) {
3417 Locs[i] = std::make_pair(-1, -1);
3418 } else {
3419 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3420 if (Val < NumElems) {
3421 Locs[i] = std::make_pair(0, NumLo);
3422 Mask1[NumLo] = Elt;
3423 NumLo++;
3424 } else {
3425 Locs[i] = std::make_pair(1, NumHi);
3426 if (2+NumHi < NumElems)
3427 Mask1[2+NumHi] = Elt;
3428 NumHi++;
3429 }
3430 }
3431 }
3432 if (NumLo <= 2 && NumHi <= 2) {
3433 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3434 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3435 &Mask1[0], Mask1.size()));
3436 for (unsigned i = 0; i != NumElems; ++i) {
3437 if (Locs[i].first == -1)
3438 continue;
3439 else {
3440 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3441 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3442 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3443 }
3444 }
3445
3446 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3447 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3448 &Mask2[0], Mask2.size()));
3449 }
3450
3451 // Break it into (shuffle shuffle_hi, shuffle_lo).
3452 Locs.clear();
3453 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3454 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3455 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3456 unsigned MaskIdx = 0;
3457 unsigned LoIdx = 0;
3458 unsigned HiIdx = NumElems/2;
3459 for (unsigned i = 0; i != NumElems; ++i) {
3460 if (i == NumElems/2) {
3461 MaskPtr = &HiMask;
3462 MaskIdx = 1;
3463 LoIdx = 0;
3464 HiIdx = NumElems/2;
3465 }
3466 SDOperand Elt = PermMask.getOperand(i);
3467 if (Elt.getOpcode() == ISD::UNDEF) {
3468 Locs[i] = std::make_pair(-1, -1);
3469 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3470 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3471 (*MaskPtr)[LoIdx] = Elt;
3472 LoIdx++;
3473 } else {
3474 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3475 (*MaskPtr)[HiIdx] = Elt;
3476 HiIdx++;
3477 }
3478 }
3479
3480 SDOperand LoShuffle =
3481 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3482 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3483 &LoMask[0], LoMask.size()));
3484 SDOperand HiShuffle =
3485 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3486 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3487 &HiMask[0], HiMask.size()));
3488 SmallVector<SDOperand, 8> MaskOps;
3489 for (unsigned i = 0; i != NumElems; ++i) {
3490 if (Locs[i].first == -1) {
3491 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3492 } else {
3493 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3494 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3495 }
3496 }
3497 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3498 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3499 &MaskOps[0], MaskOps.size()));
3500 }
3501
3502 return SDOperand();
3503}
3504
3505SDOperand
3506X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3507 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3508 return SDOperand();
3509
3510 MVT::ValueType VT = Op.getValueType();
3511 // TODO: handle v16i8.
3512 if (MVT::getSizeInBits(VT) == 16) {
3513 // Transform it so it match pextrw which produces a 32-bit result.
3514 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3515 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3516 Op.getOperand(0), Op.getOperand(1));
3517 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3518 DAG.getValueType(VT));
3519 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3520 } else if (MVT::getSizeInBits(VT) == 32) {
3521 SDOperand Vec = Op.getOperand(0);
3522 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3523 if (Idx == 0)
3524 return Op;
3525 // SHUFPS the element to the lowest double word, then movss.
3526 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3527 SmallVector<SDOperand, 8> IdxVec;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00003528 IdxVec.
3529 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3530 IdxVec.
3531 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3532 IdxVec.
3533 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3534 IdxVec.
3535 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003536 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3537 &IdxVec[0], IdxVec.size());
3538 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3539 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3540 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3541 DAG.getConstant(0, getPointerTy()));
3542 } else if (MVT::getSizeInBits(VT) == 64) {
3543 SDOperand Vec = Op.getOperand(0);
3544 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3545 if (Idx == 0)
3546 return Op;
3547
3548 // UNPCKHPD the element to the lowest double word, then movsd.
3549 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3550 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3551 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3552 SmallVector<SDOperand, 8> IdxVec;
3553 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00003554 IdxVec.
3555 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003556 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3557 &IdxVec[0], IdxVec.size());
3558 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3559 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3560 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3561 DAG.getConstant(0, getPointerTy()));
3562 }
3563
3564 return SDOperand();
3565}
3566
3567SDOperand
3568X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3569 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3570 // as its second argument.
3571 MVT::ValueType VT = Op.getValueType();
3572 MVT::ValueType BaseVT = MVT::getVectorElementType(VT);
3573 SDOperand N0 = Op.getOperand(0);
3574 SDOperand N1 = Op.getOperand(1);
3575 SDOperand N2 = Op.getOperand(2);
3576 if (MVT::getSizeInBits(BaseVT) == 16) {
3577 if (N1.getValueType() != MVT::i32)
3578 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3579 if (N2.getValueType() != MVT::i32)
3580 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
3581 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3582 } else if (MVT::getSizeInBits(BaseVT) == 32) {
3583 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
3584 if (Idx == 0) {
3585 // Use a movss.
3586 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
3587 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3588 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3589 SmallVector<SDOperand, 8> MaskVec;
3590 MaskVec.push_back(DAG.getConstant(4, BaseVT));
3591 for (unsigned i = 1; i <= 3; ++i)
3592 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3593 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
3594 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3595 &MaskVec[0], MaskVec.size()));
3596 } else {
3597 // Use two pinsrw instructions to insert a 32 bit value.
3598 Idx <<= 1;
3599 if (MVT::isFloatingPoint(N1.getValueType())) {
Evan Cheng1eea6752007-07-31 06:21:44 +00003600 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
3601 N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
3602 N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
3603 DAG.getConstant(0, getPointerTy()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003604 }
3605 N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
3606 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3607 DAG.getConstant(Idx, getPointerTy()));
3608 N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
3609 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3610 DAG.getConstant(Idx+1, getPointerTy()));
3611 return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3612 }
3613 }
3614
3615 return SDOperand();
3616}
3617
3618SDOperand
3619X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3620 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3621 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3622}
3623
3624// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3625// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3626// one of the above mentioned nodes. It has to be wrapped because otherwise
3627// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3628// be used to form addressing mode. These wrapped nodes will be selected
3629// into MOV32ri.
3630SDOperand
3631X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3632 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3633 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3634 getPointerTy(),
3635 CP->getAlignment());
3636 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3637 // With PIC, the address is actually $g + Offset.
3638 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3639 !Subtarget->isPICStyleRIPRel()) {
3640 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3641 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3642 Result);
3643 }
3644
3645 return Result;
3646}
3647
3648SDOperand
3649X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3650 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3651 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3652 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3653 // With PIC, the address is actually $g + Offset.
3654 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3655 !Subtarget->isPICStyleRIPRel()) {
3656 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3657 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3658 Result);
3659 }
3660
3661 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3662 // load the value at address GV, not the value of GV itself. This means that
3663 // the GlobalAddress must be in the base or index register of the address, not
3664 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3665 // The same applies for external symbols during PIC codegen
3666 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3667 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
3668
3669 return Result;
3670}
3671
3672// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3673static SDOperand
3674LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3675 const MVT::ValueType PtrVT) {
3676 SDOperand InFlag;
3677 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3678 DAG.getNode(X86ISD::GlobalBaseReg,
3679 PtrVT), InFlag);
3680 InFlag = Chain.getValue(1);
3681
3682 // emit leal symbol@TLSGD(,%ebx,1), %eax
3683 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3684 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3685 GA->getValueType(0),
3686 GA->getOffset());
3687 SDOperand Ops[] = { Chain, TGA, InFlag };
3688 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3689 InFlag = Result.getValue(2);
3690 Chain = Result.getValue(1);
3691
3692 // call ___tls_get_addr. This function receives its argument in
3693 // the register EAX.
3694 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3695 InFlag = Chain.getValue(1);
3696
3697 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3698 SDOperand Ops1[] = { Chain,
3699 DAG.getTargetExternalSymbol("___tls_get_addr",
3700 PtrVT),
3701 DAG.getRegister(X86::EAX, PtrVT),
3702 DAG.getRegister(X86::EBX, PtrVT),
3703 InFlag };
3704 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3705 InFlag = Chain.getValue(1);
3706
3707 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3708}
3709
3710// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3711// "local exec" model.
3712static SDOperand
3713LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3714 const MVT::ValueType PtrVT) {
3715 // Get the Thread Pointer
3716 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3717 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3718 // exec)
3719 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3720 GA->getValueType(0),
3721 GA->getOffset());
3722 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3723
3724 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3725 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
3726
3727 // The address of the thread local variable is the add of the thread
3728 // pointer with the offset of the variable.
3729 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3730}
3731
3732SDOperand
3733X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3734 // TODO: implement the "local dynamic" model
3735 // TODO: implement the "initial exec"model for pic executables
3736 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3737 "TLS not implemented for non-ELF and 64-bit targets");
3738 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3739 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3740 // otherwise use the "Local Exec"TLS Model
3741 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3742 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3743 else
3744 return LowerToTLSExecModel(GA, DAG, getPointerTy());
3745}
3746
3747SDOperand
3748X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3749 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3750 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3751 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3752 // With PIC, the address is actually $g + Offset.
3753 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3754 !Subtarget->isPICStyleRIPRel()) {
3755 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3756 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3757 Result);
3758 }
3759
3760 return Result;
3761}
3762
3763SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3764 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3765 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3766 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3767 // With PIC, the address is actually $g + Offset.
3768 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3769 !Subtarget->isPICStyleRIPRel()) {
3770 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3771 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3772 Result);
3773 }
3774
3775 return Result;
3776}
3777
Chris Lattner62814a32007-10-17 06:02:13 +00003778/// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
3779/// take a 2 x i32 value to shift plus a shift amount.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003780SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner62814a32007-10-17 06:02:13 +00003781 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
3782 "Not an i64 shift!");
3783 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
3784 SDOperand ShOpLo = Op.getOperand(0);
3785 SDOperand ShOpHi = Op.getOperand(1);
3786 SDOperand ShAmt = Op.getOperand(2);
3787 SDOperand Tmp1 = isSRA ?
3788 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
3789 DAG.getConstant(0, MVT::i32);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003790
Chris Lattner62814a32007-10-17 06:02:13 +00003791 SDOperand Tmp2, Tmp3;
3792 if (Op.getOpcode() == ISD::SHL_PARTS) {
3793 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
3794 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
3795 } else {
3796 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
3797 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
3798 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003799
Chris Lattner62814a32007-10-17 06:02:13 +00003800 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3801 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
3802 DAG.getConstant(32, MVT::i8));
3803 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
3804 AndNode, DAG.getConstant(0, MVT::i8));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003805
Chris Lattner62814a32007-10-17 06:02:13 +00003806 SDOperand Hi, Lo;
3807 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3808 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
3809 SmallVector<SDOperand, 4> Ops;
3810 if (Op.getOpcode() == ISD::SHL_PARTS) {
3811 Ops.push_back(Tmp2);
3812 Ops.push_back(Tmp3);
3813 Ops.push_back(CC);
3814 Ops.push_back(Cond);
3815 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003816
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003817 Ops.clear();
Chris Lattner62814a32007-10-17 06:02:13 +00003818 Ops.push_back(Tmp3);
3819 Ops.push_back(Tmp1);
3820 Ops.push_back(CC);
3821 Ops.push_back(Cond);
3822 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3823 } else {
3824 Ops.push_back(Tmp2);
3825 Ops.push_back(Tmp3);
3826 Ops.push_back(CC);
3827 Ops.push_back(Cond);
3828 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3829
3830 Ops.clear();
3831 Ops.push_back(Tmp3);
3832 Ops.push_back(Tmp1);
3833 Ops.push_back(CC);
3834 Ops.push_back(Cond);
3835 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3836 }
3837
3838 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
3839 Ops.clear();
3840 Ops.push_back(Lo);
3841 Ops.push_back(Hi);
3842 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003843}
3844
3845SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
3846 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
3847 Op.getOperand(0).getValueType() >= MVT::i16 &&
3848 "Unknown SINT_TO_FP to lower!");
3849
3850 SDOperand Result;
3851 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
3852 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
3853 MachineFunction &MF = DAG.getMachineFunction();
3854 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
3855 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3856 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
3857 StackSlot, NULL, 0);
3858
Dale Johannesen2fc20782007-09-14 22:26:36 +00003859 // These are really Legal; caller falls through into that case.
Dale Johannesene0e0fd02007-09-23 14:52:20 +00003860 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f32 && X86ScalarSSEf32)
3861 return Result;
3862 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f64 && X86ScalarSSEf64)
Dale Johannesen2fc20782007-09-14 22:26:36 +00003863 return Result;
Dale Johannesen958b08b2007-09-19 23:55:34 +00003864 if (SrcVT==MVT::i64 && Op.getValueType() != MVT::f80 &&
3865 Subtarget->is64Bit())
3866 return Result;
Dale Johannesen2fc20782007-09-14 22:26:36 +00003867
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003868 // Build the FILD
3869 SDVTList Tys;
Dale Johannesene0e0fd02007-09-23 14:52:20 +00003870 bool useSSE = (X86ScalarSSEf32 && Op.getValueType() == MVT::f32) ||
3871 (X86ScalarSSEf64 && Op.getValueType() == MVT::f64);
Dale Johannesen2fc20782007-09-14 22:26:36 +00003872 if (useSSE)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003873 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
3874 else
3875 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
3876 SmallVector<SDOperand, 8> Ops;
3877 Ops.push_back(Chain);
3878 Ops.push_back(StackSlot);
3879 Ops.push_back(DAG.getValueType(SrcVT));
Dale Johannesen2fc20782007-09-14 22:26:36 +00003880 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003881 Tys, &Ops[0], Ops.size());
3882
Dale Johannesen2fc20782007-09-14 22:26:36 +00003883 if (useSSE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003884 Chain = Result.getValue(1);
3885 SDOperand InFlag = Result.getValue(2);
3886
3887 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
3888 // shouldn't be necessary except that RFP cannot be live across
3889 // multiple blocks. When stackifier is fixed, they can be uncoupled.
3890 MachineFunction &MF = DAG.getMachineFunction();
3891 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3892 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3893 Tys = DAG.getVTList(MVT::Other);
3894 SmallVector<SDOperand, 8> Ops;
3895 Ops.push_back(Chain);
3896 Ops.push_back(Result);
3897 Ops.push_back(StackSlot);
3898 Ops.push_back(DAG.getValueType(Op.getValueType()));
3899 Ops.push_back(InFlag);
3900 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
3901 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
3902 }
3903
3904 return Result;
3905}
3906
3907SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
3908 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
3909 "Unknown FP_TO_SINT to lower!");
Dale Johannesen2fc20782007-09-14 22:26:36 +00003910 SDOperand Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003911
Dale Johannesen2fc20782007-09-14 22:26:36 +00003912 // These are really Legal.
Dale Johannesene0e0fd02007-09-23 14:52:20 +00003913 if (Op.getValueType() == MVT::i32 &&
3914 X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32)
3915 return Result;
3916 if (Op.getValueType() == MVT::i32 &&
3917 X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)
Dale Johannesen2fc20782007-09-14 22:26:36 +00003918 return Result;
Dale Johannesen958b08b2007-09-19 23:55:34 +00003919 if (Subtarget->is64Bit() &&
3920 Op.getValueType() == MVT::i64 &&
3921 Op.getOperand(0).getValueType() != MVT::f80)
3922 return Result;
Dale Johannesen2fc20782007-09-14 22:26:36 +00003923
Evan Cheng05441e62007-10-15 20:11:21 +00003924 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
3925 // stack slot.
3926 MachineFunction &MF = DAG.getMachineFunction();
3927 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
3928 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3929 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003930 unsigned Opc;
3931 switch (Op.getValueType()) {
3932 default: assert(0 && "Invalid FP_TO_SINT to lower!");
3933 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
3934 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
3935 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
3936 }
3937
3938 SDOperand Chain = DAG.getEntryNode();
3939 SDOperand Value = Op.getOperand(0);
Dale Johannesene0e0fd02007-09-23 14:52:20 +00003940 if ((X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32) ||
3941 (X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003942 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
3943 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
3944 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
3945 SDOperand Ops[] = {
3946 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
3947 };
3948 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
3949 Chain = Value.getValue(1);
3950 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3951 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3952 }
3953
3954 // Build the FP_TO_INT*_IN_MEM
3955 SDOperand Ops[] = { Chain, Value, StackSlot };
3956 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
3957
Chris Lattner79b8afe2007-10-17 06:17:29 +00003958 // Load the result. If this is an i64 load on an x86-32 host, expand the
3959 // load.
3960 if (Op.getValueType() != MVT::i64 || Subtarget->is64Bit())
3961 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
3962
3963 SDOperand Lo = DAG.getLoad(MVT::i32, FIST, StackSlot, NULL, 0);
3964 StackSlot = DAG.getNode(ISD::ADD, StackSlot.getValueType(), StackSlot,
3965 DAG.getConstant(StackSlot.getValueType(), 4));
3966 SDOperand Hi = DAG.getLoad(MVT::i32, FIST, StackSlot, NULL, 0);
3967
3968
3969 return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003970}
3971
3972SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
3973 MVT::ValueType VT = Op.getValueType();
3974 MVT::ValueType EltVT = VT;
3975 if (MVT::isVector(VT))
3976 EltVT = MVT::getVectorElementType(VT);
3977 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
3978 std::vector<Constant*> CV;
3979 if (EltVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00003980 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003981 CV.push_back(C);
3982 CV.push_back(C);
3983 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00003984 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003985 CV.push_back(C);
3986 CV.push_back(C);
3987 CV.push_back(C);
3988 CV.push_back(C);
3989 }
Dan Gohman11821702007-07-27 17:16:43 +00003990 Constant *C = ConstantVector::get(CV);
3991 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
3992 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
3993 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003994 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
3995}
3996
3997SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
3998 MVT::ValueType VT = Op.getValueType();
3999 MVT::ValueType EltVT = VT;
Evan Cheng92b8f782007-07-19 23:36:01 +00004000 unsigned EltNum = 1;
4001 if (MVT::isVector(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004002 EltVT = MVT::getVectorElementType(VT);
Evan Cheng92b8f782007-07-19 23:36:01 +00004003 EltNum = MVT::getVectorNumElements(VT);
4004 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004005 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4006 std::vector<Constant*> CV;
4007 if (EltVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004008 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004009 CV.push_back(C);
4010 CV.push_back(C);
4011 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004012 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004013 CV.push_back(C);
4014 CV.push_back(C);
4015 CV.push_back(C);
4016 CV.push_back(C);
4017 }
Dan Gohman11821702007-07-27 17:16:43 +00004018 Constant *C = ConstantVector::get(CV);
4019 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4020 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4021 false, 16);
Evan Cheng92b8f782007-07-19 23:36:01 +00004022 if (MVT::isVector(VT)) {
Evan Cheng92b8f782007-07-19 23:36:01 +00004023 return DAG.getNode(ISD::BIT_CONVERT, VT,
4024 DAG.getNode(ISD::XOR, MVT::v2i64,
4025 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4026 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4027 } else {
Evan Cheng92b8f782007-07-19 23:36:01 +00004028 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4029 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004030}
4031
4032SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4033 SDOperand Op0 = Op.getOperand(0);
4034 SDOperand Op1 = Op.getOperand(1);
4035 MVT::ValueType VT = Op.getValueType();
4036 MVT::ValueType SrcVT = Op1.getValueType();
4037 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4038
4039 // If second operand is smaller, extend it first.
4040 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4041 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4042 SrcVT = VT;
Dale Johannesenb9de9f02007-09-06 18:13:44 +00004043 SrcTy = MVT::getTypeForValueType(SrcVT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004044 }
Dale Johannesenfb0fa912007-10-21 01:07:44 +00004045 // And if it is bigger, shrink it first.
4046 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4047 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1);
4048 SrcVT = VT;
4049 SrcTy = MVT::getTypeForValueType(SrcVT);
4050 }
4051
4052 // At this point the operands and the result should have the same
4053 // type, and that won't be f80 since that is not custom lowered.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004054
4055 // First get the sign bit of second operand.
4056 std::vector<Constant*> CV;
4057 if (SrcVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004058 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4059 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004060 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004061 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4062 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4063 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4064 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004065 }
Dan Gohman11821702007-07-27 17:16:43 +00004066 Constant *C = ConstantVector::get(CV);
4067 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4068 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx, NULL, 0,
4069 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004070 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4071
4072 // Shift sign bit right or left if the two operands have different types.
4073 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4074 // Op0 is MVT::f32, Op1 is MVT::f64.
4075 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4076 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4077 DAG.getConstant(32, MVT::i32));
4078 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4079 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4080 DAG.getConstant(0, getPointerTy()));
4081 }
4082
4083 // Clear first operand sign bit.
4084 CV.clear();
4085 if (VT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004086 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4087 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004088 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004089 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4090 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4091 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4092 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004093 }
Dan Gohman11821702007-07-27 17:16:43 +00004094 C = ConstantVector::get(CV);
4095 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4096 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4097 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004098 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4099
4100 // Or the value with the sign bit.
4101 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4102}
4103
Evan Cheng621216e2007-09-29 00:00:36 +00004104SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
Evan Cheng950aac02007-09-25 01:57:46 +00004105 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
Evan Cheng6afec3d2007-09-26 00:45:55 +00004106 SDOperand Cond;
Evan Cheng950aac02007-09-25 01:57:46 +00004107 SDOperand Op0 = Op.getOperand(0);
4108 SDOperand Op1 = Op.getOperand(1);
4109 SDOperand CC = Op.getOperand(2);
4110 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4111 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4112 unsigned X86CC;
4113
Evan Cheng950aac02007-09-25 01:57:46 +00004114 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
Evan Cheng6afec3d2007-09-26 00:45:55 +00004115 Op0, Op1, DAG)) {
Evan Cheng621216e2007-09-29 00:00:36 +00004116 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4117 return DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004118 DAG.getConstant(X86CC, MVT::i8), Cond);
Evan Cheng6afec3d2007-09-26 00:45:55 +00004119 }
Evan Cheng950aac02007-09-25 01:57:46 +00004120
4121 assert(isFP && "Illegal integer SetCC!");
4122
Evan Cheng621216e2007-09-29 00:00:36 +00004123 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
Evan Cheng950aac02007-09-25 01:57:46 +00004124 switch (SetCCOpcode) {
4125 default: assert(false && "Illegal floating point SetCC!");
4126 case ISD::SETOEQ: { // !PF & ZF
Evan Cheng621216e2007-09-29 00:00:36 +00004127 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004128 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004129 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004130 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4131 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4132 }
4133 case ISD::SETUNE: { // PF | !ZF
Evan Cheng621216e2007-09-29 00:00:36 +00004134 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004135 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004136 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004137 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4138 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4139 }
4140 }
4141}
4142
4143
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004144SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4145 bool addTest = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004146 SDOperand Cond = Op.getOperand(0);
4147 SDOperand CC;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004148
4149 if (Cond.getOpcode() == ISD::SETCC)
Evan Cheng621216e2007-09-29 00:00:36 +00004150 Cond = LowerSETCC(Cond, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004151
Evan Cheng50d37ab2007-10-08 22:16:29 +00004152 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4153 // setting operand in place of the X86ISD::SETCC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004154 if (Cond.getOpcode() == X86ISD::SETCC) {
4155 CC = Cond.getOperand(0);
4156
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004157 SDOperand Cmp = Cond.getOperand(1);
4158 unsigned Opc = Cmp.getOpcode();
Evan Cheng50d37ab2007-10-08 22:16:29 +00004159 MVT::ValueType VT = Op.getValueType();
4160 bool IllegalFPCMov = false;
4161 if (VT == MVT::f32 && !X86ScalarSSEf32)
4162 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4163 else if (VT == MVT::f64 && !X86ScalarSSEf64)
4164 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
Dale Johannesen3b955db2007-10-16 18:09:08 +00004165 else if (VT == MVT::f80)
4166 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
Evan Cheng621216e2007-09-29 00:00:36 +00004167 if ((Opc == X86ISD::CMP ||
4168 Opc == X86ISD::COMI ||
4169 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
Evan Cheng50d37ab2007-10-08 22:16:29 +00004170 Cond = Cmp;
Evan Cheng950aac02007-09-25 01:57:46 +00004171 addTest = false;
4172 }
4173 }
4174
4175 if (addTest) {
4176 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
Evan Cheng50d37ab2007-10-08 22:16:29 +00004177 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
Evan Cheng950aac02007-09-25 01:57:46 +00004178 }
4179
4180 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4181 MVT::Flag);
4182 SmallVector<SDOperand, 4> Ops;
4183 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4184 // condition is true.
4185 Ops.push_back(Op.getOperand(2));
4186 Ops.push_back(Op.getOperand(1));
4187 Ops.push_back(CC);
4188 Ops.push_back(Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004189 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
Evan Cheng950aac02007-09-25 01:57:46 +00004190}
4191
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004192SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4193 bool addTest = true;
4194 SDOperand Chain = Op.getOperand(0);
4195 SDOperand Cond = Op.getOperand(1);
4196 SDOperand Dest = Op.getOperand(2);
4197 SDOperand CC;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004198
4199 if (Cond.getOpcode() == ISD::SETCC)
Evan Cheng621216e2007-09-29 00:00:36 +00004200 Cond = LowerSETCC(Cond, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004201
Evan Cheng50d37ab2007-10-08 22:16:29 +00004202 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4203 // setting operand in place of the X86ISD::SETCC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004204 if (Cond.getOpcode() == X86ISD::SETCC) {
4205 CC = Cond.getOperand(0);
4206
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004207 SDOperand Cmp = Cond.getOperand(1);
4208 unsigned Opc = Cmp.getOpcode();
Evan Cheng621216e2007-09-29 00:00:36 +00004209 if (Opc == X86ISD::CMP ||
4210 Opc == X86ISD::COMI ||
4211 Opc == X86ISD::UCOMI) {
Evan Cheng50d37ab2007-10-08 22:16:29 +00004212 Cond = Cmp;
Evan Cheng950aac02007-09-25 01:57:46 +00004213 addTest = false;
4214 }
4215 }
4216
4217 if (addTest) {
4218 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
Evan Cheng621216e2007-09-29 00:00:36 +00004219 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
Evan Cheng950aac02007-09-25 01:57:46 +00004220 }
Evan Cheng621216e2007-09-29 00:00:36 +00004221 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
Evan Cheng950aac02007-09-25 01:57:46 +00004222 Chain, Op.getOperand(2), CC, Cond);
4223}
4224
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004225SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004226 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4227 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004228
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004229 if (Subtarget->is64Bit())
4230 if(CallingConv==CallingConv::Fast && isTailCall && PerformTailCallOpt)
4231 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4232 else
4233 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004234 else
4235 switch (CallingConv) {
4236 default:
4237 assert(0 && "Unsupported calling convention");
4238 case CallingConv::Fast:
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004239 if (isTailCall && PerformTailCallOpt)
4240 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4241 else
4242 return LowerCCCCallTo(Op,DAG, CallingConv);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004243 case CallingConv::C:
4244 case CallingConv::X86_StdCall:
4245 return LowerCCCCallTo(Op, DAG, CallingConv);
4246 case CallingConv::X86_FastCall:
4247 return LowerFastCCCallTo(Op, DAG, CallingConv);
4248 }
4249}
4250
4251
4252// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4253// Calls to _alloca is needed to probe the stack when allocating more than 4k
4254// bytes in one go. Touching the stack at 4K increments is necessary to ensure
4255// that the guard pages used by the OS virtual memory manager are allocated in
4256// correct sequence.
4257SDOperand
4258X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4259 SelectionDAG &DAG) {
4260 assert(Subtarget->isTargetCygMing() &&
4261 "This should be used only on Cygwin/Mingw targets");
4262
4263 // Get the inputs.
4264 SDOperand Chain = Op.getOperand(0);
4265 SDOperand Size = Op.getOperand(1);
4266 // FIXME: Ensure alignment here
4267
4268 SDOperand Flag;
4269
4270 MVT::ValueType IntPtr = getPointerTy();
4271 MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
4272
4273 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4274 Flag = Chain.getValue(1);
4275
4276 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4277 SDOperand Ops[] = { Chain,
4278 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4279 DAG.getRegister(X86::EAX, IntPtr),
4280 Flag };
4281 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4282 Flag = Chain.getValue(1);
4283
4284 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4285
4286 std::vector<MVT::ValueType> Tys;
4287 Tys.push_back(SPTy);
4288 Tys.push_back(MVT::Other);
4289 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4290 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4291}
4292
4293SDOperand
4294X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
4295 MachineFunction &MF = DAG.getMachineFunction();
4296 const Function* Fn = MF.getFunction();
4297 if (Fn->hasExternalLinkage() &&
4298 Subtarget->isTargetCygMing() &&
4299 Fn->getName() == "main")
4300 MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
4301
4302 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4303 if (Subtarget->is64Bit())
4304 return LowerX86_64CCCArguments(Op, DAG);
4305 else
4306 switch(CC) {
4307 default:
4308 assert(0 && "Unsupported calling convention");
4309 case CallingConv::Fast:
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004310 return LowerCCCArguments(Op,DAG, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004311 // Falls through
4312 case CallingConv::C:
4313 return LowerCCCArguments(Op, DAG);
4314 case CallingConv::X86_StdCall:
4315 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
4316 return LowerCCCArguments(Op, DAG, true);
4317 case CallingConv::X86_FastCall:
4318 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
4319 return LowerFastCCArguments(Op, DAG);
4320 }
4321}
4322
4323SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4324 SDOperand InFlag(0, 0);
4325 SDOperand Chain = Op.getOperand(0);
4326 unsigned Align =
4327 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4328 if (Align == 0) Align = 1;
4329
4330 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
Rafael Espindola5d3e7622007-08-27 10:18:20 +00004331 // If not DWORD aligned or size is more than the threshold, call memset.
Rafael Espindolab2e7a6b2007-08-27 17:48:26 +00004332 // The libc version is likely to be faster for these cases. It can use the
4333 // address value and run time information about the CPU.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004334 if ((Align & 3) != 0 ||
Rafael Espindola7afa9b12007-10-31 11:52:06 +00004335 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004336 MVT::ValueType IntPtr = getPointerTy();
4337 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4338 TargetLowering::ArgListTy Args;
4339 TargetLowering::ArgListEntry Entry;
4340 Entry.Node = Op.getOperand(1);
4341 Entry.Ty = IntPtrTy;
4342 Args.push_back(Entry);
4343 // Extend the unsigned i8 argument to be an int value for the call.
4344 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4345 Entry.Ty = IntPtrTy;
4346 Args.push_back(Entry);
4347 Entry.Node = Op.getOperand(3);
4348 Args.push_back(Entry);
4349 std::pair<SDOperand,SDOperand> CallResult =
4350 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4351 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4352 return CallResult.second;
4353 }
4354
4355 MVT::ValueType AVT;
4356 SDOperand Count;
4357 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4358 unsigned BytesLeft = 0;
4359 bool TwoRepStos = false;
4360 if (ValC) {
4361 unsigned ValReg;
4362 uint64_t Val = ValC->getValue() & 255;
4363
4364 // If the value is a constant, then we can potentially use larger sets.
4365 switch (Align & 3) {
4366 case 2: // WORD aligned
4367 AVT = MVT::i16;
4368 ValReg = X86::AX;
4369 Val = (Val << 8) | Val;
4370 break;
4371 case 0: // DWORD aligned
4372 AVT = MVT::i32;
4373 ValReg = X86::EAX;
4374 Val = (Val << 8) | Val;
4375 Val = (Val << 16) | Val;
4376 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4377 AVT = MVT::i64;
4378 ValReg = X86::RAX;
4379 Val = (Val << 32) | Val;
4380 }
4381 break;
4382 default: // Byte aligned
4383 AVT = MVT::i8;
4384 ValReg = X86::AL;
4385 Count = Op.getOperand(3);
4386 break;
4387 }
4388
4389 if (AVT > MVT::i8) {
4390 if (I) {
4391 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4392 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
4393 BytesLeft = I->getValue() % UBytes;
4394 } else {
4395 assert(AVT >= MVT::i32 &&
4396 "Do not use rep;stos if not at least DWORD aligned");
4397 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4398 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4399 TwoRepStos = true;
4400 }
4401 }
4402
4403 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4404 InFlag);
4405 InFlag = Chain.getValue(1);
4406 } else {
4407 AVT = MVT::i8;
4408 Count = Op.getOperand(3);
4409 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4410 InFlag = Chain.getValue(1);
4411 }
4412
4413 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4414 Count, InFlag);
4415 InFlag = Chain.getValue(1);
4416 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4417 Op.getOperand(1), InFlag);
4418 InFlag = Chain.getValue(1);
4419
4420 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4421 SmallVector<SDOperand, 8> Ops;
4422 Ops.push_back(Chain);
4423 Ops.push_back(DAG.getValueType(AVT));
4424 Ops.push_back(InFlag);
4425 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4426
4427 if (TwoRepStos) {
4428 InFlag = Chain.getValue(1);
4429 Count = Op.getOperand(3);
4430 MVT::ValueType CVT = Count.getValueType();
4431 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4432 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4433 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4434 Left, InFlag);
4435 InFlag = Chain.getValue(1);
4436 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4437 Ops.clear();
4438 Ops.push_back(Chain);
4439 Ops.push_back(DAG.getValueType(MVT::i8));
4440 Ops.push_back(InFlag);
4441 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4442 } else if (BytesLeft) {
4443 // Issue stores for the last 1 - 7 bytes.
4444 SDOperand Value;
4445 unsigned Val = ValC->getValue() & 255;
4446 unsigned Offset = I->getValue() - BytesLeft;
4447 SDOperand DstAddr = Op.getOperand(1);
4448 MVT::ValueType AddrVT = DstAddr.getValueType();
4449 if (BytesLeft >= 4) {
4450 Val = (Val << 8) | Val;
4451 Val = (Val << 16) | Val;
4452 Value = DAG.getConstant(Val, MVT::i32);
4453 Chain = DAG.getStore(Chain, Value,
4454 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4455 DAG.getConstant(Offset, AddrVT)),
4456 NULL, 0);
4457 BytesLeft -= 4;
4458 Offset += 4;
4459 }
4460 if (BytesLeft >= 2) {
4461 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4462 Chain = DAG.getStore(Chain, Value,
4463 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4464 DAG.getConstant(Offset, AddrVT)),
4465 NULL, 0);
4466 BytesLeft -= 2;
4467 Offset += 2;
4468 }
4469 if (BytesLeft == 1) {
4470 Value = DAG.getConstant(Val, MVT::i8);
4471 Chain = DAG.getStore(Chain, Value,
4472 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4473 DAG.getConstant(Offset, AddrVT)),
4474 NULL, 0);
4475 }
4476 }
4477
4478 return Chain;
4479}
4480
4481SDOperand X86TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004482 SDOperand ChainOp = Op.getOperand(0);
4483 SDOperand DestOp = Op.getOperand(1);
4484 SDOperand SourceOp = Op.getOperand(2);
4485 SDOperand CountOp = Op.getOperand(3);
4486 SDOperand AlignOp = Op.getOperand(4);
Rafael Espindola80825902007-10-19 10:41:11 +00004487 SDOperand AlwaysInlineOp = Op.getOperand(5);
4488
4489 bool AlwaysInline = (bool)cast<ConstantSDNode>(AlwaysInlineOp)->getValue();
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004490 unsigned Align = (unsigned)cast<ConstantSDNode>(AlignOp)->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004491 if (Align == 0) Align = 1;
4492
Rafael Espindola80825902007-10-19 10:41:11 +00004493 // If size is unknown, call memcpy.
4494 ConstantSDNode *I = dyn_cast<ConstantSDNode>(CountOp);
4495 if (!I) {
4496 assert(!AlwaysInline && "Cannot inline copy of unknown size");
4497 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
4498 }
Rafael Espindola80825902007-10-19 10:41:11 +00004499
Rafael Espindola948da402007-10-31 14:39:58 +00004500 // If not DWORD aligned or if size is more than threshold, then call memcpy.
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004501 // The libc version is likely to be faster for the following cases. It can
4502 // use the address value and run time information about the CPU.
Rafael Espindolab2e7a6b2007-08-27 17:48:26 +00004503 // With glibc 2.6.1 on a core 2, coping an array of 100M longs was 30% faster
Rafael Espindola948da402007-10-31 14:39:58 +00004504 unsigned Size = I->getValue();
4505 if (AlwaysInline ||
4506 (Size <= Subtarget->getMaxInlineSizeThreshold() &&
4507 (Align & 3) == 0))
4508 return LowerMEMCPYInline(ChainOp, DestOp, SourceOp, Size, Align, DAG);
4509 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004510}
4511
4512SDOperand X86TargetLowering::LowerMEMCPYCall(SDOperand Chain,
4513 SDOperand Dest,
4514 SDOperand Source,
4515 SDOperand Count,
4516 SelectionDAG &DAG) {
4517 MVT::ValueType IntPtr = getPointerTy();
4518 TargetLowering::ArgListTy Args;
4519 TargetLowering::ArgListEntry Entry;
4520 Entry.Ty = getTargetData()->getIntPtrType();
4521 Entry.Node = Dest; Args.push_back(Entry);
4522 Entry.Node = Source; Args.push_back(Entry);
4523 Entry.Node = Count; Args.push_back(Entry);
4524 std::pair<SDOperand,SDOperand> CallResult =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004525 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4526 DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004527 return CallResult.second;
4528}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004529
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004530SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4531 SDOperand Dest,
4532 SDOperand Source,
4533 unsigned Size,
4534 unsigned Align,
4535 SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004536 MVT::ValueType AVT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004537 unsigned BytesLeft = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004538 switch (Align & 3) {
4539 case 2: // WORD aligned
4540 AVT = MVT::i16;
4541 break;
4542 case 0: // DWORD aligned
4543 AVT = MVT::i32;
4544 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4545 AVT = MVT::i64;
4546 break;
4547 default: // Byte aligned
4548 AVT = MVT::i8;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004549 break;
4550 }
4551
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004552 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4553 SDOperand Count = DAG.getConstant(Size / UBytes, getPointerTy());
4554 BytesLeft = Size % UBytes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004555
4556 SDOperand InFlag(0, 0);
4557 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4558 Count, InFlag);
4559 InFlag = Chain.getValue(1);
4560 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004561 Dest, InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004562 InFlag = Chain.getValue(1);
4563 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004564 Source, InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004565 InFlag = Chain.getValue(1);
4566
4567 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4568 SmallVector<SDOperand, 8> Ops;
4569 Ops.push_back(Chain);
4570 Ops.push_back(DAG.getValueType(AVT));
4571 Ops.push_back(InFlag);
4572 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4573
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004574 if (BytesLeft) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004575 // Issue loads and stores for the last 1 - 7 bytes.
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004576 unsigned Offset = Size - BytesLeft;
4577 SDOperand DstAddr = Dest;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004578 MVT::ValueType DstVT = DstAddr.getValueType();
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004579 SDOperand SrcAddr = Source;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004580 MVT::ValueType SrcVT = SrcAddr.getValueType();
4581 SDOperand Value;
4582 if (BytesLeft >= 4) {
4583 Value = DAG.getLoad(MVT::i32, Chain,
4584 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4585 DAG.getConstant(Offset, SrcVT)),
4586 NULL, 0);
4587 Chain = Value.getValue(1);
4588 Chain = DAG.getStore(Chain, Value,
4589 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4590 DAG.getConstant(Offset, DstVT)),
4591 NULL, 0);
4592 BytesLeft -= 4;
4593 Offset += 4;
4594 }
4595 if (BytesLeft >= 2) {
4596 Value = DAG.getLoad(MVT::i16, Chain,
4597 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4598 DAG.getConstant(Offset, SrcVT)),
4599 NULL, 0);
4600 Chain = Value.getValue(1);
4601 Chain = DAG.getStore(Chain, Value,
4602 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4603 DAG.getConstant(Offset, DstVT)),
4604 NULL, 0);
4605 BytesLeft -= 2;
4606 Offset += 2;
4607 }
4608
4609 if (BytesLeft == 1) {
4610 Value = DAG.getLoad(MVT::i8, Chain,
4611 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4612 DAG.getConstant(Offset, SrcVT)),
4613 NULL, 0);
4614 Chain = Value.getValue(1);
4615 Chain = DAG.getStore(Chain, Value,
4616 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4617 DAG.getConstant(Offset, DstVT)),
4618 NULL, 0);
4619 }
4620 }
4621
4622 return Chain;
4623}
4624
4625SDOperand
4626X86TargetLowering::LowerREADCYCLCECOUNTER(SDOperand Op, SelectionDAG &DAG) {
4627 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4628 SDOperand TheOp = Op.getOperand(0);
4629 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheOp, 1);
4630 if (Subtarget->is64Bit()) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004631 SDOperand Copy1 =
4632 DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004633 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::RDX,
4634 MVT::i64, Copy1.getValue(2));
4635 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, Copy2,
4636 DAG.getConstant(32, MVT::i8));
4637 SDOperand Ops[] = {
4638 DAG.getNode(ISD::OR, MVT::i64, Copy1, Tmp), Copy2.getValue(1)
4639 };
4640
4641 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4642 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2);
4643 }
4644
4645 SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4646 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::EDX,
4647 MVT::i32, Copy1.getValue(2));
4648 SDOperand Ops[] = { Copy1, Copy2, Copy2.getValue(1) };
4649 Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
4650 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 3);
4651}
4652
4653SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4654 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
4655
4656 if (!Subtarget->is64Bit()) {
4657 // vastart just stores the address of the VarArgsFrameIndex slot into the
4658 // memory location argument.
4659 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4660 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
4661 SV->getOffset());
4662 }
4663
4664 // __va_list_tag:
4665 // gp_offset (0 - 6 * 8)
4666 // fp_offset (48 - 48 + 8 * 16)
4667 // overflow_arg_area (point to parameters coming in memory).
4668 // reg_save_area
4669 SmallVector<SDOperand, 8> MemOps;
4670 SDOperand FIN = Op.getOperand(1);
4671 // Store gp_offset
4672 SDOperand Store = DAG.getStore(Op.getOperand(0),
4673 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4674 FIN, SV->getValue(), SV->getOffset());
4675 MemOps.push_back(Store);
4676
4677 // Store fp_offset
4678 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4679 DAG.getConstant(4, getPointerTy()));
4680 Store = DAG.getStore(Op.getOperand(0),
4681 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4682 FIN, SV->getValue(), SV->getOffset());
4683 MemOps.push_back(Store);
4684
4685 // Store ptr to overflow_arg_area
4686 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4687 DAG.getConstant(4, getPointerTy()));
4688 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4689 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
4690 SV->getOffset());
4691 MemOps.push_back(Store);
4692
4693 // Store ptr to reg_save_area.
4694 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4695 DAG.getConstant(8, getPointerTy()));
4696 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4697 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
4698 SV->getOffset());
4699 MemOps.push_back(Store);
4700 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4701}
4702
4703SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4704 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4705 SDOperand Chain = Op.getOperand(0);
4706 SDOperand DstPtr = Op.getOperand(1);
4707 SDOperand SrcPtr = Op.getOperand(2);
4708 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
4709 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
4710
4711 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
4712 SrcSV->getValue(), SrcSV->getOffset());
4713 Chain = SrcPtr.getValue(1);
4714 for (unsigned i = 0; i < 3; ++i) {
4715 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
4716 SrcSV->getValue(), SrcSV->getOffset());
4717 Chain = Val.getValue(1);
4718 Chain = DAG.getStore(Chain, Val, DstPtr,
4719 DstSV->getValue(), DstSV->getOffset());
4720 if (i == 2)
4721 break;
4722 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
4723 DAG.getConstant(8, getPointerTy()));
4724 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
4725 DAG.getConstant(8, getPointerTy()));
4726 }
4727 return Chain;
4728}
4729
4730SDOperand
4731X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4732 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4733 switch (IntNo) {
4734 default: return SDOperand(); // Don't custom lower most intrinsics.
4735 // Comparison intrinsics.
4736 case Intrinsic::x86_sse_comieq_ss:
4737 case Intrinsic::x86_sse_comilt_ss:
4738 case Intrinsic::x86_sse_comile_ss:
4739 case Intrinsic::x86_sse_comigt_ss:
4740 case Intrinsic::x86_sse_comige_ss:
4741 case Intrinsic::x86_sse_comineq_ss:
4742 case Intrinsic::x86_sse_ucomieq_ss:
4743 case Intrinsic::x86_sse_ucomilt_ss:
4744 case Intrinsic::x86_sse_ucomile_ss:
4745 case Intrinsic::x86_sse_ucomigt_ss:
4746 case Intrinsic::x86_sse_ucomige_ss:
4747 case Intrinsic::x86_sse_ucomineq_ss:
4748 case Intrinsic::x86_sse2_comieq_sd:
4749 case Intrinsic::x86_sse2_comilt_sd:
4750 case Intrinsic::x86_sse2_comile_sd:
4751 case Intrinsic::x86_sse2_comigt_sd:
4752 case Intrinsic::x86_sse2_comige_sd:
4753 case Intrinsic::x86_sse2_comineq_sd:
4754 case Intrinsic::x86_sse2_ucomieq_sd:
4755 case Intrinsic::x86_sse2_ucomilt_sd:
4756 case Intrinsic::x86_sse2_ucomile_sd:
4757 case Intrinsic::x86_sse2_ucomigt_sd:
4758 case Intrinsic::x86_sse2_ucomige_sd:
4759 case Intrinsic::x86_sse2_ucomineq_sd: {
4760 unsigned Opc = 0;
4761 ISD::CondCode CC = ISD::SETCC_INVALID;
4762 switch (IntNo) {
4763 default: break;
4764 case Intrinsic::x86_sse_comieq_ss:
4765 case Intrinsic::x86_sse2_comieq_sd:
4766 Opc = X86ISD::COMI;
4767 CC = ISD::SETEQ;
4768 break;
4769 case Intrinsic::x86_sse_comilt_ss:
4770 case Intrinsic::x86_sse2_comilt_sd:
4771 Opc = X86ISD::COMI;
4772 CC = ISD::SETLT;
4773 break;
4774 case Intrinsic::x86_sse_comile_ss:
4775 case Intrinsic::x86_sse2_comile_sd:
4776 Opc = X86ISD::COMI;
4777 CC = ISD::SETLE;
4778 break;
4779 case Intrinsic::x86_sse_comigt_ss:
4780 case Intrinsic::x86_sse2_comigt_sd:
4781 Opc = X86ISD::COMI;
4782 CC = ISD::SETGT;
4783 break;
4784 case Intrinsic::x86_sse_comige_ss:
4785 case Intrinsic::x86_sse2_comige_sd:
4786 Opc = X86ISD::COMI;
4787 CC = ISD::SETGE;
4788 break;
4789 case Intrinsic::x86_sse_comineq_ss:
4790 case Intrinsic::x86_sse2_comineq_sd:
4791 Opc = X86ISD::COMI;
4792 CC = ISD::SETNE;
4793 break;
4794 case Intrinsic::x86_sse_ucomieq_ss:
4795 case Intrinsic::x86_sse2_ucomieq_sd:
4796 Opc = X86ISD::UCOMI;
4797 CC = ISD::SETEQ;
4798 break;
4799 case Intrinsic::x86_sse_ucomilt_ss:
4800 case Intrinsic::x86_sse2_ucomilt_sd:
4801 Opc = X86ISD::UCOMI;
4802 CC = ISD::SETLT;
4803 break;
4804 case Intrinsic::x86_sse_ucomile_ss:
4805 case Intrinsic::x86_sse2_ucomile_sd:
4806 Opc = X86ISD::UCOMI;
4807 CC = ISD::SETLE;
4808 break;
4809 case Intrinsic::x86_sse_ucomigt_ss:
4810 case Intrinsic::x86_sse2_ucomigt_sd:
4811 Opc = X86ISD::UCOMI;
4812 CC = ISD::SETGT;
4813 break;
4814 case Intrinsic::x86_sse_ucomige_ss:
4815 case Intrinsic::x86_sse2_ucomige_sd:
4816 Opc = X86ISD::UCOMI;
4817 CC = ISD::SETGE;
4818 break;
4819 case Intrinsic::x86_sse_ucomineq_ss:
4820 case Intrinsic::x86_sse2_ucomineq_sd:
4821 Opc = X86ISD::UCOMI;
4822 CC = ISD::SETNE;
4823 break;
4824 }
4825
4826 unsigned X86CC;
4827 SDOperand LHS = Op.getOperand(1);
4828 SDOperand RHS = Op.getOperand(2);
4829 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4830
Evan Cheng621216e2007-09-29 00:00:36 +00004831 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
4832 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
4833 DAG.getConstant(X86CC, MVT::i8), Cond);
4834 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004835 }
4836 }
4837}
4838
4839SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4840 // Depths > 0 not supported yet!
4841 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4842 return SDOperand();
4843
4844 // Just load the return address
4845 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4846 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4847}
4848
4849SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4850 // Depths > 0 not supported yet!
4851 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4852 return SDOperand();
4853
4854 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4855 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
4856 DAG.getConstant(4, getPointerTy()));
4857}
4858
4859SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
4860 SelectionDAG &DAG) {
4861 // Is not yet supported on x86-64
4862 if (Subtarget->is64Bit())
4863 return SDOperand();
4864
4865 return DAG.getConstant(8, getPointerTy());
4866}
4867
4868SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
4869{
4870 assert(!Subtarget->is64Bit() &&
4871 "Lowering of eh_return builtin is not supported yet on x86-64");
4872
4873 MachineFunction &MF = DAG.getMachineFunction();
4874 SDOperand Chain = Op.getOperand(0);
4875 SDOperand Offset = Op.getOperand(1);
4876 SDOperand Handler = Op.getOperand(2);
4877
4878 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
4879 getPointerTy());
4880
4881 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
4882 DAG.getConstant(-4UL, getPointerTy()));
4883 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
4884 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
4885 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
4886 MF.addLiveOut(X86::ECX);
4887
4888 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
4889 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
4890}
4891
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004892SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
4893 SelectionDAG &DAG) {
4894 SDOperand Root = Op.getOperand(0);
4895 SDOperand Trmp = Op.getOperand(1); // trampoline
4896 SDOperand FPtr = Op.getOperand(2); // nested function
4897 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
4898
4899 SrcValueSDNode *TrmpSV = cast<SrcValueSDNode>(Op.getOperand(4));
4900
4901 if (Subtarget->is64Bit()) {
4902 return SDOperand(); // not yet supported
4903 } else {
4904 Function *Func = (Function *)
4905 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
4906 unsigned CC = Func->getCallingConv();
Duncan Sands466eadd2007-08-29 19:01:20 +00004907 unsigned NestReg;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004908
4909 switch (CC) {
4910 default:
4911 assert(0 && "Unsupported calling convention");
4912 case CallingConv::C:
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004913 case CallingConv::X86_StdCall: {
4914 // Pass 'nest' parameter in ECX.
4915 // Must be kept in sync with X86CallingConv.td
Duncan Sands466eadd2007-08-29 19:01:20 +00004916 NestReg = X86::ECX;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004917
4918 // Check that ECX wasn't needed by an 'inreg' parameter.
4919 const FunctionType *FTy = Func->getFunctionType();
4920 const ParamAttrsList *Attrs = FTy->getParamAttrs();
4921
4922 if (Attrs && !Func->isVarArg()) {
4923 unsigned InRegCount = 0;
4924 unsigned Idx = 1;
4925
4926 for (FunctionType::param_iterator I = FTy->param_begin(),
4927 E = FTy->param_end(); I != E; ++I, ++Idx)
4928 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
4929 // FIXME: should only count parameters that are lowered to integers.
4930 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
4931
4932 if (InRegCount > 2) {
4933 cerr << "Nest register in use - reduce number of inreg parameters!\n";
4934 abort();
4935 }
4936 }
4937 break;
4938 }
4939 case CallingConv::X86_FastCall:
4940 // Pass 'nest' parameter in EAX.
4941 // Must be kept in sync with X86CallingConv.td
Duncan Sands466eadd2007-08-29 19:01:20 +00004942 NestReg = X86::EAX;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004943 break;
4944 }
4945
Duncan Sands466eadd2007-08-29 19:01:20 +00004946 const X86InstrInfo *TII =
4947 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
4948
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004949 SDOperand OutChains[4];
4950 SDOperand Addr, Disp;
4951
4952 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
4953 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
4954
Duncan Sands466eadd2007-08-29 19:01:20 +00004955 unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
4956 unsigned char N86Reg = ((X86RegisterInfo&)RegInfo).getX86RegNum(NestReg);
4957 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004958 Trmp, TrmpSV->getValue(), TrmpSV->getOffset());
4959
4960 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
4961 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpSV->getValue(),
4962 TrmpSV->getOffset() + 1, false, 1);
4963
Duncan Sands466eadd2007-08-29 19:01:20 +00004964 unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004965 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
4966 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
4967 TrmpSV->getValue() + 5, TrmpSV->getOffset());
4968
4969 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
4970 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpSV->getValue(),
4971 TrmpSV->getOffset() + 6, false, 1);
4972
Duncan Sands7407a9f2007-09-11 14:10:23 +00004973 SDOperand Ops[] =
4974 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
4975 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004976 }
4977}
4978
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004979/// LowerOperation - Provide custom lowering hooks for some operations.
4980///
4981SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4982 switch (Op.getOpcode()) {
4983 default: assert(0 && "Should not custom lower this!");
4984 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
4985 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
4986 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4987 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
4988 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
4989 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
4990 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
4991 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
4992 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
4993 case ISD::SHL_PARTS:
4994 case ISD::SRA_PARTS:
4995 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
4996 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
4997 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
4998 case ISD::FABS: return LowerFABS(Op, DAG);
4999 case ISD::FNEG: return LowerFNEG(Op, DAG);
5000 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
Evan Cheng621216e2007-09-29 00:00:36 +00005001 case ISD::SETCC: return LowerSETCC(Op, DAG);
5002 case ISD::SELECT: return LowerSELECT(Op, DAG);
5003 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005004 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5005 case ISD::CALL: return LowerCALL(Op, DAG);
5006 case ISD::RET: return LowerRET(Op, DAG);
5007 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5008 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5009 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
5010 case ISD::READCYCLECOUNTER: return LowerREADCYCLCECOUNTER(Op, DAG);
5011 case ISD::VASTART: return LowerVASTART(Op, DAG);
5012 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5013 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5014 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5015 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5016 case ISD::FRAME_TO_ARGS_OFFSET:
5017 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5018 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5019 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005020 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005021 }
5022 return SDOperand();
5023}
5024
5025const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5026 switch (Opcode) {
5027 default: return NULL;
5028 case X86ISD::SHLD: return "X86ISD::SHLD";
5029 case X86ISD::SHRD: return "X86ISD::SHRD";
5030 case X86ISD::FAND: return "X86ISD::FAND";
5031 case X86ISD::FOR: return "X86ISD::FOR";
5032 case X86ISD::FXOR: return "X86ISD::FXOR";
5033 case X86ISD::FSRL: return "X86ISD::FSRL";
5034 case X86ISD::FILD: return "X86ISD::FILD";
5035 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5036 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5037 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5038 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5039 case X86ISD::FLD: return "X86ISD::FLD";
5040 case X86ISD::FST: return "X86ISD::FST";
5041 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5042 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5043 case X86ISD::CALL: return "X86ISD::CALL";
5044 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5045 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5046 case X86ISD::CMP: return "X86ISD::CMP";
5047 case X86ISD::COMI: return "X86ISD::COMI";
5048 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5049 case X86ISD::SETCC: return "X86ISD::SETCC";
5050 case X86ISD::CMOV: return "X86ISD::CMOV";
5051 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5052 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5053 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5054 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005055 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5056 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5057 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5058 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5059 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5060 case X86ISD::FMAX: return "X86ISD::FMAX";
5061 case X86ISD::FMIN: return "X86ISD::FMIN";
5062 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5063 case X86ISD::FRCP: return "X86ISD::FRCP";
5064 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5065 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5066 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00005067 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005068 }
5069}
5070
5071// isLegalAddressingMode - Return true if the addressing mode represented
5072// by AM is legal for this target, for a load/store of the specified type.
5073bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5074 const Type *Ty) const {
5075 // X86 supports extremely general addressing modes.
5076
5077 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5078 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5079 return false;
5080
5081 if (AM.BaseGV) {
Evan Cheng6a1f3f12007-08-01 23:46:47 +00005082 // We can only fold this if we don't need an extra load.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005083 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5084 return false;
Evan Cheng6a1f3f12007-08-01 23:46:47 +00005085
5086 // X86-64 only supports addr of globals in small code model.
5087 if (Subtarget->is64Bit()) {
5088 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5089 return false;
5090 // If lower 4G is not available, then we must use rip-relative addressing.
5091 if (AM.BaseOffs || AM.Scale > 1)
5092 return false;
5093 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005094 }
5095
5096 switch (AM.Scale) {
5097 case 0:
5098 case 1:
5099 case 2:
5100 case 4:
5101 case 8:
5102 // These scales always work.
5103 break;
5104 case 3:
5105 case 5:
5106 case 9:
5107 // These scales are formed with basereg+scalereg. Only accept if there is
5108 // no basereg yet.
5109 if (AM.HasBaseReg)
5110 return false;
5111 break;
5112 default: // Other stuff never works.
5113 return false;
5114 }
5115
5116 return true;
5117}
5118
5119
Evan Cheng27a820a2007-10-26 01:56:11 +00005120bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5121 if (!Ty1->isInteger() || !Ty2->isInteger())
5122 return false;
Evan Cheng7f152602007-10-29 07:57:50 +00005123 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5124 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5125 if (NumBits1 <= NumBits2)
5126 return false;
5127 return Subtarget->is64Bit() || NumBits1 < 64;
Evan Cheng27a820a2007-10-26 01:56:11 +00005128}
5129
Evan Cheng9decb332007-10-29 19:58:20 +00005130bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5131 MVT::ValueType VT2) const {
5132 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5133 return false;
5134 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5135 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5136 if (NumBits1 <= NumBits2)
5137 return false;
5138 return Subtarget->is64Bit() || NumBits1 < 64;
5139}
Evan Cheng27a820a2007-10-26 01:56:11 +00005140
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005141/// isShuffleMaskLegal - Targets can use this to indicate that they only
5142/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5143/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5144/// are assumed to be legal.
5145bool
5146X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5147 // Only do shuffles on 128-bit vector types for now.
5148 if (MVT::getSizeInBits(VT) == 64) return false;
5149 return (Mask.Val->getNumOperands() <= 4 ||
5150 isIdentityMask(Mask.Val) ||
5151 isIdentityMask(Mask.Val, true) ||
5152 isSplatMask(Mask.Val) ||
5153 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5154 X86::isUNPCKLMask(Mask.Val) ||
5155 X86::isUNPCKHMask(Mask.Val) ||
5156 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5157 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5158}
5159
5160bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5161 MVT::ValueType EVT,
5162 SelectionDAG &DAG) const {
5163 unsigned NumElts = BVOps.size();
5164 // Only do shuffles on 128-bit vector types for now.
5165 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5166 if (NumElts == 2) return true;
5167 if (NumElts == 4) {
5168 return (isMOVLMask(&BVOps[0], 4) ||
5169 isCommutedMOVL(&BVOps[0], 4, true) ||
5170 isSHUFPMask(&BVOps[0], 4) ||
5171 isCommutedSHUFP(&BVOps[0], 4));
5172 }
5173 return false;
5174}
5175
5176//===----------------------------------------------------------------------===//
5177// X86 Scheduler Hooks
5178//===----------------------------------------------------------------------===//
5179
5180MachineBasicBlock *
5181X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
5182 MachineBasicBlock *BB) {
5183 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5184 switch (MI->getOpcode()) {
5185 default: assert(false && "Unexpected instr type to insert");
5186 case X86::CMOV_FR32:
5187 case X86::CMOV_FR64:
5188 case X86::CMOV_V4F32:
5189 case X86::CMOV_V2F64:
Evan Cheng621216e2007-09-29 00:00:36 +00005190 case X86::CMOV_V2I64: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005191 // To "insert" a SELECT_CC instruction, we actually have to insert the
5192 // diamond control-flow pattern. The incoming instruction knows the
5193 // destination vreg to set, the condition code register to branch on, the
5194 // true/false values to select between, and a branch opcode to use.
5195 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5196 ilist<MachineBasicBlock>::iterator It = BB;
5197 ++It;
5198
5199 // thisMBB:
5200 // ...
5201 // TrueVal = ...
5202 // cmpTY ccX, r1, r2
5203 // bCC copy1MBB
5204 // fallthrough --> copy0MBB
5205 MachineBasicBlock *thisMBB = BB;
5206 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5207 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5208 unsigned Opc =
5209 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5210 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5211 MachineFunction *F = BB->getParent();
5212 F->getBasicBlockList().insert(It, copy0MBB);
5213 F->getBasicBlockList().insert(It, sinkMBB);
5214 // Update machine-CFG edges by first adding all successors of the current
5215 // block to the new block which will contain the Phi node for the select.
5216 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5217 e = BB->succ_end(); i != e; ++i)
5218 sinkMBB->addSuccessor(*i);
5219 // Next, remove all successors of the current block, and add the true
5220 // and fallthrough blocks as its successors.
5221 while(!BB->succ_empty())
5222 BB->removeSuccessor(BB->succ_begin());
5223 BB->addSuccessor(copy0MBB);
5224 BB->addSuccessor(sinkMBB);
5225
5226 // copy0MBB:
5227 // %FalseValue = ...
5228 // # fallthrough to sinkMBB
5229 BB = copy0MBB;
5230
5231 // Update machine-CFG edges
5232 BB->addSuccessor(sinkMBB);
5233
5234 // sinkMBB:
5235 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5236 // ...
5237 BB = sinkMBB;
5238 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5239 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5240 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5241
5242 delete MI; // The pseudo instruction is gone now.
5243 return BB;
5244 }
5245
5246 case X86::FP32_TO_INT16_IN_MEM:
5247 case X86::FP32_TO_INT32_IN_MEM:
5248 case X86::FP32_TO_INT64_IN_MEM:
5249 case X86::FP64_TO_INT16_IN_MEM:
5250 case X86::FP64_TO_INT32_IN_MEM:
Dale Johannesen6d0e36a2007-08-07 01:17:37 +00005251 case X86::FP64_TO_INT64_IN_MEM:
5252 case X86::FP80_TO_INT16_IN_MEM:
5253 case X86::FP80_TO_INT32_IN_MEM:
5254 case X86::FP80_TO_INT64_IN_MEM: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005255 // Change the floating point control register to use "round towards zero"
5256 // mode when truncating to an integer value.
5257 MachineFunction *F = BB->getParent();
5258 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5259 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5260
5261 // Load the old value of the high byte of the control word...
5262 unsigned OldCW =
5263 F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
5264 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5265
5266 // Set the high part to be round to zero...
5267 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5268 .addImm(0xC7F);
5269
5270 // Reload the modified control word now...
5271 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5272
5273 // Restore the memory image of control word to original value
5274 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5275 .addReg(OldCW);
5276
5277 // Get the X86 opcode to use.
5278 unsigned Opc;
5279 switch (MI->getOpcode()) {
5280 default: assert(0 && "illegal opcode!");
5281 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5282 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5283 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5284 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5285 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5286 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
Dale Johannesen6d0e36a2007-08-07 01:17:37 +00005287 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5288 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5289 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005290 }
5291
5292 X86AddressMode AM;
5293 MachineOperand &Op = MI->getOperand(0);
5294 if (Op.isRegister()) {
5295 AM.BaseType = X86AddressMode::RegBase;
5296 AM.Base.Reg = Op.getReg();
5297 } else {
5298 AM.BaseType = X86AddressMode::FrameIndexBase;
5299 AM.Base.FrameIndex = Op.getFrameIndex();
5300 }
5301 Op = MI->getOperand(1);
5302 if (Op.isImmediate())
5303 AM.Scale = Op.getImm();
5304 Op = MI->getOperand(2);
5305 if (Op.isImmediate())
5306 AM.IndexReg = Op.getImm();
5307 Op = MI->getOperand(3);
5308 if (Op.isGlobalAddress()) {
5309 AM.GV = Op.getGlobal();
5310 } else {
5311 AM.Disp = Op.getImm();
5312 }
5313 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5314 .addReg(MI->getOperand(4).getReg());
5315
5316 // Reload the original control word now.
5317 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5318
5319 delete MI; // The pseudo instruction is gone now.
5320 return BB;
5321 }
5322 }
5323}
5324
5325//===----------------------------------------------------------------------===//
5326// X86 Optimization Hooks
5327//===----------------------------------------------------------------------===//
5328
5329void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5330 uint64_t Mask,
5331 uint64_t &KnownZero,
5332 uint64_t &KnownOne,
5333 const SelectionDAG &DAG,
5334 unsigned Depth) const {
5335 unsigned Opc = Op.getOpcode();
5336 assert((Opc >= ISD::BUILTIN_OP_END ||
5337 Opc == ISD::INTRINSIC_WO_CHAIN ||
5338 Opc == ISD::INTRINSIC_W_CHAIN ||
5339 Opc == ISD::INTRINSIC_VOID) &&
5340 "Should use MaskedValueIsZero if you don't know whether Op"
5341 " is a target node!");
5342
5343 KnownZero = KnownOne = 0; // Don't know anything.
5344 switch (Opc) {
5345 default: break;
5346 case X86ISD::SETCC:
5347 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5348 break;
5349 }
5350}
5351
5352/// getShuffleScalarElt - Returns the scalar element that will make up the ith
5353/// element of the result of the vector shuffle.
5354static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5355 MVT::ValueType VT = N->getValueType(0);
5356 SDOperand PermMask = N->getOperand(2);
5357 unsigned NumElems = PermMask.getNumOperands();
5358 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5359 i %= NumElems;
5360 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5361 return (i == 0)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00005362 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005363 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5364 SDOperand Idx = PermMask.getOperand(i);
5365 if (Idx.getOpcode() == ISD::UNDEF)
5366 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5367 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5368 }
5369 return SDOperand();
5370}
5371
5372/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5373/// node is a GlobalAddress + an offset.
5374static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5375 unsigned Opc = N->getOpcode();
5376 if (Opc == X86ISD::Wrapper) {
5377 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5378 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5379 return true;
5380 }
5381 } else if (Opc == ISD::ADD) {
5382 SDOperand N1 = N->getOperand(0);
5383 SDOperand N2 = N->getOperand(1);
5384 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5385 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5386 if (V) {
5387 Offset += V->getSignExtended();
5388 return true;
5389 }
5390 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5391 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5392 if (V) {
5393 Offset += V->getSignExtended();
5394 return true;
5395 }
5396 }
5397 }
5398 return false;
5399}
5400
5401/// isConsecutiveLoad - Returns true if N is loading from an address of Base
5402/// + Dist * Size.
5403static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5404 MachineFrameInfo *MFI) {
5405 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5406 return false;
5407
5408 SDOperand Loc = N->getOperand(1);
5409 SDOperand BaseLoc = Base->getOperand(1);
5410 if (Loc.getOpcode() == ISD::FrameIndex) {
5411 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5412 return false;
Dan Gohman53491e92007-07-23 20:24:29 +00005413 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5414 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005415 int FS = MFI->getObjectSize(FI);
5416 int BFS = MFI->getObjectSize(BFI);
5417 if (FS != BFS || FS != Size) return false;
5418 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5419 } else {
5420 GlobalValue *GV1 = NULL;
5421 GlobalValue *GV2 = NULL;
5422 int64_t Offset1 = 0;
5423 int64_t Offset2 = 0;
5424 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5425 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5426 if (isGA1 && isGA2 && GV1 == GV2)
5427 return Offset1 == (Offset2 + Dist*Size);
5428 }
5429
5430 return false;
5431}
5432
5433static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5434 const X86Subtarget *Subtarget) {
5435 GlobalValue *GV;
5436 int64_t Offset;
5437 if (isGAPlusOffset(Base, GV, Offset))
5438 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5439 else {
5440 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
Dan Gohman53491e92007-07-23 20:24:29 +00005441 int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005442 if (BFI < 0)
5443 // Fixed objects do not specify alignment, however the offsets are known.
5444 return ((Subtarget->getStackAlignment() % 16) == 0 &&
5445 (MFI->getObjectOffset(BFI) % 16) == 0);
5446 else
5447 return MFI->getObjectAlignment(BFI) >= 16;
5448 }
5449 return false;
5450}
5451
5452
5453/// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5454/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5455/// if the load addresses are consecutive, non-overlapping, and in the right
5456/// order.
5457static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5458 const X86Subtarget *Subtarget) {
5459 MachineFunction &MF = DAG.getMachineFunction();
5460 MachineFrameInfo *MFI = MF.getFrameInfo();
5461 MVT::ValueType VT = N->getValueType(0);
5462 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5463 SDOperand PermMask = N->getOperand(2);
5464 int NumElems = (int)PermMask.getNumOperands();
5465 SDNode *Base = NULL;
5466 for (int i = 0; i < NumElems; ++i) {
5467 SDOperand Idx = PermMask.getOperand(i);
5468 if (Idx.getOpcode() == ISD::UNDEF) {
5469 if (!Base) return SDOperand();
5470 } else {
5471 SDOperand Arg =
5472 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5473 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5474 return SDOperand();
5475 if (!Base)
5476 Base = Arg.Val;
5477 else if (!isConsecutiveLoad(Arg.Val, Base,
5478 i, MVT::getSizeInBits(EVT)/8,MFI))
5479 return SDOperand();
5480 }
5481 }
5482
5483 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
Dan Gohman11821702007-07-27 17:16:43 +00005484 LoadSDNode *LD = cast<LoadSDNode>(Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005485 if (isAlign16) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005486 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
Dan Gohman11821702007-07-27 17:16:43 +00005487 LD->getSrcValueOffset(), LD->isVolatile());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005488 } else {
Dan Gohman11821702007-07-27 17:16:43 +00005489 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5490 LD->getSrcValueOffset(), LD->isVolatile(),
5491 LD->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005492 }
5493}
5494
5495/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5496static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5497 const X86Subtarget *Subtarget) {
5498 SDOperand Cond = N->getOperand(0);
5499
5500 // If we have SSE[12] support, try to form min/max nodes.
5501 if (Subtarget->hasSSE2() &&
5502 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5503 if (Cond.getOpcode() == ISD::SETCC) {
5504 // Get the LHS/RHS of the select.
5505 SDOperand LHS = N->getOperand(1);
5506 SDOperand RHS = N->getOperand(2);
5507 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5508
5509 unsigned Opcode = 0;
5510 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5511 switch (CC) {
5512 default: break;
5513 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5514 case ISD::SETULE:
5515 case ISD::SETLE:
5516 if (!UnsafeFPMath) break;
5517 // FALL THROUGH.
5518 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
5519 case ISD::SETLT:
5520 Opcode = X86ISD::FMIN;
5521 break;
5522
5523 case ISD::SETOGT: // (X > Y) ? X : Y -> max
5524 case ISD::SETUGT:
5525 case ISD::SETGT:
5526 if (!UnsafeFPMath) break;
5527 // FALL THROUGH.
5528 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
5529 case ISD::SETGE:
5530 Opcode = X86ISD::FMAX;
5531 break;
5532 }
5533 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5534 switch (CC) {
5535 default: break;
5536 case ISD::SETOGT: // (X > Y) ? Y : X -> min
5537 case ISD::SETUGT:
5538 case ISD::SETGT:
5539 if (!UnsafeFPMath) break;
5540 // FALL THROUGH.
5541 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
5542 case ISD::SETGE:
5543 Opcode = X86ISD::FMIN;
5544 break;
5545
5546 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
5547 case ISD::SETULE:
5548 case ISD::SETLE:
5549 if (!UnsafeFPMath) break;
5550 // FALL THROUGH.
5551 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
5552 case ISD::SETLT:
5553 Opcode = X86ISD::FMAX;
5554 break;
5555 }
5556 }
5557
5558 if (Opcode)
5559 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5560 }
5561
5562 }
5563
5564 return SDOperand();
5565}
5566
5567
5568SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5569 DAGCombinerInfo &DCI) const {
5570 SelectionDAG &DAG = DCI.DAG;
5571 switch (N->getOpcode()) {
5572 default: break;
5573 case ISD::VECTOR_SHUFFLE:
5574 return PerformShuffleCombine(N, DAG, Subtarget);
5575 case ISD::SELECT:
5576 return PerformSELECTCombine(N, DAG, Subtarget);
5577 }
5578
5579 return SDOperand();
5580}
5581
5582//===----------------------------------------------------------------------===//
5583// X86 Inline Assembly Support
5584//===----------------------------------------------------------------------===//
5585
5586/// getConstraintType - Given a constraint letter, return the type of
5587/// constraint it is for this target.
5588X86TargetLowering::ConstraintType
5589X86TargetLowering::getConstraintType(const std::string &Constraint) const {
5590 if (Constraint.size() == 1) {
5591 switch (Constraint[0]) {
5592 case 'A':
5593 case 'r':
5594 case 'R':
5595 case 'l':
5596 case 'q':
5597 case 'Q':
5598 case 'x':
5599 case 'Y':
5600 return C_RegisterClass;
5601 default:
5602 break;
5603 }
5604 }
5605 return TargetLowering::getConstraintType(Constraint);
5606}
5607
Chris Lattnera531abc2007-08-25 00:47:38 +00005608/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5609/// vector. If it is invalid, don't add anything to Ops.
5610void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
5611 char Constraint,
5612 std::vector<SDOperand>&Ops,
5613 SelectionDAG &DAG) {
5614 SDOperand Result(0, 0);
5615
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005616 switch (Constraint) {
5617 default: break;
5618 case 'I':
5619 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
Chris Lattnera531abc2007-08-25 00:47:38 +00005620 if (C->getValue() <= 31) {
5621 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5622 break;
5623 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005624 }
Chris Lattnera531abc2007-08-25 00:47:38 +00005625 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005626 case 'N':
5627 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
Chris Lattnera531abc2007-08-25 00:47:38 +00005628 if (C->getValue() <= 255) {
5629 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5630 break;
5631 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005632 }
Chris Lattnera531abc2007-08-25 00:47:38 +00005633 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005634 case 'i': {
5635 // Literal immediates are always ok.
Chris Lattnera531abc2007-08-25 00:47:38 +00005636 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
5637 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
5638 break;
5639 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005640
5641 // If we are in non-pic codegen mode, we allow the address of a global (with
5642 // an optional displacement) to be used with 'i'.
5643 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
5644 int64_t Offset = 0;
5645
5646 // Match either (GA) or (GA+C)
5647 if (GA) {
5648 Offset = GA->getOffset();
5649 } else if (Op.getOpcode() == ISD::ADD) {
5650 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5651 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5652 if (C && GA) {
5653 Offset = GA->getOffset()+C->getValue();
5654 } else {
5655 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5656 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5657 if (C && GA)
5658 Offset = GA->getOffset()+C->getValue();
5659 else
5660 C = 0, GA = 0;
5661 }
5662 }
5663
5664 if (GA) {
5665 // If addressing this global requires a load (e.g. in PIC mode), we can't
5666 // match.
5667 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
5668 false))
Chris Lattnera531abc2007-08-25 00:47:38 +00005669 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005670
5671 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5672 Offset);
Chris Lattnera531abc2007-08-25 00:47:38 +00005673 Result = Op;
5674 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005675 }
5676
5677 // Otherwise, not valid for this mode.
Chris Lattnera531abc2007-08-25 00:47:38 +00005678 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005679 }
5680 }
Chris Lattnera531abc2007-08-25 00:47:38 +00005681
5682 if (Result.Val) {
5683 Ops.push_back(Result);
5684 return;
5685 }
5686 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005687}
5688
5689std::vector<unsigned> X86TargetLowering::
5690getRegClassForInlineAsmConstraint(const std::string &Constraint,
5691 MVT::ValueType VT) const {
5692 if (Constraint.size() == 1) {
5693 // FIXME: not handling fp-stack yet!
5694 switch (Constraint[0]) { // GCC X86 Constraint Letters
5695 default: break; // Unknown constraint letter
5696 case 'A': // EAX/EDX
5697 if (VT == MVT::i32 || VT == MVT::i64)
5698 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
5699 break;
5700 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
5701 case 'Q': // Q_REGS
5702 if (VT == MVT::i32)
5703 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
5704 else if (VT == MVT::i16)
5705 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
5706 else if (VT == MVT::i8)
Evan Chengf85c10f2007-08-13 23:27:11 +00005707 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005708 break;
5709 }
5710 }
5711
5712 return std::vector<unsigned>();
5713}
5714
5715std::pair<unsigned, const TargetRegisterClass*>
5716X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
5717 MVT::ValueType VT) const {
5718 // First, see if this is a constraint that directly corresponds to an LLVM
5719 // register class.
5720 if (Constraint.size() == 1) {
5721 // GCC Constraint Letters
5722 switch (Constraint[0]) {
5723 default: break;
5724 case 'r': // GENERAL_REGS
5725 case 'R': // LEGACY_REGS
5726 case 'l': // INDEX_REGS
5727 if (VT == MVT::i64 && Subtarget->is64Bit())
5728 return std::make_pair(0U, X86::GR64RegisterClass);
5729 if (VT == MVT::i32)
5730 return std::make_pair(0U, X86::GR32RegisterClass);
5731 else if (VT == MVT::i16)
5732 return std::make_pair(0U, X86::GR16RegisterClass);
5733 else if (VT == MVT::i8)
5734 return std::make_pair(0U, X86::GR8RegisterClass);
5735 break;
5736 case 'y': // MMX_REGS if MMX allowed.
5737 if (!Subtarget->hasMMX()) break;
5738 return std::make_pair(0U, X86::VR64RegisterClass);
5739 break;
5740 case 'Y': // SSE_REGS if SSE2 allowed
5741 if (!Subtarget->hasSSE2()) break;
5742 // FALL THROUGH.
5743 case 'x': // SSE_REGS if SSE1 allowed
5744 if (!Subtarget->hasSSE1()) break;
5745
5746 switch (VT) {
5747 default: break;
5748 // Scalar SSE types.
5749 case MVT::f32:
5750 case MVT::i32:
5751 return std::make_pair(0U, X86::FR32RegisterClass);
5752 case MVT::f64:
5753 case MVT::i64:
5754 return std::make_pair(0U, X86::FR64RegisterClass);
5755 // Vector types.
5756 case MVT::v16i8:
5757 case MVT::v8i16:
5758 case MVT::v4i32:
5759 case MVT::v2i64:
5760 case MVT::v4f32:
5761 case MVT::v2f64:
5762 return std::make_pair(0U, X86::VR128RegisterClass);
5763 }
5764 break;
5765 }
5766 }
5767
5768 // Use the default implementation in TargetLowering to convert the register
5769 // constraint into a member of a register class.
5770 std::pair<unsigned, const TargetRegisterClass*> Res;
5771 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
5772
5773 // Not found as a standard register?
5774 if (Res.second == 0) {
5775 // GCC calls "st(0)" just plain "st".
5776 if (StringsEqualNoCase("{st}", Constraint)) {
5777 Res.first = X86::ST0;
Chris Lattner3cfe51b2007-09-24 05:27:37 +00005778 Res.second = X86::RFP80RegisterClass;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005779 }
5780
5781 return Res;
5782 }
5783
5784 // Otherwise, check to see if this is a register class of the wrong value
5785 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
5786 // turn into {ax},{dx}.
5787 if (Res.second->hasType(VT))
5788 return Res; // Correct type already, nothing to do.
5789
5790 // All of the single-register GCC register classes map their values onto
5791 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
5792 // really want an 8-bit or 32-bit register, map to the appropriate register
5793 // class and return the appropriate register.
5794 if (Res.second != X86::GR16RegisterClass)
5795 return Res;
5796
5797 if (VT == MVT::i8) {
5798 unsigned DestReg = 0;
5799 switch (Res.first) {
5800 default: break;
5801 case X86::AX: DestReg = X86::AL; break;
5802 case X86::DX: DestReg = X86::DL; break;
5803 case X86::CX: DestReg = X86::CL; break;
5804 case X86::BX: DestReg = X86::BL; break;
5805 }
5806 if (DestReg) {
5807 Res.first = DestReg;
5808 Res.second = Res.second = X86::GR8RegisterClass;
5809 }
5810 } else if (VT == MVT::i32) {
5811 unsigned DestReg = 0;
5812 switch (Res.first) {
5813 default: break;
5814 case X86::AX: DestReg = X86::EAX; break;
5815 case X86::DX: DestReg = X86::EDX; break;
5816 case X86::CX: DestReg = X86::ECX; break;
5817 case X86::BX: DestReg = X86::EBX; break;
5818 case X86::SI: DestReg = X86::ESI; break;
5819 case X86::DI: DestReg = X86::EDI; break;
5820 case X86::BP: DestReg = X86::EBP; break;
5821 case X86::SP: DestReg = X86::ESP; break;
5822 }
5823 if (DestReg) {
5824 Res.first = DestReg;
5825 Res.second = Res.second = X86::GR32RegisterClass;
5826 }
5827 } else if (VT == MVT::i64) {
5828 unsigned DestReg = 0;
5829 switch (Res.first) {
5830 default: break;
5831 case X86::AX: DestReg = X86::RAX; break;
5832 case X86::DX: DestReg = X86::RDX; break;
5833 case X86::CX: DestReg = X86::RCX; break;
5834 case X86::BX: DestReg = X86::RBX; break;
5835 case X86::SI: DestReg = X86::RSI; break;
5836 case X86::DI: DestReg = X86::RDI; break;
5837 case X86::BP: DestReg = X86::RBP; break;
5838 case X86::SP: DestReg = X86::RSP; break;
5839 }
5840 if (DestReg) {
5841 Res.first = DestReg;
5842 Res.second = Res.second = X86::GR64RegisterClass;
5843 }
5844 }
5845
5846 return Res;
5847}