blob: 83751412e950ee93ed34809a7cbcf7470bf1b8b5 [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"
Evan Cheng75184a92007-12-11 01:46:18 +000026#include "llvm/ADT/BitVector.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/ADT/VectorExtras.h"
28#include "llvm/Analysis/ScalarEvolutionExpressions.h"
29#include "llvm/CodeGen/CallingConvLower.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/CodeGen/SSARegMap.h"
35#include "llvm/Support/MathExtras.h"
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +000036#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038#include "llvm/Target/TargetOptions.h"
Evan Cheng75184a92007-12-11 01:46:18 +000039#include "llvm/ADT/SmallSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/ADT/StringExtras.h"
Duncan Sandsd8455ca2007-07-27 20:02:49 +000041#include "llvm/ParameterAttributes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042using namespace llvm;
43
44X86TargetLowering::X86TargetLowering(TargetMachine &TM)
45 : TargetLowering(TM) {
46 Subtarget = &TM.getSubtarget<X86Subtarget>();
Dale Johannesene0e0fd02007-09-23 14:52:20 +000047 X86ScalarSSEf64 = Subtarget->hasSSE2();
48 X86ScalarSSEf32 = Subtarget->hasSSE1();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +000050
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051
52 RegInfo = TM.getRegisterInfo();
53
54 // Set up the TargetLowering object.
55
56 // X86 is weird, it always uses i8 for shift amounts and setcc results.
57 setShiftAmountType(MVT::i8);
58 setSetCCResultType(MVT::i8);
59 setSetCCResultContents(ZeroOrOneSetCCResult);
60 setSchedulingPreference(SchedulingForRegPressure);
61 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
62 setStackPointerRegisterToSaveRestore(X86StackPtr);
63
64 if (Subtarget->isTargetDarwin()) {
65 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
66 setUseUnderscoreSetJmp(false);
67 setUseUnderscoreLongJmp(false);
68 } else if (Subtarget->isTargetMingw()) {
69 // MS runtime is weird: it exports _setjmp, but longjmp!
70 setUseUnderscoreSetJmp(true);
71 setUseUnderscoreLongJmp(false);
72 } else {
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(true);
75 }
76
77 // Set up the register classes.
78 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
79 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
80 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
81 if (Subtarget->is64Bit())
82 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
83
84 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
85
86 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
87 // operation.
88 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
89 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
90 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
91
92 if (Subtarget->is64Bit()) {
93 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
94 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
95 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +000096 if (X86ScalarSSEf64)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
98 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
99 else
100 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
101 }
102
103 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
104 // this operation.
105 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
106 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
107 // SSE has no i16 to fp conversion, only i32
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000108 if (X86ScalarSSEf32) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000109 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000110 // f32 and f64 cases are Legal, f80 case is not
111 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
112 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
114 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
115 }
116
Dale Johannesen958b08b2007-09-19 23:55:34 +0000117 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
118 // are Legal, f80 is custom lowered.
119 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
120 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000121
122 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
123 // this operation.
124 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
125 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
126
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000127 if (X86ScalarSSEf32) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000129 // f32 and f64 cases are Legal, f80 case is not
130 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131 } else {
132 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
133 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
134 }
135
136 // Handle FP_TO_UINT by promoting the destination to a larger signed
137 // conversion.
138 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
139 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
140 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
141
142 if (Subtarget->is64Bit()) {
143 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
144 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
145 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000146 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147 // Expand FP_TO_UINT into a select.
148 // FIXME: We would like to use a Custom expander here eventually to do
149 // the optimal thing for SSE vs. the default expansion in the legalizer.
150 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
151 else
152 // With SSE3 we can use fisttpll to convert to a signed i64.
153 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
154 }
155
156 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000157 if (!X86ScalarSSEf64) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
159 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
160 }
161
Dan Gohman5a199552007-10-08 18:33:35 +0000162 // Scalar integer multiply, multiply-high, divide, and remainder are
163 // lowered to use operations that produce two results, to match the
164 // available instructions. This exposes the two-result form to trivial
165 // CSE, which is able to combine x/y and x%y into a single instruction,
166 // for example. The single-result multiply instructions are introduced
167 // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
168 // is not needed.
169 setOperationAction(ISD::MUL , MVT::i8 , Expand);
170 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
171 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
172 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
173 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
174 setOperationAction(ISD::SREM , MVT::i8 , Expand);
175 setOperationAction(ISD::UREM , MVT::i8 , Expand);
176 setOperationAction(ISD::MUL , MVT::i16 , Expand);
177 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
178 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
179 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
180 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
181 setOperationAction(ISD::SREM , MVT::i16 , Expand);
182 setOperationAction(ISD::UREM , MVT::i16 , Expand);
183 setOperationAction(ISD::MUL , MVT::i32 , Expand);
184 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
185 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
186 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
187 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
188 setOperationAction(ISD::SREM , MVT::i32 , Expand);
189 setOperationAction(ISD::UREM , MVT::i32 , Expand);
190 setOperationAction(ISD::MUL , MVT::i64 , Expand);
191 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
192 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
193 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
194 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
195 setOperationAction(ISD::SREM , MVT::i64 , Expand);
196 setOperationAction(ISD::UREM , MVT::i64 , Expand);
Dan Gohman242a5ba2007-09-25 18:23:27 +0000197
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
199 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
200 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
201 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
202 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
203 if (Subtarget->is64Bit())
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
206 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
208 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
209 setOperationAction(ISD::FREM , MVT::f64 , Expand);
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +0000210 setOperationAction(ISD::FLT_ROUNDS , MVT::i32 , Custom);
211
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
213 setOperationAction(ISD::CTTZ , MVT::i8 , Expand);
214 setOperationAction(ISD::CTLZ , MVT::i8 , Expand);
215 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
216 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
217 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
218 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
219 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
220 setOperationAction(ISD::CTLZ , MVT::i32 , Expand);
221 if (Subtarget->is64Bit()) {
222 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
223 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
224 setOperationAction(ISD::CTLZ , MVT::i64 , Expand);
225 }
226
227 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
228 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
229
230 // These should be promoted to a larger select which is supported.
231 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
232 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
233 // X86 wants to expand cmov itself.
234 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
235 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
236 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
237 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000238 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
240 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
241 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
242 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
243 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000244 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245 if (Subtarget->is64Bit()) {
246 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
247 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
248 }
249 // X86 ret instruction may pop stack.
250 setOperationAction(ISD::RET , MVT::Other, Custom);
251 if (!Subtarget->is64Bit())
252 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
253
254 // Darwin ABI issue.
255 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
256 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
257 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
258 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
259 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
260 if (Subtarget->is64Bit()) {
261 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
262 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
263 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
264 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
265 }
266 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
267 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
268 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
269 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
270 // X86 wants to expand memset / memcpy itself.
271 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
272 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
273
Dan Gohman21442852007-09-25 15:10:49 +0000274 // Use the default ISD::LOCATION expansion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 // FIXME - use subtarget debug flags
277 if (!Subtarget->isTargetDarwin() &&
278 !Subtarget->isTargetELF() &&
279 !Subtarget->isTargetCygMing())
280 setOperationAction(ISD::LABEL, MVT::Other, Expand);
281
282 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
283 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
284 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
285 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
286 if (Subtarget->is64Bit()) {
287 // FIXME: Verify
288 setExceptionPointerRegister(X86::RAX);
289 setExceptionSelectorRegister(X86::RDX);
290 } else {
291 setExceptionPointerRegister(X86::EAX);
292 setExceptionSelectorRegister(X86::EDX);
293 }
Anton Korobeynikov23ca9c52007-09-03 00:36:06 +0000294 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295
Duncan Sands7407a9f2007-09-11 14:10:23 +0000296 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
Duncan Sandsd8455ca2007-07-27 20:02:49 +0000297
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
299 setOperationAction(ISD::VASTART , MVT::Other, Custom);
300 setOperationAction(ISD::VAARG , MVT::Other, Expand);
301 setOperationAction(ISD::VAEND , MVT::Other, Expand);
302 if (Subtarget->is64Bit())
303 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
304 else
305 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
306
307 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
308 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
309 if (Subtarget->is64Bit())
310 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
311 if (Subtarget->isTargetCygMing())
312 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
313 else
314 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
315
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000316 if (X86ScalarSSEf64) {
317 // f32 and f64 use SSE.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318 // Set up the FP register classes.
319 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
320 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
321
322 // Use ANDPD to simulate FABS.
323 setOperationAction(ISD::FABS , MVT::f64, Custom);
324 setOperationAction(ISD::FABS , MVT::f32, Custom);
325
326 // Use XORP to simulate FNEG.
327 setOperationAction(ISD::FNEG , MVT::f64, Custom);
328 setOperationAction(ISD::FNEG , MVT::f32, Custom);
329
330 // Use ANDPD and ORPD to simulate FCOPYSIGN.
331 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
332 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
333
334 // We don't support sin/cos/fmod
335 setOperationAction(ISD::FSIN , MVT::f64, Expand);
336 setOperationAction(ISD::FCOS , MVT::f64, Expand);
337 setOperationAction(ISD::FREM , MVT::f64, Expand);
338 setOperationAction(ISD::FSIN , MVT::f32, Expand);
339 setOperationAction(ISD::FCOS , MVT::f32, Expand);
340 setOperationAction(ISD::FREM , MVT::f32, Expand);
341
342 // Expand FP immediates into loads from the stack, except for the special
343 // cases we handle.
344 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
345 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000346 addLegalFPImmediate(APFloat(+0.0)); // xorpd
347 addLegalFPImmediate(APFloat(+0.0f)); // xorps
Dale Johannesen8f83a6b2007-08-09 01:04:01 +0000348
349 // Conversions to long double (in X87) go through memory.
350 setConvertAction(MVT::f32, MVT::f80, Expand);
351 setConvertAction(MVT::f64, MVT::f80, Expand);
352
353 // Conversions from long double (in X87) go through memory.
354 setConvertAction(MVT::f80, MVT::f32, Expand);
355 setConvertAction(MVT::f80, MVT::f64, Expand);
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000356 } else if (X86ScalarSSEf32) {
357 // Use SSE for f32, x87 for f64.
358 // Set up the FP register classes.
359 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
360 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
361
362 // Use ANDPS to simulate FABS.
363 setOperationAction(ISD::FABS , MVT::f32, Custom);
364
365 // Use XORP to simulate FNEG.
366 setOperationAction(ISD::FNEG , MVT::f32, Custom);
367
368 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
369
370 // Use ANDPS and ORPS to simulate FCOPYSIGN.
371 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
372 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
373
374 // We don't support sin/cos/fmod
375 setOperationAction(ISD::FSIN , MVT::f32, Expand);
376 setOperationAction(ISD::FCOS , MVT::f32, Expand);
377 setOperationAction(ISD::FREM , MVT::f32, Expand);
378
379 // Expand FP immediates into loads from the stack, except for the special
380 // cases we handle.
381 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
382 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
383 addLegalFPImmediate(APFloat(+0.0f)); // xorps
384 addLegalFPImmediate(APFloat(+0.0)); // FLD0
385 addLegalFPImmediate(APFloat(+1.0)); // FLD1
386 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
387 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
388
389 // SSE->x87 conversions go through memory.
390 setConvertAction(MVT::f32, MVT::f64, Expand);
391 setConvertAction(MVT::f32, MVT::f80, Expand);
392
393 // x87->SSE truncations need to go through memory.
394 setConvertAction(MVT::f80, MVT::f32, Expand);
395 setConvertAction(MVT::f64, MVT::f32, Expand);
396 // And x87->x87 truncations also.
397 setConvertAction(MVT::f80, MVT::f64, Expand);
398
399 if (!UnsafeFPMath) {
400 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
401 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
402 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000404 // f32 and f64 in x87.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405 // Set up the FP register classes.
406 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
407 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
408
409 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
410 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
411 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
412 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
Dale Johannesen8f83a6b2007-08-09 01:04:01 +0000413
414 // Floating truncations need to go through memory.
415 setConvertAction(MVT::f80, MVT::f32, Expand);
416 setConvertAction(MVT::f64, MVT::f32, Expand);
417 setConvertAction(MVT::f80, MVT::f64, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418
419 if (!UnsafeFPMath) {
420 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
421 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
422 }
423
424 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
425 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
Dale Johannesenbbe2b702007-08-30 00:23:21 +0000426 addLegalFPImmediate(APFloat(+0.0)); // FLD0
427 addLegalFPImmediate(APFloat(+1.0)); // FLD1
428 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
429 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000430 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
431 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
432 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
433 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434 }
435
Dale Johannesen4ab00bd2007-08-05 18:49:15 +0000436 // Long double always uses X87.
437 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000438 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
439 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
440 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
Dale Johannesen7f1076b2007-09-26 21:10:55 +0000441 if (!UnsafeFPMath) {
442 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
443 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
444 }
Dale Johannesen4ab00bd2007-08-05 18:49:15 +0000445
Dan Gohman2f7b1982007-10-11 23:21:31 +0000446 // Always use a library call for pow.
447 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
448 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
449 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
450
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000451 // First set operation action for all vector types to expand. Then we
452 // will selectively turn on ones that can be effectively codegen'd.
453 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
454 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
455 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
456 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
457 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
458 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
459 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
460 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
461 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
462 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
463 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
464 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
465 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
466 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
467 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
468 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
469 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
470 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
471 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
472 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
473 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
474 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
475 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
476 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
477 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
Dan Gohman5a199552007-10-08 18:33:35 +0000478 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
479 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
480 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
481 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
Dan Gohman2f7b1982007-10-11 23:21:31 +0000482 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
Dan Gohman1d2dc2c2007-10-12 14:09:42 +0000483 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
484 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
485 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 }
487
488 if (Subtarget->hasMMX()) {
489 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
490 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
491 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
492 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
493
494 // FIXME: add MMX packed arithmetics
495
496 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
497 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
498 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
499 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
500
501 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
502 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
503 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
Dale Johannesen6b65c332007-10-30 01:18:38 +0000504 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000505
506 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
507 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
508
509 setOperationAction(ISD::AND, MVT::v8i8, Promote);
510 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
511 setOperationAction(ISD::AND, MVT::v4i16, Promote);
512 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
513 setOperationAction(ISD::AND, MVT::v2i32, Promote);
514 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
515 setOperationAction(ISD::AND, MVT::v1i64, Legal);
516
517 setOperationAction(ISD::OR, MVT::v8i8, Promote);
518 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
519 setOperationAction(ISD::OR, MVT::v4i16, Promote);
520 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
521 setOperationAction(ISD::OR, MVT::v2i32, Promote);
522 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
523 setOperationAction(ISD::OR, MVT::v1i64, Legal);
524
525 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
526 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
527 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
528 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
529 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
530 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
531 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
532
533 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
534 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
535 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
536 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
537 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
538 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
539 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
540
541 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
542 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
543 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
544 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
545
546 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
547 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
548 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
549 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
550
551 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
552 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
553 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
554 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
555 }
556
557 if (Subtarget->hasSSE1()) {
558 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
559
560 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
561 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
562 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
563 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
564 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
565 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
567 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
568 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
569 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
570 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
571 }
572
573 if (Subtarget->hasSSE2()) {
574 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
575 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
576 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
577 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
578 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
579
580 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
581 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
582 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
583 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
584 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
585 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
586 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
587 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
588 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
589 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
590 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
591 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
592 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
593 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
594 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000595
596 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
597 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
598 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
599 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
600 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
601 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
602
603 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
604 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
Nate Begemanc16406d2007-12-11 01:41:33 +0000605 // Do not attempt to custom lower non-power-of-2 vectors
606 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
607 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000608 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
609 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
610 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
611 }
612 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
613 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
614 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
615 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
616 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
Dale Johannesen2ff963d2007-10-31 00:32:36 +0000617 if (Subtarget->is64Bit())
618 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619
620 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
621 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
622 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
623 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
624 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
625 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
626 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
627 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
628 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
629 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
630 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
631 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
632 }
633
634 // Custom lower v2i64 and v2f64 selects.
635 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
636 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
637 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
638 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
639 }
640
641 // We want to custom lower some of our intrinsics.
642 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
643
644 // We have target-specific dag combine patterns for the following nodes:
645 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
646 setTargetDAGCombine(ISD::SELECT);
647
648 computeRegisterProperties();
649
650 // FIXME: These should be based on subtarget info. Plus, the values should
651 // be smaller when we are in optimizing for size mode.
652 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
653 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
654 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
655 allowUnalignedMemoryAccesses = true; // x86 supports it!
656}
657
658
Evan Cheng6fb06762007-11-09 01:32:10 +0000659/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
660/// jumptable.
661SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
662 SelectionDAG &DAG) const {
663 if (usesGlobalOffsetTable())
664 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
665 if (!Subtarget->isPICStyleRIPRel())
666 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
667 return Table;
668}
669
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670//===----------------------------------------------------------------------===//
671// Return Value Calling Convention Implementation
672//===----------------------------------------------------------------------===//
673
674#include "X86GenCallingConv.inc"
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000675
676/// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
677/// exists skip possible ISD:TokenFactor.
678static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
679 if (Chain.getOpcode()==X86ISD::TAILCALL) {
680 return Chain;
681 } else if (Chain.getOpcode()==ISD::TokenFactor) {
682 if (Chain.getNumOperands() &&
683 Chain.getOperand(0).getOpcode()==X86ISD::TAILCALL)
684 return Chain.getOperand(0);
685 }
686 return Chain;
687}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688
689/// LowerRET - Lower an ISD::RET node.
690SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
691 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
692
693 SmallVector<CCValAssign, 16> RVLocs;
694 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
695 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
696 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
697 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000698
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699 // If this is the first return lowered for this function, add the regs to the
700 // liveout set for the function.
701 if (DAG.getMachineFunction().liveout_empty()) {
702 for (unsigned i = 0; i != RVLocs.size(); ++i)
703 if (RVLocs[i].isRegLoc())
704 DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
705 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 SDOperand Chain = Op.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000708 // Handle tail call return.
709 Chain = GetPossiblePreceedingTailCall(Chain);
710 if (Chain.getOpcode() == X86ISD::TAILCALL) {
711 SDOperand TailCall = Chain;
712 SDOperand TargetAddress = TailCall.getOperand(1);
713 SDOperand StackAdjustment = TailCall.getOperand(2);
714 assert ( ((TargetAddress.getOpcode() == ISD::Register &&
715 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
716 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
717 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
718 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
719 "Expecting an global address, external symbol, or register");
720 assert( StackAdjustment.getOpcode() == ISD::Constant &&
721 "Expecting a const value");
722
723 SmallVector<SDOperand,8> Operands;
724 Operands.push_back(Chain.getOperand(0));
725 Operands.push_back(TargetAddress);
726 Operands.push_back(StackAdjustment);
727 // Copy registers used by the call. Last operand is a flag so it is not
728 // copied.
Arnold Schwaighofer10202b32007-10-16 09:05:00 +0000729 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000730 Operands.push_back(Chain.getOperand(i));
731 }
Arnold Schwaighofer10202b32007-10-16 09:05:00 +0000732 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
733 Operands.size());
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000734 }
735
736 // Regular return.
737 SDOperand Flag;
738
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 // Copy the result values into the output registers.
740 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
741 RVLocs[0].getLocReg() != X86::ST0) {
742 for (unsigned i = 0; i != RVLocs.size(); ++i) {
743 CCValAssign &VA = RVLocs[i];
744 assert(VA.isRegLoc() && "Can only return in registers!");
745 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
746 Flag);
747 Flag = Chain.getValue(1);
748 }
749 } else {
750 // We need to handle a destination of ST0 specially, because it isn't really
751 // a register.
752 SDOperand Value = Op.getOperand(1);
753
754 // If this is an FP return with ScalarSSE, we need to move the value from
755 // an XMM register onto the fp-stack.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000756 if ((X86ScalarSSEf32 && RVLocs[0].getValVT()==MVT::f32) ||
757 (X86ScalarSSEf64 && RVLocs[0].getValVT()==MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 SDOperand MemLoc;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000759
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000760 // If this is a load into a scalarsse value, don't store the loaded value
761 // back to the stack, only to reload it: just replace the scalar-sse load.
762 if (ISD::isNON_EXTLoad(Value.Val) &&
763 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
764 Chain = Value.getOperand(0);
765 MemLoc = Value.getOperand(1);
766 } else {
767 // Spill the value to memory and reload it into top of stack.
768 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
769 MachineFunction &MF = DAG.getMachineFunction();
770 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
771 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
772 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
773 }
774 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
775 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
776 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
777 Chain = Value.getValue(1);
778 }
779
780 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
781 SDOperand Ops[] = { Chain, Value };
782 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
783 Flag = Chain.getValue(1);
784 }
785
786 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
787 if (Flag.Val)
788 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
789 else
790 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
791}
792
793
794/// LowerCallResult - Lower the result values of an ISD::CALL into the
795/// appropriate copies out of appropriate physical registers. This assumes that
796/// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
797/// being lowered. The returns a SDNode with the same number of values as the
798/// ISD::CALL.
799SDNode *X86TargetLowering::
800LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
801 unsigned CallingConv, SelectionDAG &DAG) {
802
803 // Assign locations to each value returned by this call.
804 SmallVector<CCValAssign, 16> RVLocs;
805 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
806 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
807 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
808
809
810 SmallVector<SDOperand, 8> ResultVals;
811
812 // Copy all of the result registers out of their specified physreg.
813 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
814 for (unsigned i = 0; i != RVLocs.size(); ++i) {
815 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
816 RVLocs[i].getValVT(), InFlag).getValue(1);
817 InFlag = Chain.getValue(2);
818 ResultVals.push_back(Chain.getValue(0));
819 }
820 } else {
821 // Copies from the FP stack are special, as ST0 isn't a valid register
822 // before the fp stackifier runs.
823
824 // Copy ST0 into an RFP register with FP_GET_RESULT.
825 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
826 SDOperand GROps[] = { Chain, InFlag };
827 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
828 Chain = RetVal.getValue(1);
829 InFlag = RetVal.getValue(2);
830
831 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
832 // an XMM register.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000833 if ((X86ScalarSSEf32 && RVLocs[0].getValVT() == MVT::f32) ||
834 (X86ScalarSSEf64 && RVLocs[0].getValVT() == MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
836 // shouldn't be necessary except that RFP cannot be live across
837 // multiple blocks. When stackifier is fixed, they can be uncoupled.
838 MachineFunction &MF = DAG.getMachineFunction();
839 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
840 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
841 SDOperand Ops[] = {
842 Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
843 };
844 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
845 RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
846 Chain = RetVal.getValue(1);
847 }
848 ResultVals.push_back(RetVal);
849 }
850
851 // Merge everything together with a MERGE_VALUES node.
852 ResultVals.push_back(Chain);
853 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
854 &ResultVals[0], ResultVals.size()).Val;
855}
856
857
858//===----------------------------------------------------------------------===//
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000859// C & StdCall & Fast Calling Convention implementation
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860//===----------------------------------------------------------------------===//
861// StdCall calling convention seems to be standard for many Windows' API
862// routines and around. It differs from C calling convention just a little:
863// callee should clean up the stack, not caller. Symbols should be also
864// decorated in some fancy way :) It doesn't support any vector arguments.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000865// For info on fast calling convention see Fast Calling Convention (tail call)
866// implementation LowerX86_32FastCCCallTo.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867
868/// AddLiveIn - This helper function adds the specified physical register to the
869/// MachineFunction as a live in value. It also creates a corresponding virtual
870/// register for it.
871static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
872 const TargetRegisterClass *RC) {
873 assert(RC->contains(PReg) && "Not the correct regclass!");
874 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
875 MF.addLiveIn(PReg, VReg);
876 return VReg;
877}
878
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000879// align stack arguments according to platform alignment needed for tail calls
880unsigned GetAlignedArgumentStackSize(unsigned StackSize, SelectionDAG& DAG);
881
Rafael Espindola03cbeb72007-09-14 15:48:13 +0000882SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
883 const CCValAssign &VA,
884 MachineFrameInfo *MFI,
885 SDOperand Root, unsigned i) {
886 // Create the nodes corresponding to a load from this parameter slot.
887 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
888 VA.getLocMemOffset());
889 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
890
891 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
892
893 if (Flags & ISD::ParamFlags::ByVal)
894 return FIN;
895 else
896 return DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0);
897}
898
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
900 bool isStdCall) {
901 unsigned NumArgs = Op.Val->getNumValues() - 1;
902 MachineFunction &MF = DAG.getMachineFunction();
903 MachineFrameInfo *MFI = MF.getFrameInfo();
904 SDOperand Root = Op.getOperand(0);
905 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000906 unsigned CC = MF.getFunction()->getCallingConv();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907 // Assign locations to all of the incoming arguments.
908 SmallVector<CCValAssign, 16> ArgLocs;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000909 CCState CCInfo(CC, isVarArg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000910 getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000911 // Check for possible tail call calling convention.
912 if (CC == CallingConv::Fast && PerformTailCallOpt)
913 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_TailCall);
914 else
915 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
916
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917 SmallVector<SDOperand, 8> ArgValues;
918 unsigned LastVal = ~0U;
919 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
920 CCValAssign &VA = ArgLocs[i];
921 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
922 // places.
923 assert(VA.getValNo() != LastVal &&
924 "Don't support value assigned to multiple locs yet");
925 LastVal = VA.getValNo();
926
927 if (VA.isRegLoc()) {
928 MVT::ValueType RegVT = VA.getLocVT();
929 TargetRegisterClass *RC;
930 if (RegVT == MVT::i32)
931 RC = X86::GR32RegisterClass;
932 else {
933 assert(MVT::isVector(RegVT));
934 RC = X86::VR128RegisterClass;
935 }
936
937 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
938 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
939
940 // If this is an 8 or 16-bit value, it is really passed promoted to 32
941 // bits. Insert an assert[sz]ext to capture this, then truncate to the
942 // right size.
943 if (VA.getLocInfo() == CCValAssign::SExt)
944 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
945 DAG.getValueType(VA.getValVT()));
946 else if (VA.getLocInfo() == CCValAssign::ZExt)
947 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
948 DAG.getValueType(VA.getValVT()));
949
950 if (VA.getLocInfo() != CCValAssign::Full)
951 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
952
953 ArgValues.push_back(ArgValue);
954 } else {
955 assert(VA.isMemLoc());
Rafael Espindola03cbeb72007-09-14 15:48:13 +0000956 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000957 }
958 }
959
960 unsigned StackSize = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000961 // align stack specially for tail calls
962 if (CC==CallingConv::Fast)
963 StackSize = GetAlignedArgumentStackSize(StackSize,DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000964
965 ArgValues.push_back(Root);
966
967 // If the function takes variable number of arguments, make a frame index for
968 // the start of the first vararg value... for expansion of llvm.va_start.
969 if (isVarArg)
970 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
971
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000972 // Tail call calling convention (CallingConv::Fast) does not support varargs.
973 assert( !(isVarArg && CC == CallingConv::Fast) &&
974 "CallingConv::Fast does not support varargs.");
975
976 if (isStdCall && !isVarArg &&
977 (CC==CallingConv::Fast && PerformTailCallOpt || CC!=CallingConv::Fast)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978 BytesToPopOnReturn = StackSize; // Callee pops everything..
979 BytesCallerReserves = 0;
980 } else {
981 BytesToPopOnReturn = 0; // Callee pops nothing.
982
983 // If this is an sret function, the return should pop the hidden pointer.
984 if (NumArgs &&
985 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
986 ISD::ParamFlags::StructReturn))
987 BytesToPopOnReturn = 4;
988
989 BytesCallerReserves = StackSize;
990 }
Anton Korobeynikove844e472007-08-15 17:12:32 +0000991
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993
Anton Korobeynikove844e472007-08-15 17:12:32 +0000994 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
995 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996
997 // Return the new list of results.
998 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
999 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1000}
1001
1002SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
1003 unsigned CC) {
1004 SDOperand Chain = Op.getOperand(0);
1005 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 SDOperand Callee = Op.getOperand(4);
1007 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001008
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 // Analyze operands of the call, assigning locations to each operand.
1010 SmallVector<CCValAssign, 16> ArgLocs;
1011 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001012 if(CC==CallingConv::Fast && PerformTailCallOpt)
1013 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1014 else
1015 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001016
1017 // Get a count of how many bytes are to be pushed on the stack.
1018 unsigned NumBytes = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001019 if (CC==CallingConv::Fast)
1020 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021
1022 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1023
1024 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1025 SmallVector<SDOperand, 8> MemOpChains;
1026
1027 SDOperand StackPtr;
1028
1029 // Walk the register/memloc assignments, inserting copies/loads.
1030 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1031 CCValAssign &VA = ArgLocs[i];
1032 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1033
1034 // Promote the value if needed.
1035 switch (VA.getLocInfo()) {
1036 default: assert(0 && "Unknown loc info!");
1037 case CCValAssign::Full: break;
1038 case CCValAssign::SExt:
1039 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1040 break;
1041 case CCValAssign::ZExt:
1042 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1043 break;
1044 case CCValAssign::AExt:
1045 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1046 break;
1047 }
1048
1049 if (VA.isRegLoc()) {
1050 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1051 } else {
1052 assert(VA.isMemLoc());
1053 if (StackPtr.Val == 0)
1054 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindola007b7142007-09-21 15:50:22 +00001055
1056 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1057 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 }
1059 }
1060
1061 // If the first argument is an sret pointer, remember it.
1062 bool isSRet = NumOps &&
1063 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
1064 ISD::ParamFlags::StructReturn);
1065
1066 if (!MemOpChains.empty())
1067 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1068 &MemOpChains[0], MemOpChains.size());
1069
1070 // Build a sequence of copy-to-reg nodes chained together with token chain
1071 // and flag operands which copy the outgoing args into registers.
1072 SDOperand InFlag;
1073 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1074 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1075 InFlag);
1076 InFlag = Chain.getValue(1);
1077 }
1078
1079 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1080 // GOT pointer.
1081 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1082 Subtarget->isPICStyleGOT()) {
1083 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1084 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1085 InFlag);
1086 InFlag = Chain.getValue(1);
1087 }
1088
1089 // If the callee is a GlobalAddress node (quite common, every direct call is)
1090 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1091 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1092 // We should use extra load for direct calls to dllimported functions in
1093 // non-JIT mode.
1094 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1095 getTargetMachine(), true))
1096 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1097 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1098 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1099
1100 // Returns a chain & a flag for retval copy to use.
1101 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1102 SmallVector<SDOperand, 8> Ops;
1103 Ops.push_back(Chain);
1104 Ops.push_back(Callee);
1105
1106 // Add argument registers to the end of the list so that they are known live
1107 // into the call.
1108 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1109 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1110 RegsToPass[i].second.getValueType()));
1111
1112 // Add an implicit use GOT pointer in EBX.
1113 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1114 Subtarget->isPICStyleGOT())
1115 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1116
1117 if (InFlag.Val)
1118 Ops.push_back(InFlag);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001119
1120 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121 InFlag = Chain.getValue(1);
1122
1123 // Create the CALLSEQ_END node.
1124 unsigned NumBytesForCalleeToPush = 0;
1125
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001126 if (CC == CallingConv::X86_StdCall ||
1127 (CC == CallingConv::Fast && PerformTailCallOpt)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128 if (isVarArg)
1129 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1130 else
1131 NumBytesForCalleeToPush = NumBytes;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001132 assert(!(isVarArg && CC==CallingConv::Fast) &&
1133 "CallingConv::Fast does not support varargs.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134 } else {
1135 // If this is is a call to a struct-return function, the callee
1136 // pops the hidden struct pointer, so we have to push it back.
1137 // This is common for Darwin/X86, Linux & Mingw32 targets.
1138 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1139 }
Bill Wendling22f8deb2007-11-13 00:44:25 +00001140
1141 Chain = DAG.getCALLSEQ_END(Chain,
1142 DAG.getConstant(NumBytes, getPointerTy()),
1143 DAG.getConstant(NumBytesForCalleeToPush,
1144 getPointerTy()),
1145 InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 InFlag = Chain.getValue(1);
1147
1148 // Handle result values, copying them out of physregs into vregs that we
1149 // return.
1150 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1151}
1152
1153
1154//===----------------------------------------------------------------------===//
1155// FastCall Calling Convention implementation
1156//===----------------------------------------------------------------------===//
1157//
1158// The X86 'fastcall' calling convention passes up to two integer arguments in
1159// registers (an appropriate portion of ECX/EDX), passes arguments in C order,
1160// and requires that the callee pop its arguments off the stack (allowing proper
1161// tail calls), and has the same return value conventions as C calling convs.
1162//
1163// This calling convention always arranges for the callee pop value to be 8n+4
1164// bytes, which is needed for tail recursion elimination and stack alignment
1165// reasons.
1166SDOperand
1167X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
1168 MachineFunction &MF = DAG.getMachineFunction();
1169 MachineFrameInfo *MFI = MF.getFrameInfo();
1170 SDOperand Root = Op.getOperand(0);
1171 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1172
1173 // Assign locations to all of the incoming arguments.
1174 SmallVector<CCValAssign, 16> ArgLocs;
1175 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
1176 getTargetMachine(), ArgLocs);
1177 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
1178
1179 SmallVector<SDOperand, 8> ArgValues;
1180 unsigned LastVal = ~0U;
1181 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1182 CCValAssign &VA = ArgLocs[i];
1183 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1184 // places.
1185 assert(VA.getValNo() != LastVal &&
1186 "Don't support value assigned to multiple locs yet");
1187 LastVal = VA.getValNo();
1188
1189 if (VA.isRegLoc()) {
1190 MVT::ValueType RegVT = VA.getLocVT();
1191 TargetRegisterClass *RC;
1192 if (RegVT == MVT::i32)
1193 RC = X86::GR32RegisterClass;
1194 else {
1195 assert(MVT::isVector(RegVT));
1196 RC = X86::VR128RegisterClass;
1197 }
1198
1199 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1200 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1201
1202 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1203 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1204 // right size.
1205 if (VA.getLocInfo() == CCValAssign::SExt)
1206 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1207 DAG.getValueType(VA.getValVT()));
1208 else if (VA.getLocInfo() == CCValAssign::ZExt)
1209 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1210 DAG.getValueType(VA.getValVT()));
1211
1212 if (VA.getLocInfo() != CCValAssign::Full)
1213 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1214
1215 ArgValues.push_back(ArgValue);
1216 } else {
1217 assert(VA.isMemLoc());
Rafael Espindolab53ef122007-09-21 14:55:38 +00001218 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219 }
1220 }
1221
1222 ArgValues.push_back(Root);
1223
1224 unsigned StackSize = CCInfo.getNextStackOffset();
1225
1226 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1227 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001228 // arguments and the arguments after the retaddr has been pushed are
1229 // aligned.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001230 if ((StackSize & 7) == 0)
1231 StackSize += 4;
1232 }
1233
1234 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1235 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001236 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
1237 BytesCallerReserves = 0;
1238
Anton Korobeynikove844e472007-08-15 17:12:32 +00001239 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1240 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001241
1242 // Return the new list of results.
1243 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1244 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1245}
1246
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001247SDOperand
1248X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1249 const SDOperand &StackPtr,
1250 const CCValAssign &VA,
1251 SDOperand Chain,
1252 SDOperand Arg) {
1253 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1254 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1255 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1256 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1257 if (Flags & ISD::ParamFlags::ByVal) {
1258 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1259 ISD::ParamFlags::ByValAlignOffs);
1260
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001261 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1262 ISD::ParamFlags::ByValSizeOffs;
1263
1264 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1265 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00001266 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001267
Rafael Espindola80825902007-10-19 10:41:11 +00001268 return DAG.getMemcpy(Chain, PtrOff, Arg, SizeNode, AlignNode,
1269 AlwaysInline);
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001270 } else {
1271 return DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1272 }
1273}
1274
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1276 unsigned CC) {
1277 SDOperand Chain = Op.getOperand(0);
1278 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1279 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1280 SDOperand Callee = Op.getOperand(4);
1281
1282 // Analyze operands of the call, assigning locations to each operand.
1283 SmallVector<CCValAssign, 16> ArgLocs;
1284 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1285 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1286
1287 // Get a count of how many bytes are to be pushed on the stack.
1288 unsigned NumBytes = CCInfo.getNextStackOffset();
1289
1290 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1291 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001292 // arguments and the arguments after the retaddr has been pushed are
1293 // aligned.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 if ((NumBytes & 7) == 0)
1295 NumBytes += 4;
1296 }
1297
1298 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1299
1300 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1301 SmallVector<SDOperand, 8> MemOpChains;
1302
1303 SDOperand StackPtr;
1304
1305 // Walk the register/memloc assignments, inserting copies/loads.
1306 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1307 CCValAssign &VA = ArgLocs[i];
1308 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1309
1310 // Promote the value if needed.
1311 switch (VA.getLocInfo()) {
1312 default: assert(0 && "Unknown loc info!");
1313 case CCValAssign::Full: break;
1314 case CCValAssign::SExt:
1315 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1316 break;
1317 case CCValAssign::ZExt:
1318 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1319 break;
1320 case CCValAssign::AExt:
1321 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1322 break;
1323 }
1324
1325 if (VA.isRegLoc()) {
1326 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1327 } else {
1328 assert(VA.isMemLoc());
1329 if (StackPtr.Val == 0)
1330 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindola007b7142007-09-21 15:50:22 +00001331
1332 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1333 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 }
1335 }
1336
1337 if (!MemOpChains.empty())
1338 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1339 &MemOpChains[0], MemOpChains.size());
1340
1341 // Build a sequence of copy-to-reg nodes chained together with token chain
1342 // and flag operands which copy the outgoing args into registers.
1343 SDOperand InFlag;
1344 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1345 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1346 InFlag);
1347 InFlag = Chain.getValue(1);
1348 }
1349
1350 // If the callee is a GlobalAddress node (quite common, every direct call is)
1351 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1352 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1353 // We should use extra load for direct calls to dllimported functions in
1354 // non-JIT mode.
1355 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1356 getTargetMachine(), true))
1357 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1358 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1359 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1360
1361 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1362 // GOT pointer.
1363 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1364 Subtarget->isPICStyleGOT()) {
1365 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1366 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1367 InFlag);
1368 InFlag = Chain.getValue(1);
1369 }
1370
1371 // Returns a chain & a flag for retval copy to use.
1372 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1373 SmallVector<SDOperand, 8> Ops;
1374 Ops.push_back(Chain);
1375 Ops.push_back(Callee);
1376
1377 // Add argument registers to the end of the list so that they are known live
1378 // into the call.
1379 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1380 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1381 RegsToPass[i].second.getValueType()));
1382
1383 // Add an implicit use GOT pointer in EBX.
1384 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1385 Subtarget->isPICStyleGOT())
1386 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1387
1388 if (InFlag.Val)
1389 Ops.push_back(InFlag);
1390
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001391 assert(isTailCall==false && "no tail call here");
1392 Chain = DAG.getNode(X86ISD::CALL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393 NodeTys, &Ops[0], Ops.size());
1394 InFlag = Chain.getValue(1);
1395
1396 // Returns a flag for retval copy to use.
1397 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1398 Ops.clear();
1399 Ops.push_back(Chain);
1400 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1401 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1402 Ops.push_back(InFlag);
1403 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1404 InFlag = Chain.getValue(1);
1405
1406 // Handle result values, copying them out of physregs into vregs that we
1407 // return.
1408 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1409}
1410
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001411//===----------------------------------------------------------------------===//
1412// Fast Calling Convention (tail call) implementation
1413//===----------------------------------------------------------------------===//
1414
1415// Like std call, callee cleans arguments, convention except that ECX is
1416// reserved for storing the tail called function address. Only 2 registers are
1417// free for argument passing (inreg). Tail call optimization is performed
1418// provided:
1419// * tailcallopt is enabled
1420// * caller/callee are fastcc
1421// * elf/pic is disabled OR
1422// * elf/pic enabled + callee is in module + callee has
1423// visibility protected or hidden
Arnold Schwaighofer373e8652007-10-12 21:30:57 +00001424// To keep the stack aligned according to platform abi the function
1425// GetAlignedArgumentStackSize ensures that argument delta is always multiples
1426// of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001427// If a tail called function callee has more arguments than the caller the
1428// caller needs to make sure that there is room to move the RETADDR to. This is
Arnold Schwaighofer373e8652007-10-12 21:30:57 +00001429// achieved by reserving an area the size of the argument delta right after the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001430// original REtADDR, but before the saved framepointer or the spilled registers
1431// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1432// stack layout:
1433// arg1
1434// arg2
1435// RETADDR
1436// [ new RETADDR
1437// move area ]
1438// (possible EBP)
1439// ESI
1440// EDI
1441// local1 ..
1442
1443/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1444/// for a 16 byte align requirement.
1445unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1446 SelectionDAG& DAG) {
1447 if (PerformTailCallOpt) {
1448 MachineFunction &MF = DAG.getMachineFunction();
1449 const TargetMachine &TM = MF.getTarget();
1450 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1451 unsigned StackAlignment = TFI.getStackAlignment();
1452 uint64_t AlignMask = StackAlignment - 1;
1453 int64_t Offset = StackSize;
1454 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1455 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1456 // Number smaller than 12 so just add the difference.
1457 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1458 } else {
1459 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1460 Offset = ((~AlignMask) & Offset) + StackAlignment +
1461 (StackAlignment-SlotSize);
1462 }
1463 StackSize = Offset;
1464 }
1465 return StackSize;
1466}
1467
1468/// IsEligibleForTailCallElimination - Check to see whether the next instruction
Evan Chenge7a87392007-11-02 01:26:22 +00001469/// following the call is a return. A function is eligible if caller/callee
1470/// calling conventions match, currently only fastcc supports tail calls, and
1471/// the function CALL is immediatly followed by a RET.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001472bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1473 SDOperand Ret,
1474 SelectionDAG& DAG) const {
Evan Chenge7a87392007-11-02 01:26:22 +00001475 if (!PerformTailCallOpt)
1476 return false;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001477
1478 // Check whether CALL node immediatly preceeds the RET node and whether the
1479 // return uses the result of the node or is a void return.
Evan Chenge7a87392007-11-02 01:26:22 +00001480 unsigned NumOps = Ret.getNumOperands();
1481 if ((NumOps == 1 &&
1482 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1483 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
Evan Cheng26c0e982007-11-02 17:45:40 +00001484 (NumOps > 1 &&
Evan Chenge7a87392007-11-02 01:26:22 +00001485 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1486 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001487 MachineFunction &MF = DAG.getMachineFunction();
1488 unsigned CallerCC = MF.getFunction()->getCallingConv();
1489 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1490 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1491 SDOperand Callee = Call.getOperand(4);
1492 // On elf/pic %ebx needs to be livein.
Evan Chenge7a87392007-11-02 01:26:22 +00001493 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1494 !Subtarget->isPICStyleGOT())
1495 return true;
1496
1497 // Can only do local tail calls with PIC.
1498 GlobalValue * GV = 0;
1499 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1500 if(G != 0 &&
1501 (GV = G->getGlobal()) &&
1502 (GV->hasHiddenVisibility() || GV->hasProtectedVisibility()))
1503 return true;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001504 }
1505 }
Evan Chenge7a87392007-11-02 01:26:22 +00001506
1507 return false;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001508}
1509
1510SDOperand X86TargetLowering::LowerX86_TailCallTo(SDOperand Op,
1511 SelectionDAG &DAG,
1512 unsigned CC) {
1513 SDOperand Chain = Op.getOperand(0);
1514 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1515 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1516 SDOperand Callee = Op.getOperand(4);
1517 bool is64Bit = Subtarget->is64Bit();
1518
1519 assert(isTailCall && PerformTailCallOpt && "Should only emit tail calls.");
1520
1521 // Analyze operands of the call, assigning locations to each operand.
1522 SmallVector<CCValAssign, 16> ArgLocs;
1523 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1524 if (is64Bit)
1525 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1526 else
1527 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1528
1529
1530 // Lower arguments at fp - stackoffset + fpdiff.
1531 MachineFunction &MF = DAG.getMachineFunction();
1532
1533 unsigned NumBytesToBePushed =
1534 GetAlignedArgumentStackSize(CCInfo.getNextStackOffset(), DAG);
1535
1536 unsigned NumBytesCallerPushed =
1537 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1538 int FPDiff = NumBytesCallerPushed - NumBytesToBePushed;
1539
1540 // Set the delta of movement of the returnaddr stackslot.
1541 // But only set if delta is greater than previous delta.
1542 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1543 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1544
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001545 Chain = DAG.
1546 getCALLSEQ_START(Chain, DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1547
1548 // Adjust the Return address stack slot.
1549 SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001550 if (FPDiff) {
1551 MVT::ValueType VT = is64Bit ? MVT::i64 : MVT::i32;
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001552 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1553 // Load the "old" Return address.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001554 RetAddrFrIdx =
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001555 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1556 // Calculate the new stack slot for the return address.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001557 int SlotSize = is64Bit ? 8 : 4;
1558 int NewReturnAddrFI =
1559 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001560 NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1561 Chain = SDOperand(RetAddrFrIdx.Val, 1);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001562 }
1563
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001564 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1565 SmallVector<SDOperand, 8> MemOpChains;
1566 SmallVector<SDOperand, 8> MemOpChains2;
1567 SDOperand FramePtr, StackPtr;
1568 SDOperand PtrOff;
1569 SDOperand FIN;
1570 int FI = 0;
1571
1572 // Walk the register/memloc assignments, inserting copies/loads. Lower
1573 // arguments first to the stack slot where they would normally - in case of a
1574 // normal function call - be.
1575 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1576 CCValAssign &VA = ArgLocs[i];
1577 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1578
1579 // Promote the value if needed.
1580 switch (VA.getLocInfo()) {
1581 default: assert(0 && "Unknown loc info!");
1582 case CCValAssign::Full: break;
1583 case CCValAssign::SExt:
1584 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1585 break;
1586 case CCValAssign::ZExt:
1587 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1588 break;
1589 case CCValAssign::AExt:
1590 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1591 break;
1592 }
1593
1594 if (VA.isRegLoc()) {
1595 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1596 } else {
1597 assert(VA.isMemLoc());
1598 if (StackPtr.Val == 0)
1599 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1600
1601 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1602 Arg));
1603 }
1604 }
1605
1606 if (!MemOpChains.empty())
1607 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1608 &MemOpChains[0], MemOpChains.size());
1609
1610 // Build a sequence of copy-to-reg nodes chained together with token chain
1611 // and flag operands which copy the outgoing args into registers.
1612 SDOperand InFlag;
1613 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1614 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1615 InFlag);
1616 InFlag = Chain.getValue(1);
1617 }
1618 InFlag = SDOperand();
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001619
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001620 // Copy from stack slots to stack slot of a tail called function. This needs
1621 // to be done because if we would lower the arguments directly to their real
1622 // stack slot we might end up overwriting each other.
1623 // TODO: To make this more efficient (sometimes saving a store/load) we could
1624 // analyse the arguments and emit this store/load/store sequence only for
1625 // arguments which would be overwritten otherwise.
1626 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1627 CCValAssign &VA = ArgLocs[i];
1628 if (!VA.isRegLoc()) {
1629 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1630 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1631
1632 // Get source stack slot.
1633 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1634 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1635 // Create frame index.
1636 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1637 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1638 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1639 FIN = DAG.getFrameIndex(FI, MVT::i32);
1640 if (Flags & ISD::ParamFlags::ByVal) {
1641 // Copy relative to framepointer.
1642 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1643 ISD::ParamFlags::ByValAlignOffs);
1644
1645 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1646 ISD::ParamFlags::ByValSizeOffs;
1647
1648 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1649 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
Arnold Schwaighofer97794942007-11-10 10:48:01 +00001650 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i1);
1651
1652 MemOpChains2.push_back(DAG.getMemcpy(Chain, FIN, PtrOff, SizeNode,
1653 AlignNode,AlwaysInline));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001654 } else {
1655 SDOperand LoadedArg = DAG.getLoad(VA.getValVT(), Chain, PtrOff, NULL,0);
1656 // Store relative to framepointer.
1657 MemOpChains2.push_back(DAG.getStore(Chain, LoadedArg, FIN, NULL, 0));
1658 }
1659 }
1660 }
1661
1662 if (!MemOpChains2.empty())
1663 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1664 &MemOpChains2[0], MemOpChains.size());
1665
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001666 // Store the return address to the appropriate stack slot.
1667 if (FPDiff)
1668 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1669
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001670 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1671 // GOT pointer.
1672 // Does not work with tail call since ebx is not restored correctly by
1673 // tailcaller. TODO: at least for x86 - verify for x86-64
1674
1675 // If the callee is a GlobalAddress node (quite common, every direct call is)
1676 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1677 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1678 // We should use extra load for direct calls to dllimported functions in
1679 // non-JIT mode.
1680 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1681 getTargetMachine(), true))
1682 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1683 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1684 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1685 else {
1686 assert(Callee.getOpcode() == ISD::LOAD &&
1687 "Function destination must be loaded into virtual register");
1688 unsigned Opc = is64Bit ? X86::R9 : X86::ECX;
1689
1690 Chain = DAG.getCopyToReg(Chain,
1691 DAG.getRegister(Opc, getPointerTy()) ,
1692 Callee,InFlag);
1693 Callee = DAG.getRegister(Opc, getPointerTy());
1694 // Add register as live out.
1695 DAG.getMachineFunction().addLiveOut(Opc);
1696 }
1697
1698 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1699 SmallVector<SDOperand, 8> Ops;
1700
1701 Ops.push_back(Chain);
1702 Ops.push_back(DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1703 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1704 if (InFlag.Val)
1705 Ops.push_back(InFlag);
1706 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1707 InFlag = Chain.getValue(1);
1708
1709 // Returns a chain & a flag for retval copy to use.
1710 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1711 Ops.clear();
1712 Ops.push_back(Chain);
1713 Ops.push_back(Callee);
1714 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1715 // Add argument registers to the end of the list so that they are known live
1716 // into the call.
1717 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1718 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1719 RegsToPass[i].second.getValueType()));
1720 if (InFlag.Val)
1721 Ops.push_back(InFlag);
1722 assert(InFlag.Val &&
1723 "Flag must be set. Depend on flag being set in LowerRET");
1724 Chain = DAG.getNode(X86ISD::TAILCALL,
1725 Op.Val->getVTList(), &Ops[0], Ops.size());
1726
1727 return SDOperand(Chain.Val, Op.ResNo);
1728}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001729
1730//===----------------------------------------------------------------------===//
1731// X86-64 C Calling Convention implementation
1732//===----------------------------------------------------------------------===//
1733
1734SDOperand
1735X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1736 MachineFunction &MF = DAG.getMachineFunction();
1737 MachineFrameInfo *MFI = MF.getFrameInfo();
1738 SDOperand Root = Op.getOperand(0);
1739 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001740 unsigned CC= MF.getFunction()->getCallingConv();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001741
1742 static const unsigned GPR64ArgRegs[] = {
1743 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1744 };
1745 static const unsigned XMMArgRegs[] = {
1746 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1747 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1748 };
1749
1750
1751 // Assign locations to all of the incoming arguments.
1752 SmallVector<CCValAssign, 16> ArgLocs;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001753 CCState CCInfo(CC, isVarArg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001754 getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001755 if (CC == CallingConv::Fast && PerformTailCallOpt)
1756 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_TailCall);
1757 else
1758 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001759
1760 SmallVector<SDOperand, 8> ArgValues;
1761 unsigned LastVal = ~0U;
1762 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1763 CCValAssign &VA = ArgLocs[i];
1764 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1765 // places.
1766 assert(VA.getValNo() != LastVal &&
1767 "Don't support value assigned to multiple locs yet");
1768 LastVal = VA.getValNo();
1769
1770 if (VA.isRegLoc()) {
1771 MVT::ValueType RegVT = VA.getLocVT();
1772 TargetRegisterClass *RC;
1773 if (RegVT == MVT::i32)
1774 RC = X86::GR32RegisterClass;
1775 else if (RegVT == MVT::i64)
1776 RC = X86::GR64RegisterClass;
1777 else if (RegVT == MVT::f32)
1778 RC = X86::FR32RegisterClass;
1779 else if (RegVT == MVT::f64)
1780 RC = X86::FR64RegisterClass;
1781 else {
1782 assert(MVT::isVector(RegVT));
1783 if (MVT::getSizeInBits(RegVT) == 64) {
1784 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1785 RegVT = MVT::i64;
1786 } else
1787 RC = X86::VR128RegisterClass;
1788 }
1789
1790 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1791 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1792
1793 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1794 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1795 // right size.
1796 if (VA.getLocInfo() == CCValAssign::SExt)
1797 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1798 DAG.getValueType(VA.getValVT()));
1799 else if (VA.getLocInfo() == CCValAssign::ZExt)
1800 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1801 DAG.getValueType(VA.getValVT()));
1802
1803 if (VA.getLocInfo() != CCValAssign::Full)
1804 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1805
1806 // Handle MMX values passed in GPRs.
1807 if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1808 MVT::getSizeInBits(RegVT) == 64)
1809 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1810
1811 ArgValues.push_back(ArgValue);
1812 } else {
1813 assert(VA.isMemLoc());
Rafael Espindola03cbeb72007-09-14 15:48:13 +00001814 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001815 }
1816 }
1817
1818 unsigned StackSize = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001819 if (CC==CallingConv::Fast)
1820 StackSize =GetAlignedArgumentStackSize(StackSize, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001821
1822 // If the function takes variable number of arguments, make a frame index for
1823 // the start of the first vararg value... for expansion of llvm.va_start.
1824 if (isVarArg) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001825 assert(CC!=CallingConv::Fast
1826 && "Var arg not supported with calling convention fastcc");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001827 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1828 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1829
1830 // For X86-64, if there are vararg parameters that are passed via
1831 // registers, then we must store them to their spots on the stack so they
1832 // may be loaded by deferencing the result of va_next.
1833 VarArgsGPOffset = NumIntRegs * 8;
1834 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1835 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1836 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1837
1838 // Store the integer parameter registers.
1839 SmallVector<SDOperand, 8> MemOps;
1840 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1841 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1842 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1843 for (; NumIntRegs != 6; ++NumIntRegs) {
1844 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1845 X86::GR64RegisterClass);
1846 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1847 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1848 MemOps.push_back(Store);
1849 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1850 DAG.getConstant(8, getPointerTy()));
1851 }
1852
1853 // Now store the XMM (fp + vector) parameter registers.
1854 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1855 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1856 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1857 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1858 X86::VR128RegisterClass);
1859 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1860 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1861 MemOps.push_back(Store);
1862 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1863 DAG.getConstant(16, getPointerTy()));
1864 }
1865 if (!MemOps.empty())
1866 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1867 &MemOps[0], MemOps.size());
1868 }
1869
1870 ArgValues.push_back(Root);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001871 // Tail call convention (fastcc) needs callee pop.
Evan Cheng778fa0f2007-10-14 10:09:39 +00001872 if (CC == CallingConv::Fast && PerformTailCallOpt) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001873 BytesToPopOnReturn = StackSize; // Callee pops everything.
1874 BytesCallerReserves = 0;
1875 } else {
1876 BytesToPopOnReturn = 0; // Callee pops nothing.
1877 BytesCallerReserves = StackSize;
1878 }
Anton Korobeynikove844e472007-08-15 17:12:32 +00001879 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1880 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1881
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001882 // Return the new list of results.
1883 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1884 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1885}
1886
1887SDOperand
1888X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1889 unsigned CC) {
1890 SDOperand Chain = Op.getOperand(0);
1891 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001892 SDOperand Callee = Op.getOperand(4);
1893
1894 // Analyze operands of the call, assigning locations to each operand.
1895 SmallVector<CCValAssign, 16> ArgLocs;
1896 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Evan Cheng778fa0f2007-10-14 10:09:39 +00001897 if (CC==CallingConv::Fast && PerformTailCallOpt)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001898 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1899 else
1900 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001901
1902 // Get a count of how many bytes are to be pushed on the stack.
1903 unsigned NumBytes = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001904 if (CC == CallingConv::Fast)
1905 NumBytes = GetAlignedArgumentStackSize(NumBytes,DAG);
1906
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001907 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1908
1909 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1910 SmallVector<SDOperand, 8> MemOpChains;
1911
1912 SDOperand StackPtr;
1913
1914 // Walk the register/memloc assignments, inserting copies/loads.
1915 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1916 CCValAssign &VA = ArgLocs[i];
1917 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1918
1919 // Promote the value if needed.
1920 switch (VA.getLocInfo()) {
1921 default: assert(0 && "Unknown loc info!");
1922 case CCValAssign::Full: break;
1923 case CCValAssign::SExt:
1924 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1925 break;
1926 case CCValAssign::ZExt:
1927 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1928 break;
1929 case CCValAssign::AExt:
1930 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1931 break;
1932 }
1933
1934 if (VA.isRegLoc()) {
1935 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1936 } else {
1937 assert(VA.isMemLoc());
1938 if (StackPtr.Val == 0)
1939 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindolab8bcfcd2007-08-20 15:18:24 +00001940
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001941 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1942 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001943 }
1944 }
1945
1946 if (!MemOpChains.empty())
1947 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1948 &MemOpChains[0], MemOpChains.size());
1949
1950 // Build a sequence of copy-to-reg nodes chained together with token chain
1951 // and flag operands which copy the outgoing args into registers.
1952 SDOperand InFlag;
1953 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1954 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1955 InFlag);
1956 InFlag = Chain.getValue(1);
1957 }
1958
1959 if (isVarArg) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001960 assert ( CallingConv::Fast != CC &&
1961 "Var args not supported with calling convention fastcc");
1962
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001963 // From AMD64 ABI document:
1964 // For calls that may call functions that use varargs or stdargs
1965 // (prototype-less calls or calls to functions containing ellipsis (...) in
1966 // the declaration) %al is used as hidden argument to specify the number
1967 // of SSE registers used. The contents of %al do not need to match exactly
1968 // the number of registers, but must be an ubound on the number of SSE
1969 // registers used and is in the range 0 - 8 inclusive.
1970
1971 // Count the number of XMM registers allocated.
1972 static const unsigned XMMArgRegs[] = {
1973 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1974 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1975 };
1976 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1977
1978 Chain = DAG.getCopyToReg(Chain, X86::AL,
1979 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1980 InFlag = Chain.getValue(1);
1981 }
1982
1983 // If the callee is a GlobalAddress node (quite common, every direct call is)
1984 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1985 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1986 // We should use extra load for direct calls to dllimported functions in
1987 // non-JIT mode.
1988 if (getTargetMachine().getCodeModel() != CodeModel::Large
1989 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1990 getTargetMachine(), true))
1991 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1992 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1993 if (getTargetMachine().getCodeModel() != CodeModel::Large)
1994 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1995
1996 // Returns a chain & a flag for retval copy to use.
1997 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1998 SmallVector<SDOperand, 8> Ops;
1999 Ops.push_back(Chain);
2000 Ops.push_back(Callee);
2001
2002 // Add argument registers to the end of the list so that they are known live
2003 // into the call.
2004 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2005 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2006 RegsToPass[i].second.getValueType()));
2007
2008 if (InFlag.Val)
2009 Ops.push_back(InFlag);
2010
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002011 Chain = DAG.getNode(X86ISD::CALL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002012 NodeTys, &Ops[0], Ops.size());
2013 InFlag = Chain.getValue(1);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002014 int NumBytesForCalleeToPush = 0;
Evan Cheng778fa0f2007-10-14 10:09:39 +00002015 if (CC==CallingConv::Fast && PerformTailCallOpt) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002016 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002017 } else {
2018 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2019 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002020 // Returns a flag for retval copy to use.
2021 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2022 Ops.clear();
2023 Ops.push_back(Chain);
2024 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002025 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002026 Ops.push_back(InFlag);
2027 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
2028 InFlag = Chain.getValue(1);
2029
2030 // Handle result values, copying them out of physregs into vregs that we
2031 // return.
2032 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
2033}
2034
2035
2036//===----------------------------------------------------------------------===//
2037// Other Lowering Hooks
2038//===----------------------------------------------------------------------===//
2039
2040
2041SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
Anton Korobeynikove844e472007-08-15 17:12:32 +00002042 MachineFunction &MF = DAG.getMachineFunction();
2043 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2044 int ReturnAddrIndex = FuncInfo->getRAIndex();
2045
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002046 if (ReturnAddrIndex == 0) {
2047 // Set up a frame object for the return address.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002048 if (Subtarget->is64Bit())
2049 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
2050 else
2051 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
Anton Korobeynikove844e472007-08-15 17:12:32 +00002052
2053 FuncInfo->setRAIndex(ReturnAddrIndex);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002054 }
2055
2056 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2057}
2058
2059
2060
2061/// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
2062/// specific condition code. It returns a false if it cannot do a direct
2063/// translation. X86CC is the translated CondCode. LHS/RHS are modified as
2064/// needed.
2065static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2066 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
2067 SelectionDAG &DAG) {
2068 X86CC = X86::COND_INVALID;
2069 if (!isFP) {
2070 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2071 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2072 // X > -1 -> X == 0, jump !sign.
2073 RHS = DAG.getConstant(0, RHS.getValueType());
2074 X86CC = X86::COND_NS;
2075 return true;
2076 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2077 // X < 0 -> X == 0, jump on sign.
2078 X86CC = X86::COND_S;
2079 return true;
Dan Gohman37b34262007-09-17 14:49:27 +00002080 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
2081 // X < 1 -> X <= 0
2082 RHS = DAG.getConstant(0, RHS.getValueType());
2083 X86CC = X86::COND_LE;
2084 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085 }
2086 }
2087
2088 switch (SetCCOpcode) {
2089 default: break;
2090 case ISD::SETEQ: X86CC = X86::COND_E; break;
2091 case ISD::SETGT: X86CC = X86::COND_G; break;
2092 case ISD::SETGE: X86CC = X86::COND_GE; break;
2093 case ISD::SETLT: X86CC = X86::COND_L; break;
2094 case ISD::SETLE: X86CC = X86::COND_LE; break;
2095 case ISD::SETNE: X86CC = X86::COND_NE; break;
2096 case ISD::SETULT: X86CC = X86::COND_B; break;
2097 case ISD::SETUGT: X86CC = X86::COND_A; break;
2098 case ISD::SETULE: X86CC = X86::COND_BE; break;
2099 case ISD::SETUGE: X86CC = X86::COND_AE; break;
2100 }
2101 } else {
2102 // On a floating point condition, the flags are set as follows:
2103 // ZF PF CF op
2104 // 0 | 0 | 0 | X > Y
2105 // 0 | 0 | 1 | X < Y
2106 // 1 | 0 | 0 | X == Y
2107 // 1 | 1 | 1 | unordered
2108 bool Flip = false;
2109 switch (SetCCOpcode) {
2110 default: break;
2111 case ISD::SETUEQ:
2112 case ISD::SETEQ: X86CC = X86::COND_E; break;
2113 case ISD::SETOLT: Flip = true; // Fallthrough
2114 case ISD::SETOGT:
2115 case ISD::SETGT: X86CC = X86::COND_A; break;
2116 case ISD::SETOLE: Flip = true; // Fallthrough
2117 case ISD::SETOGE:
2118 case ISD::SETGE: X86CC = X86::COND_AE; break;
2119 case ISD::SETUGT: Flip = true; // Fallthrough
2120 case ISD::SETULT:
2121 case ISD::SETLT: X86CC = X86::COND_B; break;
2122 case ISD::SETUGE: Flip = true; // Fallthrough
2123 case ISD::SETULE:
2124 case ISD::SETLE: X86CC = X86::COND_BE; break;
2125 case ISD::SETONE:
2126 case ISD::SETNE: X86CC = X86::COND_NE; break;
2127 case ISD::SETUO: X86CC = X86::COND_P; break;
2128 case ISD::SETO: X86CC = X86::COND_NP; break;
2129 }
2130 if (Flip)
2131 std::swap(LHS, RHS);
2132 }
2133
2134 return X86CC != X86::COND_INVALID;
2135}
2136
2137/// hasFPCMov - is there a floating point cmov for the specific X86 condition
2138/// code. Current x86 isa includes the following FP cmov instructions:
2139/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2140static bool hasFPCMov(unsigned X86CC) {
2141 switch (X86CC) {
2142 default:
2143 return false;
2144 case X86::COND_B:
2145 case X86::COND_BE:
2146 case X86::COND_E:
2147 case X86::COND_P:
2148 case X86::COND_A:
2149 case X86::COND_AE:
2150 case X86::COND_NE:
2151 case X86::COND_NP:
2152 return true;
2153 }
2154}
2155
2156/// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2157/// true if Op is undef or if its value falls within the specified range (L, H].
2158static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2159 if (Op.getOpcode() == ISD::UNDEF)
2160 return true;
2161
2162 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2163 return (Val >= Low && Val < Hi);
2164}
2165
2166/// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2167/// true if Op is undef or if its value equal to the specified value.
2168static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2169 if (Op.getOpcode() == ISD::UNDEF)
2170 return true;
2171 return cast<ConstantSDNode>(Op)->getValue() == Val;
2172}
2173
2174/// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2175/// specifies a shuffle of elements that is suitable for input to PSHUFD.
2176bool X86::isPSHUFDMask(SDNode *N) {
2177 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2178
Dan Gohman7dc19012007-08-02 21:17:01 +00002179 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002180 return false;
2181
2182 // Check if the value doesn't reference the second vector.
2183 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2184 SDOperand Arg = N->getOperand(i);
2185 if (Arg.getOpcode() == ISD::UNDEF) continue;
2186 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Dan Gohman7dc19012007-08-02 21:17:01 +00002187 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002188 return false;
2189 }
2190
2191 return true;
2192}
2193
2194/// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2195/// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2196bool X86::isPSHUFHWMask(SDNode *N) {
2197 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2198
2199 if (N->getNumOperands() != 8)
2200 return false;
2201
2202 // Lower quadword copied in order.
2203 for (unsigned i = 0; i != 4; ++i) {
2204 SDOperand Arg = N->getOperand(i);
2205 if (Arg.getOpcode() == ISD::UNDEF) continue;
2206 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2207 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2208 return false;
2209 }
2210
2211 // Upper quadword shuffled.
2212 for (unsigned i = 4; i != 8; ++i) {
2213 SDOperand Arg = N->getOperand(i);
2214 if (Arg.getOpcode() == ISD::UNDEF) continue;
2215 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2216 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2217 if (Val < 4 || Val > 7)
2218 return false;
2219 }
2220
2221 return true;
2222}
2223
2224/// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2225/// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2226bool X86::isPSHUFLWMask(SDNode *N) {
2227 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2228
2229 if (N->getNumOperands() != 8)
2230 return false;
2231
2232 // Upper quadword copied in order.
2233 for (unsigned i = 4; i != 8; ++i)
2234 if (!isUndefOrEqual(N->getOperand(i), i))
2235 return false;
2236
2237 // Lower quadword shuffled.
2238 for (unsigned i = 0; i != 4; ++i)
2239 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2240 return false;
2241
2242 return true;
2243}
2244
2245/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2246/// specifies a shuffle of elements that is suitable for input to SHUFP*.
2247static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2248 if (NumElems != 2 && NumElems != 4) return false;
2249
2250 unsigned Half = NumElems / 2;
2251 for (unsigned i = 0; i < Half; ++i)
2252 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2253 return false;
2254 for (unsigned i = Half; i < NumElems; ++i)
2255 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2256 return false;
2257
2258 return true;
2259}
2260
2261bool X86::isSHUFPMask(SDNode *N) {
2262 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2263 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2264}
2265
2266/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2267/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2268/// half elements to come from vector 1 (which would equal the dest.) and
2269/// the upper half to come from vector 2.
2270static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2271 if (NumOps != 2 && NumOps != 4) return false;
2272
2273 unsigned Half = NumOps / 2;
2274 for (unsigned i = 0; i < Half; ++i)
2275 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2276 return false;
2277 for (unsigned i = Half; i < NumOps; ++i)
2278 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2279 return false;
2280 return true;
2281}
2282
2283static bool isCommutedSHUFP(SDNode *N) {
2284 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2285 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2286}
2287
2288/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2289/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2290bool X86::isMOVHLPSMask(SDNode *N) {
2291 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2292
2293 if (N->getNumOperands() != 4)
2294 return false;
2295
2296 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2297 return isUndefOrEqual(N->getOperand(0), 6) &&
2298 isUndefOrEqual(N->getOperand(1), 7) &&
2299 isUndefOrEqual(N->getOperand(2), 2) &&
2300 isUndefOrEqual(N->getOperand(3), 3);
2301}
2302
2303/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2304/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2305/// <2, 3, 2, 3>
2306bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2307 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2308
2309 if (N->getNumOperands() != 4)
2310 return false;
2311
2312 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2313 return isUndefOrEqual(N->getOperand(0), 2) &&
2314 isUndefOrEqual(N->getOperand(1), 3) &&
2315 isUndefOrEqual(N->getOperand(2), 2) &&
2316 isUndefOrEqual(N->getOperand(3), 3);
2317}
2318
2319/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2320/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2321bool X86::isMOVLPMask(SDNode *N) {
2322 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2323
2324 unsigned NumElems = N->getNumOperands();
2325 if (NumElems != 2 && NumElems != 4)
2326 return false;
2327
2328 for (unsigned i = 0; i < NumElems/2; ++i)
2329 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2330 return false;
2331
2332 for (unsigned i = NumElems/2; i < NumElems; ++i)
2333 if (!isUndefOrEqual(N->getOperand(i), i))
2334 return false;
2335
2336 return true;
2337}
2338
2339/// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2340/// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2341/// and MOVLHPS.
2342bool X86::isMOVHPMask(SDNode *N) {
2343 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2344
2345 unsigned NumElems = N->getNumOperands();
2346 if (NumElems != 2 && NumElems != 4)
2347 return false;
2348
2349 for (unsigned i = 0; i < NumElems/2; ++i)
2350 if (!isUndefOrEqual(N->getOperand(i), i))
2351 return false;
2352
2353 for (unsigned i = 0; i < NumElems/2; ++i) {
2354 SDOperand Arg = N->getOperand(i + NumElems/2);
2355 if (!isUndefOrEqual(Arg, i + NumElems))
2356 return false;
2357 }
2358
2359 return true;
2360}
2361
2362/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2363/// specifies a shuffle of elements that is suitable for input to UNPCKL.
2364bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2365 bool V2IsSplat = false) {
2366 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2367 return false;
2368
2369 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2370 SDOperand BitI = Elts[i];
2371 SDOperand BitI1 = Elts[i+1];
2372 if (!isUndefOrEqual(BitI, j))
2373 return false;
2374 if (V2IsSplat) {
2375 if (isUndefOrEqual(BitI1, NumElts))
2376 return false;
2377 } else {
2378 if (!isUndefOrEqual(BitI1, j + NumElts))
2379 return false;
2380 }
2381 }
2382
2383 return true;
2384}
2385
2386bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2387 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2388 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2389}
2390
2391/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2392/// specifies a shuffle of elements that is suitable for input to UNPCKH.
2393bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2394 bool V2IsSplat = false) {
2395 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2396 return false;
2397
2398 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2399 SDOperand BitI = Elts[i];
2400 SDOperand BitI1 = Elts[i+1];
2401 if (!isUndefOrEqual(BitI, j + NumElts/2))
2402 return false;
2403 if (V2IsSplat) {
2404 if (isUndefOrEqual(BitI1, NumElts))
2405 return false;
2406 } else {
2407 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2408 return false;
2409 }
2410 }
2411
2412 return true;
2413}
2414
2415bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2416 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2417 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2418}
2419
2420/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2421/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2422/// <0, 0, 1, 1>
2423bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2424 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2425
2426 unsigned NumElems = N->getNumOperands();
2427 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2428 return false;
2429
2430 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2431 SDOperand BitI = N->getOperand(i);
2432 SDOperand BitI1 = N->getOperand(i+1);
2433
2434 if (!isUndefOrEqual(BitI, j))
2435 return false;
2436 if (!isUndefOrEqual(BitI1, j))
2437 return false;
2438 }
2439
2440 return true;
2441}
2442
2443/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2444/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2445/// <2, 2, 3, 3>
2446bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2447 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2448
2449 unsigned NumElems = N->getNumOperands();
2450 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2451 return false;
2452
2453 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2454 SDOperand BitI = N->getOperand(i);
2455 SDOperand BitI1 = N->getOperand(i + 1);
2456
2457 if (!isUndefOrEqual(BitI, j))
2458 return false;
2459 if (!isUndefOrEqual(BitI1, j))
2460 return false;
2461 }
2462
2463 return true;
2464}
2465
2466/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2467/// specifies a shuffle of elements that is suitable for input to MOVSS,
2468/// MOVSD, and MOVD, i.e. setting the lowest element.
2469static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
Evan Cheng62cdc642007-12-06 22:14:22 +00002470 if (NumElts != 2 && NumElts != 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002471 return false;
2472
2473 if (!isUndefOrEqual(Elts[0], NumElts))
2474 return false;
2475
2476 for (unsigned i = 1; i < NumElts; ++i) {
2477 if (!isUndefOrEqual(Elts[i], i))
2478 return false;
2479 }
2480
2481 return true;
2482}
2483
2484bool X86::isMOVLMask(SDNode *N) {
2485 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2486 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2487}
2488
2489/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2490/// of what x86 movss want. X86 movs requires the lowest element to be lowest
2491/// element of vector 2 and the other elements to come from vector 1 in order.
2492static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2493 bool V2IsSplat = false,
2494 bool V2IsUndef = false) {
2495 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2496 return false;
2497
2498 if (!isUndefOrEqual(Ops[0], 0))
2499 return false;
2500
2501 for (unsigned i = 1; i < NumOps; ++i) {
2502 SDOperand Arg = Ops[i];
2503 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2504 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2505 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2506 return false;
2507 }
2508
2509 return true;
2510}
2511
2512static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2513 bool V2IsUndef = false) {
2514 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2515 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2516 V2IsSplat, V2IsUndef);
2517}
2518
2519/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2520/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2521bool X86::isMOVSHDUPMask(SDNode *N) {
2522 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2523
2524 if (N->getNumOperands() != 4)
2525 return false;
2526
2527 // Expect 1, 1, 3, 3
2528 for (unsigned i = 0; i < 2; ++i) {
2529 SDOperand Arg = N->getOperand(i);
2530 if (Arg.getOpcode() == ISD::UNDEF) continue;
2531 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2532 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2533 if (Val != 1) return false;
2534 }
2535
2536 bool HasHi = false;
2537 for (unsigned i = 2; i < 4; ++i) {
2538 SDOperand Arg = N->getOperand(i);
2539 if (Arg.getOpcode() == ISD::UNDEF) continue;
2540 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2541 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2542 if (Val != 3) return false;
2543 HasHi = true;
2544 }
2545
2546 // Don't use movshdup if it can be done with a shufps.
2547 return HasHi;
2548}
2549
2550/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2551/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2552bool X86::isMOVSLDUPMask(SDNode *N) {
2553 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2554
2555 if (N->getNumOperands() != 4)
2556 return false;
2557
2558 // Expect 0, 0, 2, 2
2559 for (unsigned i = 0; i < 2; ++i) {
2560 SDOperand Arg = N->getOperand(i);
2561 if (Arg.getOpcode() == ISD::UNDEF) continue;
2562 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2563 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2564 if (Val != 0) return false;
2565 }
2566
2567 bool HasHi = false;
2568 for (unsigned i = 2; i < 4; ++i) {
2569 SDOperand Arg = N->getOperand(i);
2570 if (Arg.getOpcode() == ISD::UNDEF) continue;
2571 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2572 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2573 if (Val != 2) return false;
2574 HasHi = true;
2575 }
2576
2577 // Don't use movshdup if it can be done with a shufps.
2578 return HasHi;
2579}
2580
2581/// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2582/// specifies a identity operation on the LHS or RHS.
2583static bool isIdentityMask(SDNode *N, bool RHS = false) {
2584 unsigned NumElems = N->getNumOperands();
2585 for (unsigned i = 0; i < NumElems; ++i)
2586 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2587 return false;
2588 return true;
2589}
2590
2591/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2592/// a splat of a single element.
2593static bool isSplatMask(SDNode *N) {
2594 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2595
2596 // This is a splat operation if each element of the permute is the same, and
2597 // if the value doesn't reference the second vector.
2598 unsigned NumElems = N->getNumOperands();
2599 SDOperand ElementBase;
2600 unsigned i = 0;
2601 for (; i != NumElems; ++i) {
2602 SDOperand Elt = N->getOperand(i);
2603 if (isa<ConstantSDNode>(Elt)) {
2604 ElementBase = Elt;
2605 break;
2606 }
2607 }
2608
2609 if (!ElementBase.Val)
2610 return false;
2611
2612 for (; i != NumElems; ++i) {
2613 SDOperand Arg = N->getOperand(i);
2614 if (Arg.getOpcode() == ISD::UNDEF) continue;
2615 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2616 if (Arg != ElementBase) return false;
2617 }
2618
2619 // Make sure it is a splat of the first vector operand.
2620 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2621}
2622
2623/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2624/// a splat of a single element and it's a 2 or 4 element mask.
2625bool X86::isSplatMask(SDNode *N) {
2626 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2627
2628 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2629 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2630 return false;
2631 return ::isSplatMask(N);
2632}
2633
2634/// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2635/// specifies a splat of zero element.
2636bool X86::isSplatLoMask(SDNode *N) {
2637 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2638
2639 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2640 if (!isUndefOrEqual(N->getOperand(i), 0))
2641 return false;
2642 return true;
2643}
2644
2645/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2646/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2647/// instructions.
2648unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2649 unsigned NumOperands = N->getNumOperands();
2650 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2651 unsigned Mask = 0;
2652 for (unsigned i = 0; i < NumOperands; ++i) {
2653 unsigned Val = 0;
2654 SDOperand Arg = N->getOperand(NumOperands-i-1);
2655 if (Arg.getOpcode() != ISD::UNDEF)
2656 Val = cast<ConstantSDNode>(Arg)->getValue();
2657 if (Val >= NumOperands) Val -= NumOperands;
2658 Mask |= Val;
2659 if (i != NumOperands - 1)
2660 Mask <<= Shift;
2661 }
2662
2663 return Mask;
2664}
2665
2666/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2667/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2668/// instructions.
2669unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2670 unsigned Mask = 0;
2671 // 8 nodes, but we only care about the last 4.
2672 for (unsigned i = 7; i >= 4; --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 - 4);
2678 if (i != 4)
2679 Mask <<= 2;
2680 }
2681
2682 return Mask;
2683}
2684
2685/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2686/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2687/// instructions.
2688unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2689 unsigned Mask = 0;
2690 // 8 nodes, but we only care about the first 4.
2691 for (int i = 3; i >= 0; --i) {
2692 unsigned Val = 0;
2693 SDOperand Arg = N->getOperand(i);
2694 if (Arg.getOpcode() != ISD::UNDEF)
2695 Val = cast<ConstantSDNode>(Arg)->getValue();
2696 Mask |= Val;
2697 if (i != 0)
2698 Mask <<= 2;
2699 }
2700
2701 return Mask;
2702}
2703
2704/// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2705/// specifies a 8 element shuffle that can be broken into a pair of
2706/// PSHUFHW and PSHUFLW.
2707static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2708 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2709
2710 if (N->getNumOperands() != 8)
2711 return false;
2712
2713 // Lower quadword shuffled.
2714 for (unsigned i = 0; i != 4; ++i) {
2715 SDOperand Arg = N->getOperand(i);
2716 if (Arg.getOpcode() == ISD::UNDEF) continue;
2717 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2718 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
Evan Cheng75184a92007-12-11 01:46:18 +00002719 if (Val >= 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002720 return false;
2721 }
2722
2723 // Upper quadword shuffled.
2724 for (unsigned i = 4; i != 8; ++i) {
2725 SDOperand Arg = N->getOperand(i);
2726 if (Arg.getOpcode() == ISD::UNDEF) continue;
2727 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2728 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2729 if (Val < 4 || Val > 7)
2730 return false;
2731 }
2732
2733 return true;
2734}
2735
Chris Lattnere6aa3862007-11-25 00:24:49 +00002736/// CommuteVectorShuffle - Swap vector_shuffle operands as well as
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002737/// values in ther permute mask.
2738static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2739 SDOperand &V2, SDOperand &Mask,
2740 SelectionDAG &DAG) {
2741 MVT::ValueType VT = Op.getValueType();
2742 MVT::ValueType MaskVT = Mask.getValueType();
2743 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2744 unsigned NumElems = Mask.getNumOperands();
2745 SmallVector<SDOperand, 8> MaskVec;
2746
2747 for (unsigned i = 0; i != NumElems; ++i) {
2748 SDOperand Arg = Mask.getOperand(i);
2749 if (Arg.getOpcode() == ISD::UNDEF) {
2750 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2751 continue;
2752 }
2753 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2754 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2755 if (Val < NumElems)
2756 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2757 else
2758 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2759 }
2760
2761 std::swap(V1, V2);
Evan Chengfca29242007-12-07 08:07:39 +00002762 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002763 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2764}
2765
Evan Chenga6769df2007-12-07 21:30:01 +00002766/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2767/// the two vector operands have swapped position.
Evan Chengfca29242007-12-07 08:07:39 +00002768static
2769SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2770 MVT::ValueType MaskVT = Mask.getValueType();
2771 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2772 unsigned NumElems = Mask.getNumOperands();
2773 SmallVector<SDOperand, 8> MaskVec;
2774 for (unsigned i = 0; i != NumElems; ++i) {
2775 SDOperand Arg = Mask.getOperand(i);
2776 if (Arg.getOpcode() == ISD::UNDEF) {
2777 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2778 continue;
2779 }
2780 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2781 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2782 if (Val < NumElems)
2783 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2784 else
2785 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2786 }
2787 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2788}
2789
2790
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002791/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2792/// match movhlps. The lower half elements should come from upper half of
2793/// V1 (and in order), and the upper half elements should come from the upper
2794/// half of V2 (and in order).
2795static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2796 unsigned NumElems = Mask->getNumOperands();
2797 if (NumElems != 4)
2798 return false;
2799 for (unsigned i = 0, e = 2; i != e; ++i)
2800 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2801 return false;
2802 for (unsigned i = 2; i != 4; ++i)
2803 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2804 return false;
2805 return true;
2806}
2807
2808/// isScalarLoadToVector - Returns true if the node is a scalar load that
2809/// is promoted to a vector.
2810static inline bool isScalarLoadToVector(SDNode *N) {
2811 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2812 N = N->getOperand(0).Val;
2813 return ISD::isNON_EXTLoad(N);
2814 }
2815 return false;
2816}
2817
2818/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2819/// match movlp{s|d}. The lower half elements should come from lower half of
2820/// V1 (and in order), and the upper half elements should come from the upper
2821/// half of V2 (and in order). And since V1 will become the source of the
2822/// MOVLP, it must be either a vector load or a scalar load to vector.
2823static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2824 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2825 return false;
2826 // Is V2 is a vector load, don't do this transformation. We will try to use
2827 // load folding shufps op.
2828 if (ISD::isNON_EXTLoad(V2))
2829 return false;
2830
2831 unsigned NumElems = Mask->getNumOperands();
2832 if (NumElems != 2 && NumElems != 4)
2833 return false;
2834 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2835 if (!isUndefOrEqual(Mask->getOperand(i), i))
2836 return false;
2837 for (unsigned i = NumElems/2; i != NumElems; ++i)
2838 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2839 return false;
2840 return true;
2841}
2842
2843/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2844/// all the same.
2845static bool isSplatVector(SDNode *N) {
2846 if (N->getOpcode() != ISD::BUILD_VECTOR)
2847 return false;
2848
2849 SDOperand SplatValue = N->getOperand(0);
2850 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2851 if (N->getOperand(i) != SplatValue)
2852 return false;
2853 return true;
2854}
2855
2856/// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2857/// to an undef.
2858static bool isUndefShuffle(SDNode *N) {
2859 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2860 return false;
2861
2862 SDOperand V1 = N->getOperand(0);
2863 SDOperand V2 = N->getOperand(1);
2864 SDOperand Mask = N->getOperand(2);
2865 unsigned NumElems = Mask.getNumOperands();
2866 for (unsigned i = 0; i != NumElems; ++i) {
2867 SDOperand Arg = Mask.getOperand(i);
2868 if (Arg.getOpcode() != ISD::UNDEF) {
2869 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2870 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2871 return false;
2872 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2873 return false;
2874 }
2875 }
2876 return true;
2877}
2878
2879/// isZeroNode - Returns true if Elt is a constant zero or a floating point
2880/// constant +0.0.
2881static inline bool isZeroNode(SDOperand Elt) {
2882 return ((isa<ConstantSDNode>(Elt) &&
2883 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2884 (isa<ConstantFPSDNode>(Elt) &&
Dale Johannesendf8a8312007-08-31 04:03:46 +00002885 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886}
2887
2888/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2889/// to an zero vector.
2890static bool isZeroShuffle(SDNode *N) {
2891 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2892 return false;
2893
2894 SDOperand V1 = N->getOperand(0);
2895 SDOperand V2 = N->getOperand(1);
2896 SDOperand Mask = N->getOperand(2);
2897 unsigned NumElems = Mask.getNumOperands();
2898 for (unsigned i = 0; i != NumElems; ++i) {
2899 SDOperand Arg = Mask.getOperand(i);
Chris Lattnere6aa3862007-11-25 00:24:49 +00002900 if (Arg.getOpcode() == ISD::UNDEF)
2901 continue;
2902
2903 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2904 if (Idx < NumElems) {
2905 unsigned Opc = V1.Val->getOpcode();
2906 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2907 continue;
2908 if (Opc != ISD::BUILD_VECTOR ||
2909 !isZeroNode(V1.Val->getOperand(Idx)))
2910 return false;
2911 } else if (Idx >= NumElems) {
2912 unsigned Opc = V2.Val->getOpcode();
2913 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2914 continue;
2915 if (Opc != ISD::BUILD_VECTOR ||
2916 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2917 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002918 }
2919 }
2920 return true;
2921}
2922
2923/// getZeroVector - Returns a vector of specified type with all zero elements.
2924///
2925static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2926 assert(MVT::isVector(VT) && "Expected a vector type");
Chris Lattnere6aa3862007-11-25 00:24:49 +00002927
2928 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2929 // type. This ensures they get CSE'd.
2930 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2931 SDOperand Vec;
2932 if (MVT::getSizeInBits(VT) == 64) // MMX
2933 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2934 else // SSE
2935 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2936 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002937}
2938
Chris Lattnere6aa3862007-11-25 00:24:49 +00002939/// getOnesVector - Returns a vector of specified type with all bits set.
2940///
2941static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2942 assert(MVT::isVector(VT) && "Expected a vector type");
2943
2944 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2945 // type. This ensures they get CSE'd.
2946 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2947 SDOperand Vec;
2948 if (MVT::getSizeInBits(VT) == 64) // MMX
2949 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2950 else // SSE
2951 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2952 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2953}
2954
2955
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002956/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2957/// that point to V2 points to its first element.
2958static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2959 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2960
2961 bool Changed = false;
2962 SmallVector<SDOperand, 8> MaskVec;
2963 unsigned NumElems = Mask.getNumOperands();
2964 for (unsigned i = 0; i != NumElems; ++i) {
2965 SDOperand Arg = Mask.getOperand(i);
2966 if (Arg.getOpcode() != ISD::UNDEF) {
2967 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2968 if (Val > NumElems) {
2969 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2970 Changed = true;
2971 }
2972 }
2973 MaskVec.push_back(Arg);
2974 }
2975
2976 if (Changed)
2977 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2978 &MaskVec[0], MaskVec.size());
2979 return Mask;
2980}
2981
2982/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2983/// operation of specified width.
2984static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2985 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2986 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2987
2988 SmallVector<SDOperand, 8> MaskVec;
2989 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2990 for (unsigned i = 1; i != NumElems; ++i)
2991 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2992 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2993}
2994
2995/// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2996/// of specified width.
2997static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2998 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2999 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3000 SmallVector<SDOperand, 8> MaskVec;
3001 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3002 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3003 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
3004 }
3005 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3006}
3007
3008/// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3009/// of specified width.
3010static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
3011 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3012 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3013 unsigned Half = NumElems/2;
3014 SmallVector<SDOperand, 8> MaskVec;
3015 for (unsigned i = 0; i != Half; ++i) {
3016 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3017 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3018 }
3019 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3020}
3021
3022/// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
3023///
3024static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
3025 SDOperand V1 = Op.getOperand(0);
3026 SDOperand Mask = Op.getOperand(2);
3027 MVT::ValueType VT = Op.getValueType();
3028 unsigned NumElems = Mask.getNumOperands();
3029 Mask = getUnpacklMask(NumElems, DAG);
3030 while (NumElems != 4) {
3031 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
3032 NumElems >>= 1;
3033 }
3034 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
3035
Chris Lattnere6aa3862007-11-25 00:24:49 +00003036 Mask = getZeroVector(MVT::v4i32, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003037 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
3038 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
3039 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3040}
3041
3042/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
Chris Lattnere6aa3862007-11-25 00:24:49 +00003043/// vector of zero or undef vector. This produces a shuffle where the low
3044/// element of V2 is swizzled into the zero/undef vector, landing at element
3045/// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003046static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
3047 unsigned NumElems, unsigned Idx,
3048 bool isZero, SelectionDAG &DAG) {
3049 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
3050 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3051 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
Chris Lattnere6aa3862007-11-25 00:24:49 +00003052 SmallVector<SDOperand, 16> MaskVec;
3053 for (unsigned i = 0; i != NumElems; ++i)
3054 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3055 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3056 else
3057 MaskVec.push_back(DAG.getConstant(i, EVT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003058 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3059 &MaskVec[0], MaskVec.size());
3060 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3061}
3062
3063/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3064///
3065static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
3066 unsigned NumNonZero, unsigned NumZero,
3067 SelectionDAG &DAG, TargetLowering &TLI) {
3068 if (NumNonZero > 8)
3069 return SDOperand();
3070
3071 SDOperand V(0, 0);
3072 bool First = true;
3073 for (unsigned i = 0; i < 16; ++i) {
3074 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3075 if (ThisIsNonZero && First) {
3076 if (NumZero)
3077 V = getZeroVector(MVT::v8i16, DAG);
3078 else
3079 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3080 First = false;
3081 }
3082
3083 if ((i & 1) != 0) {
3084 SDOperand ThisElt(0, 0), LastElt(0, 0);
3085 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3086 if (LastIsNonZero) {
3087 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3088 }
3089 if (ThisIsNonZero) {
3090 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3091 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3092 ThisElt, DAG.getConstant(8, MVT::i8));
3093 if (LastIsNonZero)
3094 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3095 } else
3096 ThisElt = LastElt;
3097
3098 if (ThisElt.Val)
3099 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3100 DAG.getConstant(i/2, TLI.getPointerTy()));
3101 }
3102 }
3103
3104 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3105}
3106
3107/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3108///
3109static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3110 unsigned NumNonZero, unsigned NumZero,
3111 SelectionDAG &DAG, TargetLowering &TLI) {
3112 if (NumNonZero > 4)
3113 return SDOperand();
3114
3115 SDOperand V(0, 0);
3116 bool First = true;
3117 for (unsigned i = 0; i < 8; ++i) {
3118 bool isNonZero = (NonZeros & (1 << i)) != 0;
3119 if (isNonZero) {
3120 if (First) {
3121 if (NumZero)
3122 V = getZeroVector(MVT::v8i16, DAG);
3123 else
3124 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3125 First = false;
3126 }
3127 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3128 DAG.getConstant(i, TLI.getPointerTy()));
3129 }
3130 }
3131
3132 return V;
3133}
3134
Evan Cheng75184a92007-12-11 01:46:18 +00003135/// is4WideVector - Returns true if the specific v8i16 or v16i8 vector is
3136/// actually just a 4 wide vector. e.g. <a, a, y, y, d, d, x, x>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003137SDOperand
3138X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
Chris Lattnere6aa3862007-11-25 00:24:49 +00003139 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3140 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3141 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3142 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3143 // eliminated on x86-32 hosts.
3144 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3145 return Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003146
Chris Lattnere6aa3862007-11-25 00:24:49 +00003147 if (ISD::isBuildVectorAllOnes(Op.Val))
3148 return getOnesVector(Op.getValueType(), DAG);
3149 return getZeroVector(Op.getValueType(), DAG);
3150 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003151
3152 MVT::ValueType VT = Op.getValueType();
3153 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3154 unsigned EVTBits = MVT::getSizeInBits(EVT);
3155
3156 unsigned NumElems = Op.getNumOperands();
3157 unsigned NumZero = 0;
3158 unsigned NumNonZero = 0;
3159 unsigned NonZeros = 0;
Evan Chengc1073492007-12-12 06:45:40 +00003160 bool HasNonImms = false;
Evan Cheng75184a92007-12-11 01:46:18 +00003161 SmallSet<SDOperand, 8> Values;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003162 for (unsigned i = 0; i < NumElems; ++i) {
3163 SDOperand Elt = Op.getOperand(i);
Evan Chengc1073492007-12-12 06:45:40 +00003164 if (Elt.getOpcode() == ISD::UNDEF)
3165 continue;
3166 Values.insert(Elt);
3167 if (Elt.getOpcode() != ISD::Constant &&
3168 Elt.getOpcode() != ISD::ConstantFP)
3169 HasNonImms = true;
3170 if (isZeroNode(Elt))
3171 NumZero++;
3172 else {
3173 NonZeros |= (1 << i);
3174 NumNonZero++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003175 }
3176 }
3177
3178 if (NumNonZero == 0) {
Chris Lattnere6aa3862007-11-25 00:24:49 +00003179 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3180 return DAG.getNode(ISD::UNDEF, VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003181 }
3182
3183 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3184 if (Values.size() == 1)
3185 return SDOperand();
3186
3187 // Special case for single non-zero element.
Evan Chengc1073492007-12-12 06:45:40 +00003188 if (NumNonZero == 1 && NumElems <= 4) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003189 unsigned Idx = CountTrailingZeros_32(NonZeros);
3190 SDOperand Item = Op.getOperand(Idx);
3191 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3192 if (Idx == 0)
3193 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3194 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
3195 NumZero > 0, DAG);
Evan Chengc1073492007-12-12 06:45:40 +00003196 else if (!HasNonImms) // Otherwise, it's better to do a constpool load.
3197 return SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003198
3199 if (EVTBits == 32) {
3200 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3201 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
3202 DAG);
3203 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3204 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3205 SmallVector<SDOperand, 8> MaskVec;
3206 for (unsigned i = 0; i < NumElems; i++)
3207 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3208 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3209 &MaskVec[0], MaskVec.size());
3210 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3211 DAG.getNode(ISD::UNDEF, VT), Mask);
3212 }
3213 }
3214
Dan Gohman21463242007-07-24 22:55:08 +00003215 // A vector full of immediates; various special cases are already
3216 // handled, so this is best done with a single constant-pool load.
Evan Chengc1073492007-12-12 06:45:40 +00003217 if (!HasNonImms)
Dan Gohman21463242007-07-24 22:55:08 +00003218 return SDOperand();
3219
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003220 // Let legalizer expand 2-wide build_vectors.
3221 if (EVTBits == 64)
3222 return SDOperand();
3223
3224 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3225 if (EVTBits == 8 && NumElems == 16) {
3226 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3227 *this);
3228 if (V.Val) return V;
3229 }
3230
3231 if (EVTBits == 16 && NumElems == 8) {
3232 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3233 *this);
3234 if (V.Val) return V;
3235 }
3236
3237 // If element VT is == 32 bits, turn it into a number of shuffles.
3238 SmallVector<SDOperand, 8> V;
3239 V.resize(NumElems);
3240 if (NumElems == 4 && NumZero > 0) {
3241 for (unsigned i = 0; i < 4; ++i) {
3242 bool isZero = !(NonZeros & (1 << i));
3243 if (isZero)
3244 V[i] = getZeroVector(VT, DAG);
3245 else
3246 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3247 }
3248
3249 for (unsigned i = 0; i < 2; ++i) {
3250 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3251 default: break;
3252 case 0:
3253 V[i] = V[i*2]; // Must be a zero vector.
3254 break;
3255 case 1:
3256 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3257 getMOVLMask(NumElems, DAG));
3258 break;
3259 case 2:
3260 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3261 getMOVLMask(NumElems, DAG));
3262 break;
3263 case 3:
3264 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3265 getUnpacklMask(NumElems, DAG));
3266 break;
3267 }
3268 }
3269
3270 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3271 // clears the upper bits.
3272 // FIXME: we can do the same for v4f32 case when we know both parts of
3273 // the lower half come from scalar_to_vector (loadf32). We should do
3274 // that in post legalizer dag combiner with target specific hooks.
3275 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3276 return V[0];
3277 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3278 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3279 SmallVector<SDOperand, 8> MaskVec;
3280 bool Reverse = (NonZeros & 0x3) == 2;
3281 for (unsigned i = 0; i < 2; ++i)
3282 if (Reverse)
3283 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3284 else
3285 MaskVec.push_back(DAG.getConstant(i, EVT));
3286 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3287 for (unsigned i = 0; i < 2; ++i)
3288 if (Reverse)
3289 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3290 else
3291 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3292 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3293 &MaskVec[0], MaskVec.size());
3294 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3295 }
3296
3297 if (Values.size() > 2) {
3298 // Expand into a number of unpckl*.
3299 // e.g. for v4f32
3300 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3301 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3302 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3303 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3304 for (unsigned i = 0; i < NumElems; ++i)
3305 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3306 NumElems >>= 1;
3307 while (NumElems != 0) {
3308 for (unsigned i = 0; i < NumElems; ++i)
3309 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3310 UnpckMask);
3311 NumElems >>= 1;
3312 }
3313 return V[0];
3314 }
3315
3316 return SDOperand();
3317}
3318
Evan Chengfca29242007-12-07 08:07:39 +00003319static
3320SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3321 SDOperand PermMask, SelectionDAG &DAG,
3322 TargetLowering &TLI) {
Evan Cheng75184a92007-12-11 01:46:18 +00003323 SDOperand NewV;
Evan Chengfca29242007-12-07 08:07:39 +00003324 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3325 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
Evan Cheng75184a92007-12-11 01:46:18 +00003326 MVT::ValueType PtrVT = TLI.getPointerTy();
3327 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3328 PermMask.Val->op_end());
3329
3330 // First record which half of which vector the low elements come from.
3331 SmallVector<unsigned, 4> LowQuad(4);
3332 for (unsigned i = 0; i < 4; ++i) {
3333 SDOperand Elt = MaskElts[i];
3334 if (Elt.getOpcode() == ISD::UNDEF)
3335 continue;
3336 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3337 int QuadIdx = EltIdx / 4;
3338 ++LowQuad[QuadIdx];
3339 }
3340 int BestLowQuad = -1;
3341 unsigned MaxQuad = 1;
3342 for (unsigned i = 0; i < 4; ++i) {
3343 if (LowQuad[i] > MaxQuad) {
3344 BestLowQuad = i;
3345 MaxQuad = LowQuad[i];
3346 }
Evan Chengfca29242007-12-07 08:07:39 +00003347 }
3348
Evan Cheng75184a92007-12-11 01:46:18 +00003349 // Record which half of which vector the high elements come from.
3350 SmallVector<unsigned, 4> HighQuad(4);
3351 for (unsigned i = 4; i < 8; ++i) {
3352 SDOperand Elt = MaskElts[i];
3353 if (Elt.getOpcode() == ISD::UNDEF)
3354 continue;
3355 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3356 int QuadIdx = EltIdx / 4;
3357 ++HighQuad[QuadIdx];
3358 }
3359 int BestHighQuad = -1;
3360 MaxQuad = 1;
3361 for (unsigned i = 0; i < 4; ++i) {
3362 if (HighQuad[i] > MaxQuad) {
3363 BestHighQuad = i;
3364 MaxQuad = HighQuad[i];
3365 }
3366 }
3367
3368 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3369 if (BestLowQuad != -1 || BestHighQuad != -1) {
3370 // First sort the 4 chunks in order using shufpd.
3371 SmallVector<SDOperand, 8> MaskVec;
3372 if (BestLowQuad != -1)
3373 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3374 else
3375 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3376 if (BestHighQuad != -1)
3377 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3378 else
3379 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3380 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3381 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3382 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3383 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3384 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3385
3386 // Now sort high and low parts separately.
3387 BitVector InOrder(8);
3388 if (BestLowQuad != -1) {
3389 // Sort lower half in order using PSHUFLW.
3390 MaskVec.clear();
3391 bool AnyOutOrder = false;
3392 for (unsigned i = 0; i != 4; ++i) {
3393 SDOperand Elt = MaskElts[i];
3394 if (Elt.getOpcode() == ISD::UNDEF) {
3395 MaskVec.push_back(Elt);
3396 InOrder.set(i);
3397 } else {
3398 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3399 if (EltIdx != i)
3400 AnyOutOrder = true;
3401 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3402 // If this element is in the right place after this shuffle, then
3403 // remember it.
3404 if ((int)(EltIdx / 4) == BestLowQuad)
3405 InOrder.set(i);
3406 }
3407 }
3408 if (AnyOutOrder) {
3409 for (unsigned i = 4; i != 8; ++i)
3410 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3411 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3412 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3413 }
3414 }
3415
3416 if (BestHighQuad != -1) {
3417 // Sort high half in order using PSHUFHW if possible.
3418 MaskVec.clear();
3419 for (unsigned i = 0; i != 4; ++i)
3420 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3421 bool AnyOutOrder = false;
3422 for (unsigned i = 4; i != 8; ++i) {
3423 SDOperand Elt = MaskElts[i];
3424 if (Elt.getOpcode() == ISD::UNDEF) {
3425 MaskVec.push_back(Elt);
3426 InOrder.set(i);
3427 } else {
3428 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3429 if (EltIdx != i)
3430 AnyOutOrder = true;
3431 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3432 // If this element is in the right place after this shuffle, then
3433 // remember it.
3434 if ((int)(EltIdx / 4) == BestHighQuad)
3435 InOrder.set(i);
3436 }
3437 }
3438 if (AnyOutOrder) {
3439 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3440 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3441 }
3442 }
3443
3444 // The other elements are put in the right place using pextrw and pinsrw.
3445 for (unsigned i = 0; i != 8; ++i) {
3446 if (InOrder[i])
3447 continue;
3448 SDOperand Elt = MaskElts[i];
3449 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3450 if (EltIdx == i)
3451 continue;
3452 SDOperand ExtOp = (EltIdx < 8)
3453 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3454 DAG.getConstant(EltIdx, PtrVT))
3455 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3456 DAG.getConstant(EltIdx - 8, PtrVT));
3457 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3458 DAG.getConstant(i, PtrVT));
3459 }
3460 return NewV;
3461 }
3462
3463 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3464 ///as few as possible.
Evan Chengfca29242007-12-07 08:07:39 +00003465 // First, let's find out how many elements are already in the right order.
3466 unsigned V1InOrder = 0;
3467 unsigned V1FromV1 = 0;
3468 unsigned V2InOrder = 0;
3469 unsigned V2FromV2 = 0;
Evan Cheng75184a92007-12-11 01:46:18 +00003470 SmallVector<SDOperand, 8> V1Elts;
3471 SmallVector<SDOperand, 8> V2Elts;
Evan Chengfca29242007-12-07 08:07:39 +00003472 for (unsigned i = 0; i < 8; ++i) {
Evan Cheng75184a92007-12-11 01:46:18 +00003473 SDOperand Elt = MaskElts[i];
Evan Chengfca29242007-12-07 08:07:39 +00003474 if (Elt.getOpcode() == ISD::UNDEF) {
Evan Cheng75184a92007-12-11 01:46:18 +00003475 V1Elts.push_back(Elt);
3476 V2Elts.push_back(Elt);
Evan Chengfca29242007-12-07 08:07:39 +00003477 ++V1InOrder;
3478 ++V2InOrder;
Evan Cheng75184a92007-12-11 01:46:18 +00003479 continue;
3480 }
3481 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3482 if (EltIdx == i) {
3483 V1Elts.push_back(Elt);
3484 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3485 ++V1InOrder;
3486 } else if (EltIdx == i+8) {
3487 V1Elts.push_back(Elt);
3488 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3489 ++V2InOrder;
3490 } else if (EltIdx < 8) {
3491 V1Elts.push_back(Elt);
3492 ++V1FromV1;
Evan Chengfca29242007-12-07 08:07:39 +00003493 } else {
Evan Cheng75184a92007-12-11 01:46:18 +00003494 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3495 ++V2FromV2;
Evan Chengfca29242007-12-07 08:07:39 +00003496 }
3497 }
3498
3499 if (V2InOrder > V1InOrder) {
3500 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3501 std::swap(V1, V2);
3502 std::swap(V1Elts, V2Elts);
3503 std::swap(V1FromV1, V2FromV2);
3504 }
3505
Evan Cheng75184a92007-12-11 01:46:18 +00003506 if ((V1FromV1 + V1InOrder) != 8) {
3507 // Some elements are from V2.
3508 if (V1FromV1) {
3509 // If there are elements that are from V1 but out of place,
3510 // then first sort them in place
3511 SmallVector<SDOperand, 8> MaskVec;
3512 for (unsigned i = 0; i < 8; ++i) {
3513 SDOperand Elt = V1Elts[i];
3514 if (Elt.getOpcode() == ISD::UNDEF) {
3515 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3516 continue;
3517 }
3518 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3519 if (EltIdx >= 8)
3520 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3521 else
3522 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3523 }
3524 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3525 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
Evan Chengfca29242007-12-07 08:07:39 +00003526 }
Evan Cheng75184a92007-12-11 01:46:18 +00003527
3528 NewV = V1;
3529 for (unsigned i = 0; i < 8; ++i) {
3530 SDOperand Elt = V1Elts[i];
3531 if (Elt.getOpcode() == ISD::UNDEF)
3532 continue;
3533 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3534 if (EltIdx < 8)
3535 continue;
3536 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3537 DAG.getConstant(EltIdx - 8, PtrVT));
3538 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3539 DAG.getConstant(i, PtrVT));
3540 }
3541 return NewV;
3542 } else {
3543 // All elements are from V1.
3544 NewV = V1;
3545 for (unsigned i = 0; i < 8; ++i) {
3546 SDOperand Elt = V1Elts[i];
3547 if (Elt.getOpcode() == ISD::UNDEF)
3548 continue;
3549 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3550 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3551 DAG.getConstant(EltIdx, PtrVT));
3552 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3553 DAG.getConstant(i, PtrVT));
3554 }
3555 return NewV;
3556 }
3557}
3558
3559/// RewriteAs4WideShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3560/// ones if possible. This can be done when every pair / quad of shuffle mask
3561/// elements point to elements in the right sequence. e.g.
3562/// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3563static
3564SDOperand RewriteAs4WideShuffle(SDOperand V1, SDOperand V2,
3565 SDOperand PermMask, SelectionDAG &DAG,
3566 TargetLowering &TLI) {
3567 unsigned NumElems = PermMask.getNumOperands();
3568 unsigned Scale = NumElems / 4;
3569 SmallVector<SDOperand, 4> MaskVec;
3570 for (unsigned i = 0; i < NumElems; i += Scale) {
3571 unsigned StartIdx = ~0U;
3572 for (unsigned j = 0; j < Scale; ++j) {
3573 SDOperand Elt = PermMask.getOperand(i+j);
3574 if (Elt.getOpcode() == ISD::UNDEF)
3575 continue;
3576 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3577 if (StartIdx == ~0U)
3578 StartIdx = EltIdx - (EltIdx % Scale);
3579 if (EltIdx != StartIdx + j)
3580 return SDOperand();
3581 }
3582 if (StartIdx == ~0U)
3583 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3584 else
3585 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
Evan Chengfca29242007-12-07 08:07:39 +00003586 }
3587
Evan Cheng75184a92007-12-11 01:46:18 +00003588 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
3589 V2 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V2);
3590 return DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1, V2,
3591 DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, &MaskVec[0],4));
Evan Chengfca29242007-12-07 08:07:39 +00003592}
3593
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003594SDOperand
3595X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3596 SDOperand V1 = Op.getOperand(0);
3597 SDOperand V2 = Op.getOperand(1);
3598 SDOperand PermMask = Op.getOperand(2);
3599 MVT::ValueType VT = Op.getValueType();
3600 unsigned NumElems = PermMask.getNumOperands();
3601 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3602 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3603 bool V1IsSplat = false;
3604 bool V2IsSplat = false;
3605
3606 if (isUndefShuffle(Op.Val))
3607 return DAG.getNode(ISD::UNDEF, VT);
3608
3609 if (isZeroShuffle(Op.Val))
3610 return getZeroVector(VT, DAG);
3611
3612 if (isIdentityMask(PermMask.Val))
3613 return V1;
3614 else if (isIdentityMask(PermMask.Val, true))
3615 return V2;
3616
3617 if (isSplatMask(PermMask.Val)) {
3618 if (NumElems <= 4) return Op;
3619 // Promote it to a v4i32 splat.
3620 return PromoteSplat(Op, DAG);
3621 }
3622
3623 if (X86::isMOVLMask(PermMask.Val))
3624 return (V1IsUndef) ? V2 : Op;
3625
3626 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3627 X86::isMOVSLDUPMask(PermMask.Val) ||
3628 X86::isMOVHLPSMask(PermMask.Val) ||
3629 X86::isMOVHPMask(PermMask.Val) ||
3630 X86::isMOVLPMask(PermMask.Val))
3631 return Op;
3632
3633 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3634 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3635 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3636
3637 bool Commuted = false;
Chris Lattnere6aa3862007-11-25 00:24:49 +00003638 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3639 // 1,1,1,1 -> v8i16 though.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003640 V1IsSplat = isSplatVector(V1.Val);
3641 V2IsSplat = isSplatVector(V2.Val);
Chris Lattnere6aa3862007-11-25 00:24:49 +00003642
3643 // Canonicalize the splat or undef, if present, to be on the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003644 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3645 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3646 std::swap(V1IsSplat, V2IsSplat);
3647 std::swap(V1IsUndef, V2IsUndef);
3648 Commuted = true;
3649 }
3650
3651 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3652 if (V2IsUndef) return V1;
3653 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3654 if (V2IsSplat) {
3655 // V2 is a splat, so the mask may be malformed. That is, it may point
3656 // to any V2 element. The instruction selectior won't like this. Get
3657 // a corrected mask and commute to form a proper MOVS{S|D}.
3658 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3659 if (NewMask.Val != PermMask.Val)
3660 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3661 }
3662 return Op;
3663 }
3664
3665 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3666 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3667 X86::isUNPCKLMask(PermMask.Val) ||
3668 X86::isUNPCKHMask(PermMask.Val))
3669 return Op;
3670
3671 if (V2IsSplat) {
3672 // Normalize mask so all entries that point to V2 points to its first
3673 // element then try to match unpck{h|l} again. If match, return a
3674 // new vector_shuffle with the corrected mask.
3675 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3676 if (NewMask.Val != PermMask.Val) {
3677 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3678 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3679 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3680 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3681 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3682 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3683 }
3684 }
3685 }
3686
3687 // Normalize the node to match x86 shuffle ops if needed
3688 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3689 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3690
3691 if (Commuted) {
3692 // Commute is back and try unpck* again.
3693 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3694 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3695 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3696 X86::isUNPCKLMask(PermMask.Val) ||
3697 X86::isUNPCKHMask(PermMask.Val))
3698 return Op;
3699 }
3700
3701 // If VT is integer, try PSHUF* first, then SHUFP*.
3702 if (MVT::isInteger(VT)) {
Dan Gohman7dc19012007-08-02 21:17:01 +00003703 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3704 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3705 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3706 X86::isPSHUFDMask(PermMask.Val)) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003707 X86::isPSHUFHWMask(PermMask.Val) ||
3708 X86::isPSHUFLWMask(PermMask.Val)) {
3709 if (V2.getOpcode() != ISD::UNDEF)
3710 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3711 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3712 return Op;
3713 }
3714
3715 if (X86::isSHUFPMask(PermMask.Val) &&
3716 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3717 return Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003718 } else {
3719 // Floating point cases in the other order.
3720 if (X86::isSHUFPMask(PermMask.Val))
3721 return Op;
3722 if (X86::isPSHUFDMask(PermMask.Val) ||
3723 X86::isPSHUFHWMask(PermMask.Val) ||
3724 X86::isPSHUFLWMask(PermMask.Val)) {
3725 if (V2.getOpcode() != ISD::UNDEF)
3726 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3727 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3728 return Op;
3729 }
3730 }
3731
Evan Cheng75184a92007-12-11 01:46:18 +00003732 // If the shuffle can be rewritten as a 4 wide shuffle, then do it!
3733 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3734 SDOperand NewOp = RewriteAs4WideShuffle(V1, V2, PermMask, DAG, *this);
3735 if (NewOp.Val)
3736 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3737 }
Evan Chengfca29242007-12-07 08:07:39 +00003738
Evan Cheng75184a92007-12-11 01:46:18 +00003739 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3740 if (VT == MVT::v8i16) {
3741 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3742 if (NewOp.Val)
3743 return NewOp;
3744 }
3745
3746 // Handle all 4 wide cases with a number of shuffles.
3747 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
Evan Chengfca29242007-12-07 08:07:39 +00003748 // Don't do this for MMX.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003749 MVT::ValueType MaskVT = PermMask.getValueType();
3750 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3751 SmallVector<std::pair<int, int>, 8> Locs;
3752 Locs.reserve(NumElems);
Evan Cheng75184a92007-12-11 01:46:18 +00003753 SmallVector<SDOperand, 8> Mask1(NumElems,
3754 DAG.getNode(ISD::UNDEF, MaskEVT));
3755 SmallVector<SDOperand, 8> Mask2(NumElems,
3756 DAG.getNode(ISD::UNDEF, MaskEVT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003757 unsigned NumHi = 0;
3758 unsigned NumLo = 0;
3759 // If no more than two elements come from either vector. This can be
3760 // implemented with two shuffles. First shuffle gather the elements.
3761 // The second shuffle, which takes the first shuffle as both of its
3762 // vector operands, put the elements into the right order.
3763 for (unsigned i = 0; i != NumElems; ++i) {
3764 SDOperand Elt = PermMask.getOperand(i);
3765 if (Elt.getOpcode() == ISD::UNDEF) {
3766 Locs[i] = std::make_pair(-1, -1);
3767 } else {
3768 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3769 if (Val < NumElems) {
3770 Locs[i] = std::make_pair(0, NumLo);
3771 Mask1[NumLo] = Elt;
3772 NumLo++;
3773 } else {
3774 Locs[i] = std::make_pair(1, NumHi);
3775 if (2+NumHi < NumElems)
3776 Mask1[2+NumHi] = Elt;
3777 NumHi++;
3778 }
3779 }
3780 }
3781 if (NumLo <= 2 && NumHi <= 2) {
3782 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3783 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3784 &Mask1[0], Mask1.size()));
3785 for (unsigned i = 0; i != NumElems; ++i) {
3786 if (Locs[i].first == -1)
3787 continue;
3788 else {
3789 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3790 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3791 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3792 }
3793 }
3794
3795 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3796 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3797 &Mask2[0], Mask2.size()));
3798 }
3799
3800 // Break it into (shuffle shuffle_hi, shuffle_lo).
3801 Locs.clear();
3802 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3803 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3804 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3805 unsigned MaskIdx = 0;
3806 unsigned LoIdx = 0;
3807 unsigned HiIdx = NumElems/2;
3808 for (unsigned i = 0; i != NumElems; ++i) {
3809 if (i == NumElems/2) {
3810 MaskPtr = &HiMask;
3811 MaskIdx = 1;
3812 LoIdx = 0;
3813 HiIdx = NumElems/2;
3814 }
3815 SDOperand Elt = PermMask.getOperand(i);
3816 if (Elt.getOpcode() == ISD::UNDEF) {
3817 Locs[i] = std::make_pair(-1, -1);
3818 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3819 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3820 (*MaskPtr)[LoIdx] = Elt;
3821 LoIdx++;
3822 } else {
3823 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3824 (*MaskPtr)[HiIdx] = Elt;
3825 HiIdx++;
3826 }
3827 }
3828
3829 SDOperand LoShuffle =
3830 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3831 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3832 &LoMask[0], LoMask.size()));
3833 SDOperand HiShuffle =
3834 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3835 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3836 &HiMask[0], HiMask.size()));
3837 SmallVector<SDOperand, 8> MaskOps;
3838 for (unsigned i = 0; i != NumElems; ++i) {
3839 if (Locs[i].first == -1) {
3840 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3841 } else {
3842 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3843 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3844 }
3845 }
3846 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3847 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3848 &MaskOps[0], MaskOps.size()));
3849 }
3850
3851 return SDOperand();
3852}
3853
3854SDOperand
3855X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3856 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3857 return SDOperand();
3858
3859 MVT::ValueType VT = Op.getValueType();
3860 // TODO: handle v16i8.
3861 if (MVT::getSizeInBits(VT) == 16) {
Evan Cheng75184a92007-12-11 01:46:18 +00003862 SDOperand Vec = Op.getOperand(0);
3863 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3864 if (Idx == 0)
3865 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3866 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3867 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3868 Op.getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003869 // Transform it so it match pextrw which produces a 32-bit result.
3870 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3871 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3872 Op.getOperand(0), Op.getOperand(1));
3873 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3874 DAG.getValueType(VT));
3875 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3876 } else if (MVT::getSizeInBits(VT) == 32) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003877 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3878 if (Idx == 0)
3879 return Op;
3880 // SHUFPS the element to the lowest double word, then movss.
3881 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3882 SmallVector<SDOperand, 8> IdxVec;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00003883 IdxVec.
3884 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3885 IdxVec.
3886 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3887 IdxVec.
3888 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3889 IdxVec.
3890 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003891 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3892 &IdxVec[0], IdxVec.size());
Evan Cheng75184a92007-12-11 01:46:18 +00003893 SDOperand Vec = Op.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003894 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3895 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3896 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3897 DAG.getConstant(0, getPointerTy()));
3898 } else if (MVT::getSizeInBits(VT) == 64) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003899 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3900 if (Idx == 0)
3901 return Op;
3902
3903 // UNPCKHPD the element to the lowest double word, then movsd.
3904 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3905 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3906 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3907 SmallVector<SDOperand, 8> IdxVec;
3908 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00003909 IdxVec.
3910 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003911 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3912 &IdxVec[0], IdxVec.size());
Evan Cheng75184a92007-12-11 01:46:18 +00003913 SDOperand Vec = Op.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003914 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3915 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3916 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3917 DAG.getConstant(0, getPointerTy()));
3918 }
3919
3920 return SDOperand();
3921}
3922
3923SDOperand
3924X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3925 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3926 // as its second argument.
3927 MVT::ValueType VT = Op.getValueType();
3928 MVT::ValueType BaseVT = MVT::getVectorElementType(VT);
3929 SDOperand N0 = Op.getOperand(0);
3930 SDOperand N1 = Op.getOperand(1);
3931 SDOperand N2 = Op.getOperand(2);
3932 if (MVT::getSizeInBits(BaseVT) == 16) {
3933 if (N1.getValueType() != MVT::i32)
3934 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3935 if (N2.getValueType() != MVT::i32)
3936 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
3937 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3938 } else if (MVT::getSizeInBits(BaseVT) == 32) {
3939 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
3940 if (Idx == 0) {
3941 // Use a movss.
3942 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
3943 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3944 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3945 SmallVector<SDOperand, 8> MaskVec;
3946 MaskVec.push_back(DAG.getConstant(4, BaseVT));
3947 for (unsigned i = 1; i <= 3; ++i)
3948 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3949 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
3950 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3951 &MaskVec[0], MaskVec.size()));
3952 } else {
3953 // Use two pinsrw instructions to insert a 32 bit value.
3954 Idx <<= 1;
3955 if (MVT::isFloatingPoint(N1.getValueType())) {
Evan Cheng1eea6752007-07-31 06:21:44 +00003956 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
3957 N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
3958 N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
3959 DAG.getConstant(0, getPointerTy()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003960 }
3961 N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
3962 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3963 DAG.getConstant(Idx, getPointerTy()));
3964 N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
3965 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3966 DAG.getConstant(Idx+1, getPointerTy()));
3967 return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3968 }
3969 }
3970
3971 return SDOperand();
3972}
3973
3974SDOperand
3975X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3976 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3977 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3978}
3979
3980// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3981// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3982// one of the above mentioned nodes. It has to be wrapped because otherwise
3983// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3984// be used to form addressing mode. These wrapped nodes will be selected
3985// into MOV32ri.
3986SDOperand
3987X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3988 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3989 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3990 getPointerTy(),
3991 CP->getAlignment());
3992 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3993 // With PIC, the address is actually $g + Offset.
3994 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3995 !Subtarget->isPICStyleRIPRel()) {
3996 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3997 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3998 Result);
3999 }
4000
4001 return Result;
4002}
4003
4004SDOperand
4005X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4006 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4007 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4008 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4009 // With PIC, the address is actually $g + Offset.
4010 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4011 !Subtarget->isPICStyleRIPRel()) {
4012 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4013 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4014 Result);
4015 }
4016
4017 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4018 // load the value at address GV, not the value of GV itself. This means that
4019 // the GlobalAddress must be in the base or index register of the address, not
4020 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4021 // The same applies for external symbols during PIC codegen
4022 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4023 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
4024
4025 return Result;
4026}
4027
4028// Lower ISD::GlobalTLSAddress using the "general dynamic" model
4029static SDOperand
4030LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4031 const MVT::ValueType PtrVT) {
4032 SDOperand InFlag;
4033 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4034 DAG.getNode(X86ISD::GlobalBaseReg,
4035 PtrVT), InFlag);
4036 InFlag = Chain.getValue(1);
4037
4038 // emit leal symbol@TLSGD(,%ebx,1), %eax
4039 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4040 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4041 GA->getValueType(0),
4042 GA->getOffset());
4043 SDOperand Ops[] = { Chain, TGA, InFlag };
4044 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4045 InFlag = Result.getValue(2);
4046 Chain = Result.getValue(1);
4047
4048 // call ___tls_get_addr. This function receives its argument in
4049 // the register EAX.
4050 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4051 InFlag = Chain.getValue(1);
4052
4053 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4054 SDOperand Ops1[] = { Chain,
4055 DAG.getTargetExternalSymbol("___tls_get_addr",
4056 PtrVT),
4057 DAG.getRegister(X86::EAX, PtrVT),
4058 DAG.getRegister(X86::EBX, PtrVT),
4059 InFlag };
4060 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4061 InFlag = Chain.getValue(1);
4062
4063 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4064}
4065
4066// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4067// "local exec" model.
4068static SDOperand
4069LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4070 const MVT::ValueType PtrVT) {
4071 // Get the Thread Pointer
4072 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4073 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4074 // exec)
4075 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4076 GA->getValueType(0),
4077 GA->getOffset());
4078 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4079
4080 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4081 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
4082
4083 // The address of the thread local variable is the add of the thread
4084 // pointer with the offset of the variable.
4085 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4086}
4087
4088SDOperand
4089X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4090 // TODO: implement the "local dynamic" model
4091 // TODO: implement the "initial exec"model for pic executables
4092 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4093 "TLS not implemented for non-ELF and 64-bit targets");
4094 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4095 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4096 // otherwise use the "Local Exec"TLS Model
4097 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4098 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4099 else
4100 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4101}
4102
4103SDOperand
4104X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4105 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4106 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4107 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4108 // With PIC, the address is actually $g + Offset.
4109 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4110 !Subtarget->isPICStyleRIPRel()) {
4111 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4112 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4113 Result);
4114 }
4115
4116 return Result;
4117}
4118
4119SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4120 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4121 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4122 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4123 // With PIC, the address is actually $g + Offset.
4124 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4125 !Subtarget->isPICStyleRIPRel()) {
4126 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4127 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4128 Result);
4129 }
4130
4131 return Result;
4132}
4133
Chris Lattner62814a32007-10-17 06:02:13 +00004134/// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4135/// take a 2 x i32 value to shift plus a shift amount.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004136SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner62814a32007-10-17 06:02:13 +00004137 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
4138 "Not an i64 shift!");
4139 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4140 SDOperand ShOpLo = Op.getOperand(0);
4141 SDOperand ShOpHi = Op.getOperand(1);
4142 SDOperand ShAmt = Op.getOperand(2);
4143 SDOperand Tmp1 = isSRA ?
4144 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
4145 DAG.getConstant(0, MVT::i32);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004146
Chris Lattner62814a32007-10-17 06:02:13 +00004147 SDOperand Tmp2, Tmp3;
4148 if (Op.getOpcode() == ISD::SHL_PARTS) {
4149 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
4150 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
4151 } else {
4152 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
4153 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
4154 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004155
Chris Lattner62814a32007-10-17 06:02:13 +00004156 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4157 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4158 DAG.getConstant(32, MVT::i8));
4159 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
4160 AndNode, DAG.getConstant(0, MVT::i8));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004161
Chris Lattner62814a32007-10-17 06:02:13 +00004162 SDOperand Hi, Lo;
4163 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4164 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
4165 SmallVector<SDOperand, 4> Ops;
4166 if (Op.getOpcode() == ISD::SHL_PARTS) {
4167 Ops.push_back(Tmp2);
4168 Ops.push_back(Tmp3);
4169 Ops.push_back(CC);
4170 Ops.push_back(Cond);
4171 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004172
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004173 Ops.clear();
Chris Lattner62814a32007-10-17 06:02:13 +00004174 Ops.push_back(Tmp3);
4175 Ops.push_back(Tmp1);
4176 Ops.push_back(CC);
4177 Ops.push_back(Cond);
4178 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4179 } else {
4180 Ops.push_back(Tmp2);
4181 Ops.push_back(Tmp3);
4182 Ops.push_back(CC);
4183 Ops.push_back(Cond);
4184 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4185
4186 Ops.clear();
4187 Ops.push_back(Tmp3);
4188 Ops.push_back(Tmp1);
4189 Ops.push_back(CC);
4190 Ops.push_back(Cond);
4191 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4192 }
4193
4194 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
4195 Ops.clear();
4196 Ops.push_back(Lo);
4197 Ops.push_back(Hi);
4198 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004199}
4200
4201SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4202 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
4203 Op.getOperand(0).getValueType() >= MVT::i16 &&
4204 "Unknown SINT_TO_FP to lower!");
4205
4206 SDOperand Result;
4207 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4208 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4209 MachineFunction &MF = DAG.getMachineFunction();
4210 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4211 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4212 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4213 StackSlot, NULL, 0);
4214
Dale Johannesen2fc20782007-09-14 22:26:36 +00004215 // These are really Legal; caller falls through into that case.
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004216 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f32 && X86ScalarSSEf32)
4217 return Result;
4218 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f64 && X86ScalarSSEf64)
Dale Johannesen2fc20782007-09-14 22:26:36 +00004219 return Result;
Dale Johannesen958b08b2007-09-19 23:55:34 +00004220 if (SrcVT==MVT::i64 && Op.getValueType() != MVT::f80 &&
4221 Subtarget->is64Bit())
4222 return Result;
Dale Johannesen2fc20782007-09-14 22:26:36 +00004223
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004224 // Build the FILD
4225 SDVTList Tys;
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004226 bool useSSE = (X86ScalarSSEf32 && Op.getValueType() == MVT::f32) ||
4227 (X86ScalarSSEf64 && Op.getValueType() == MVT::f64);
Dale Johannesen2fc20782007-09-14 22:26:36 +00004228 if (useSSE)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004229 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4230 else
4231 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4232 SmallVector<SDOperand, 8> Ops;
4233 Ops.push_back(Chain);
4234 Ops.push_back(StackSlot);
4235 Ops.push_back(DAG.getValueType(SrcVT));
Dale Johannesen2fc20782007-09-14 22:26:36 +00004236 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004237 Tys, &Ops[0], Ops.size());
4238
Dale Johannesen2fc20782007-09-14 22:26:36 +00004239 if (useSSE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004240 Chain = Result.getValue(1);
4241 SDOperand InFlag = Result.getValue(2);
4242
4243 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4244 // shouldn't be necessary except that RFP cannot be live across
4245 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4246 MachineFunction &MF = DAG.getMachineFunction();
4247 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4248 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4249 Tys = DAG.getVTList(MVT::Other);
4250 SmallVector<SDOperand, 8> Ops;
4251 Ops.push_back(Chain);
4252 Ops.push_back(Result);
4253 Ops.push_back(StackSlot);
4254 Ops.push_back(DAG.getValueType(Op.getValueType()));
4255 Ops.push_back(InFlag);
4256 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4257 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
4258 }
4259
4260 return Result;
4261}
4262
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004263std::pair<SDOperand,SDOperand> X86TargetLowering::
4264FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004265 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4266 "Unknown FP_TO_SINT to lower!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004267
Dale Johannesen2fc20782007-09-14 22:26:36 +00004268 // These are really Legal.
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004269 if (Op.getValueType() == MVT::i32 &&
4270 X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32)
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004271 return std::make_pair(SDOperand(), SDOperand());
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004272 if (Op.getValueType() == MVT::i32 &&
4273 X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004274 return std::make_pair(SDOperand(), SDOperand());
Dale Johannesen958b08b2007-09-19 23:55:34 +00004275 if (Subtarget->is64Bit() &&
4276 Op.getValueType() == MVT::i64 &&
4277 Op.getOperand(0).getValueType() != MVT::f80)
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004278 return std::make_pair(SDOperand(), SDOperand());
Dale Johannesen2fc20782007-09-14 22:26:36 +00004279
Evan Cheng05441e62007-10-15 20:11:21 +00004280 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4281 // stack slot.
4282 MachineFunction &MF = DAG.getMachineFunction();
4283 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4284 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4285 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004286 unsigned Opc;
4287 switch (Op.getValueType()) {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004288 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4289 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4290 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4291 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004292 }
4293
4294 SDOperand Chain = DAG.getEntryNode();
4295 SDOperand Value = Op.getOperand(0);
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004296 if ((X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32) ||
4297 (X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004298 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4299 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
4300 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4301 SDOperand Ops[] = {
4302 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4303 };
4304 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4305 Chain = Value.getValue(1);
4306 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4307 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4308 }
4309
4310 // Build the FP_TO_INT*_IN_MEM
4311 SDOperand Ops[] = { Chain, Value, StackSlot };
4312 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4313
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004314 return std::make_pair(FIST, StackSlot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004315}
4316
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004317SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004318 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4319 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4320 if (FIST.Val == 0) return SDOperand();
4321
4322 // Load the result.
4323 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4324}
4325
4326SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4327 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4328 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4329 if (FIST.Val == 0) return 0;
4330
4331 // Return an i64 load from the stack slot.
4332 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4333
4334 // Use a MERGE_VALUES node to drop the chain result value.
4335 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4336}
4337
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004338SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4339 MVT::ValueType VT = Op.getValueType();
4340 MVT::ValueType EltVT = VT;
4341 if (MVT::isVector(VT))
4342 EltVT = MVT::getVectorElementType(VT);
4343 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4344 std::vector<Constant*> CV;
4345 if (EltVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004346 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004347 CV.push_back(C);
4348 CV.push_back(C);
4349 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004350 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004351 CV.push_back(C);
4352 CV.push_back(C);
4353 CV.push_back(C);
4354 CV.push_back(C);
4355 }
Dan Gohman11821702007-07-27 17:16:43 +00004356 Constant *C = ConstantVector::get(CV);
4357 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4358 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4359 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004360 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4361}
4362
4363SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4364 MVT::ValueType VT = Op.getValueType();
4365 MVT::ValueType EltVT = VT;
Evan Cheng92b8f782007-07-19 23:36:01 +00004366 unsigned EltNum = 1;
4367 if (MVT::isVector(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004368 EltVT = MVT::getVectorElementType(VT);
Evan Cheng92b8f782007-07-19 23:36:01 +00004369 EltNum = MVT::getVectorNumElements(VT);
4370 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004371 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4372 std::vector<Constant*> CV;
4373 if (EltVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004374 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004375 CV.push_back(C);
4376 CV.push_back(C);
4377 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004378 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004379 CV.push_back(C);
4380 CV.push_back(C);
4381 CV.push_back(C);
4382 CV.push_back(C);
4383 }
Dan Gohman11821702007-07-27 17:16:43 +00004384 Constant *C = ConstantVector::get(CV);
4385 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4386 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4387 false, 16);
Evan Cheng92b8f782007-07-19 23:36:01 +00004388 if (MVT::isVector(VT)) {
Evan Cheng92b8f782007-07-19 23:36:01 +00004389 return DAG.getNode(ISD::BIT_CONVERT, VT,
4390 DAG.getNode(ISD::XOR, MVT::v2i64,
4391 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4392 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4393 } else {
Evan Cheng92b8f782007-07-19 23:36:01 +00004394 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4395 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004396}
4397
4398SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4399 SDOperand Op0 = Op.getOperand(0);
4400 SDOperand Op1 = Op.getOperand(1);
4401 MVT::ValueType VT = Op.getValueType();
4402 MVT::ValueType SrcVT = Op1.getValueType();
4403 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4404
4405 // If second operand is smaller, extend it first.
4406 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4407 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4408 SrcVT = VT;
Dale Johannesenb9de9f02007-09-06 18:13:44 +00004409 SrcTy = MVT::getTypeForValueType(SrcVT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004410 }
Dale Johannesenfb0fa912007-10-21 01:07:44 +00004411 // And if it is bigger, shrink it first.
4412 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4413 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1);
4414 SrcVT = VT;
4415 SrcTy = MVT::getTypeForValueType(SrcVT);
4416 }
4417
4418 // At this point the operands and the result should have the same
4419 // type, and that won't be f80 since that is not custom lowered.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004420
4421 // First get the sign bit of second operand.
4422 std::vector<Constant*> CV;
4423 if (SrcVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004424 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4425 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004426 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004427 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4428 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4429 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4430 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004431 }
Dan Gohman11821702007-07-27 17:16:43 +00004432 Constant *C = ConstantVector::get(CV);
4433 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4434 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx, NULL, 0,
4435 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004436 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4437
4438 // Shift sign bit right or left if the two operands have different types.
4439 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4440 // Op0 is MVT::f32, Op1 is MVT::f64.
4441 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4442 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4443 DAG.getConstant(32, MVT::i32));
4444 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4445 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4446 DAG.getConstant(0, getPointerTy()));
4447 }
4448
4449 // Clear first operand sign bit.
4450 CV.clear();
4451 if (VT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004452 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4453 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004454 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004455 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4456 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4457 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4458 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004459 }
Dan Gohman11821702007-07-27 17:16:43 +00004460 C = ConstantVector::get(CV);
4461 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4462 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4463 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004464 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4465
4466 // Or the value with the sign bit.
4467 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4468}
4469
Evan Cheng621216e2007-09-29 00:00:36 +00004470SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
Evan Cheng950aac02007-09-25 01:57:46 +00004471 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
Evan Cheng6afec3d2007-09-26 00:45:55 +00004472 SDOperand Cond;
Evan Cheng950aac02007-09-25 01:57:46 +00004473 SDOperand Op0 = Op.getOperand(0);
4474 SDOperand Op1 = Op.getOperand(1);
4475 SDOperand CC = Op.getOperand(2);
4476 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4477 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4478 unsigned X86CC;
4479
Evan Cheng950aac02007-09-25 01:57:46 +00004480 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
Evan Cheng6afec3d2007-09-26 00:45:55 +00004481 Op0, Op1, DAG)) {
Evan Cheng621216e2007-09-29 00:00:36 +00004482 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4483 return DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004484 DAG.getConstant(X86CC, MVT::i8), Cond);
Evan Cheng6afec3d2007-09-26 00:45:55 +00004485 }
Evan Cheng950aac02007-09-25 01:57:46 +00004486
4487 assert(isFP && "Illegal integer SetCC!");
4488
Evan Cheng621216e2007-09-29 00:00:36 +00004489 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
Evan Cheng950aac02007-09-25 01:57:46 +00004490 switch (SetCCOpcode) {
4491 default: assert(false && "Illegal floating point SetCC!");
4492 case ISD::SETOEQ: { // !PF & ZF
Evan Cheng621216e2007-09-29 00:00:36 +00004493 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004494 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004495 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004496 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4497 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4498 }
4499 case ISD::SETUNE: { // PF | !ZF
Evan Cheng621216e2007-09-29 00:00:36 +00004500 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004501 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004502 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004503 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4504 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4505 }
4506 }
4507}
4508
4509
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004510SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4511 bool addTest = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004512 SDOperand Cond = Op.getOperand(0);
4513 SDOperand CC;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004514
4515 if (Cond.getOpcode() == ISD::SETCC)
Evan Cheng621216e2007-09-29 00:00:36 +00004516 Cond = LowerSETCC(Cond, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004517
Evan Cheng50d37ab2007-10-08 22:16:29 +00004518 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4519 // setting operand in place of the X86ISD::SETCC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004520 if (Cond.getOpcode() == X86ISD::SETCC) {
4521 CC = Cond.getOperand(0);
4522
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004523 SDOperand Cmp = Cond.getOperand(1);
4524 unsigned Opc = Cmp.getOpcode();
Evan Cheng50d37ab2007-10-08 22:16:29 +00004525 MVT::ValueType VT = Op.getValueType();
4526 bool IllegalFPCMov = false;
4527 if (VT == MVT::f32 && !X86ScalarSSEf32)
4528 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4529 else if (VT == MVT::f64 && !X86ScalarSSEf64)
4530 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
Dale Johannesen3b955db2007-10-16 18:09:08 +00004531 else if (VT == MVT::f80)
4532 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
Evan Cheng621216e2007-09-29 00:00:36 +00004533 if ((Opc == X86ISD::CMP ||
4534 Opc == X86ISD::COMI ||
4535 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
Evan Cheng50d37ab2007-10-08 22:16:29 +00004536 Cond = Cmp;
Evan Cheng950aac02007-09-25 01:57:46 +00004537 addTest = false;
4538 }
4539 }
4540
4541 if (addTest) {
4542 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
Evan Cheng50d37ab2007-10-08 22:16:29 +00004543 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
Evan Cheng950aac02007-09-25 01:57:46 +00004544 }
4545
4546 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4547 MVT::Flag);
4548 SmallVector<SDOperand, 4> Ops;
4549 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4550 // condition is true.
4551 Ops.push_back(Op.getOperand(2));
4552 Ops.push_back(Op.getOperand(1));
4553 Ops.push_back(CC);
4554 Ops.push_back(Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004555 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
Evan Cheng950aac02007-09-25 01:57:46 +00004556}
4557
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004558SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4559 bool addTest = true;
4560 SDOperand Chain = Op.getOperand(0);
4561 SDOperand Cond = Op.getOperand(1);
4562 SDOperand Dest = Op.getOperand(2);
4563 SDOperand CC;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004564
4565 if (Cond.getOpcode() == ISD::SETCC)
Evan Cheng621216e2007-09-29 00:00:36 +00004566 Cond = LowerSETCC(Cond, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004567
Evan Cheng50d37ab2007-10-08 22:16:29 +00004568 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4569 // setting operand in place of the X86ISD::SETCC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004570 if (Cond.getOpcode() == X86ISD::SETCC) {
4571 CC = Cond.getOperand(0);
4572
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004573 SDOperand Cmp = Cond.getOperand(1);
4574 unsigned Opc = Cmp.getOpcode();
Evan Cheng621216e2007-09-29 00:00:36 +00004575 if (Opc == X86ISD::CMP ||
4576 Opc == X86ISD::COMI ||
4577 Opc == X86ISD::UCOMI) {
Evan Cheng50d37ab2007-10-08 22:16:29 +00004578 Cond = Cmp;
Evan Cheng950aac02007-09-25 01:57:46 +00004579 addTest = false;
4580 }
4581 }
4582
4583 if (addTest) {
4584 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
Evan Cheng621216e2007-09-29 00:00:36 +00004585 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
Evan Cheng950aac02007-09-25 01:57:46 +00004586 }
Evan Cheng621216e2007-09-29 00:00:36 +00004587 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
Evan Cheng950aac02007-09-25 01:57:46 +00004588 Chain, Op.getOperand(2), CC, Cond);
4589}
4590
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004591SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004592 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4593 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004594
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004595 if (Subtarget->is64Bit())
4596 if(CallingConv==CallingConv::Fast && isTailCall && PerformTailCallOpt)
4597 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4598 else
4599 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004600 else
4601 switch (CallingConv) {
4602 default:
4603 assert(0 && "Unsupported calling convention");
4604 case CallingConv::Fast:
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004605 if (isTailCall && PerformTailCallOpt)
4606 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4607 else
4608 return LowerCCCCallTo(Op,DAG, CallingConv);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004609 case CallingConv::C:
4610 case CallingConv::X86_StdCall:
4611 return LowerCCCCallTo(Op, DAG, CallingConv);
4612 case CallingConv::X86_FastCall:
4613 return LowerFastCCCallTo(Op, DAG, CallingConv);
4614 }
4615}
4616
4617
4618// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4619// Calls to _alloca is needed to probe the stack when allocating more than 4k
4620// bytes in one go. Touching the stack at 4K increments is necessary to ensure
4621// that the guard pages used by the OS virtual memory manager are allocated in
4622// correct sequence.
4623SDOperand
4624X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4625 SelectionDAG &DAG) {
4626 assert(Subtarget->isTargetCygMing() &&
4627 "This should be used only on Cygwin/Mingw targets");
4628
4629 // Get the inputs.
4630 SDOperand Chain = Op.getOperand(0);
4631 SDOperand Size = Op.getOperand(1);
4632 // FIXME: Ensure alignment here
4633
4634 SDOperand Flag;
4635
4636 MVT::ValueType IntPtr = getPointerTy();
4637 MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
4638
4639 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4640 Flag = Chain.getValue(1);
4641
4642 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4643 SDOperand Ops[] = { Chain,
4644 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4645 DAG.getRegister(X86::EAX, IntPtr),
4646 Flag };
4647 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4648 Flag = Chain.getValue(1);
4649
4650 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4651
4652 std::vector<MVT::ValueType> Tys;
4653 Tys.push_back(SPTy);
4654 Tys.push_back(MVT::Other);
4655 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4656 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4657}
4658
4659SDOperand
4660X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
4661 MachineFunction &MF = DAG.getMachineFunction();
4662 const Function* Fn = MF.getFunction();
4663 if (Fn->hasExternalLinkage() &&
4664 Subtarget->isTargetCygMing() &&
4665 Fn->getName() == "main")
4666 MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
4667
4668 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4669 if (Subtarget->is64Bit())
4670 return LowerX86_64CCCArguments(Op, DAG);
4671 else
4672 switch(CC) {
4673 default:
4674 assert(0 && "Unsupported calling convention");
4675 case CallingConv::Fast:
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004676 return LowerCCCArguments(Op,DAG, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004677 // Falls through
4678 case CallingConv::C:
4679 return LowerCCCArguments(Op, DAG);
4680 case CallingConv::X86_StdCall:
4681 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
4682 return LowerCCCArguments(Op, DAG, true);
4683 case CallingConv::X86_FastCall:
4684 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
4685 return LowerFastCCArguments(Op, DAG);
4686 }
4687}
4688
4689SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4690 SDOperand InFlag(0, 0);
4691 SDOperand Chain = Op.getOperand(0);
4692 unsigned Align =
4693 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4694 if (Align == 0) Align = 1;
4695
4696 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
Rafael Espindola5d3e7622007-08-27 10:18:20 +00004697 // If not DWORD aligned or size is more than the threshold, call memset.
Rafael Espindolab2e7a6b2007-08-27 17:48:26 +00004698 // The libc version is likely to be faster for these cases. It can use the
4699 // address value and run time information about the CPU.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004700 if ((Align & 3) != 0 ||
Rafael Espindola7afa9b12007-10-31 11:52:06 +00004701 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004702 MVT::ValueType IntPtr = getPointerTy();
4703 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4704 TargetLowering::ArgListTy Args;
4705 TargetLowering::ArgListEntry Entry;
4706 Entry.Node = Op.getOperand(1);
4707 Entry.Ty = IntPtrTy;
4708 Args.push_back(Entry);
4709 // Extend the unsigned i8 argument to be an int value for the call.
4710 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4711 Entry.Ty = IntPtrTy;
4712 Args.push_back(Entry);
4713 Entry.Node = Op.getOperand(3);
4714 Args.push_back(Entry);
4715 std::pair<SDOperand,SDOperand> CallResult =
4716 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4717 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4718 return CallResult.second;
4719 }
4720
4721 MVT::ValueType AVT;
4722 SDOperand Count;
4723 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4724 unsigned BytesLeft = 0;
4725 bool TwoRepStos = false;
4726 if (ValC) {
4727 unsigned ValReg;
4728 uint64_t Val = ValC->getValue() & 255;
4729
4730 // If the value is a constant, then we can potentially use larger sets.
4731 switch (Align & 3) {
4732 case 2: // WORD aligned
4733 AVT = MVT::i16;
4734 ValReg = X86::AX;
4735 Val = (Val << 8) | Val;
4736 break;
4737 case 0: // DWORD aligned
4738 AVT = MVT::i32;
4739 ValReg = X86::EAX;
4740 Val = (Val << 8) | Val;
4741 Val = (Val << 16) | Val;
4742 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4743 AVT = MVT::i64;
4744 ValReg = X86::RAX;
4745 Val = (Val << 32) | Val;
4746 }
4747 break;
4748 default: // Byte aligned
4749 AVT = MVT::i8;
4750 ValReg = X86::AL;
4751 Count = Op.getOperand(3);
4752 break;
4753 }
4754
4755 if (AVT > MVT::i8) {
4756 if (I) {
4757 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4758 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
4759 BytesLeft = I->getValue() % UBytes;
4760 } else {
4761 assert(AVT >= MVT::i32 &&
4762 "Do not use rep;stos if not at least DWORD aligned");
4763 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4764 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4765 TwoRepStos = true;
4766 }
4767 }
4768
4769 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4770 InFlag);
4771 InFlag = Chain.getValue(1);
4772 } else {
4773 AVT = MVT::i8;
4774 Count = Op.getOperand(3);
4775 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4776 InFlag = Chain.getValue(1);
4777 }
4778
4779 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4780 Count, InFlag);
4781 InFlag = Chain.getValue(1);
4782 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4783 Op.getOperand(1), InFlag);
4784 InFlag = Chain.getValue(1);
4785
4786 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4787 SmallVector<SDOperand, 8> Ops;
4788 Ops.push_back(Chain);
4789 Ops.push_back(DAG.getValueType(AVT));
4790 Ops.push_back(InFlag);
4791 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4792
4793 if (TwoRepStos) {
4794 InFlag = Chain.getValue(1);
4795 Count = Op.getOperand(3);
4796 MVT::ValueType CVT = Count.getValueType();
4797 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4798 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4799 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4800 Left, InFlag);
4801 InFlag = Chain.getValue(1);
4802 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4803 Ops.clear();
4804 Ops.push_back(Chain);
4805 Ops.push_back(DAG.getValueType(MVT::i8));
4806 Ops.push_back(InFlag);
4807 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4808 } else if (BytesLeft) {
4809 // Issue stores for the last 1 - 7 bytes.
4810 SDOperand Value;
4811 unsigned Val = ValC->getValue() & 255;
4812 unsigned Offset = I->getValue() - BytesLeft;
4813 SDOperand DstAddr = Op.getOperand(1);
4814 MVT::ValueType AddrVT = DstAddr.getValueType();
4815 if (BytesLeft >= 4) {
4816 Val = (Val << 8) | Val;
4817 Val = (Val << 16) | Val;
4818 Value = DAG.getConstant(Val, MVT::i32);
4819 Chain = DAG.getStore(Chain, Value,
4820 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4821 DAG.getConstant(Offset, AddrVT)),
4822 NULL, 0);
4823 BytesLeft -= 4;
4824 Offset += 4;
4825 }
4826 if (BytesLeft >= 2) {
4827 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4828 Chain = DAG.getStore(Chain, Value,
4829 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4830 DAG.getConstant(Offset, AddrVT)),
4831 NULL, 0);
4832 BytesLeft -= 2;
4833 Offset += 2;
4834 }
4835 if (BytesLeft == 1) {
4836 Value = DAG.getConstant(Val, MVT::i8);
4837 Chain = DAG.getStore(Chain, Value,
4838 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4839 DAG.getConstant(Offset, AddrVT)),
4840 NULL, 0);
4841 }
4842 }
4843
4844 return Chain;
4845}
4846
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004847SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4848 SDOperand Dest,
4849 SDOperand Source,
4850 unsigned Size,
4851 unsigned Align,
4852 SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004853 MVT::ValueType AVT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004854 unsigned BytesLeft = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004855 switch (Align & 3) {
4856 case 2: // WORD aligned
4857 AVT = MVT::i16;
4858 break;
4859 case 0: // DWORD aligned
4860 AVT = MVT::i32;
4861 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4862 AVT = MVT::i64;
4863 break;
4864 default: // Byte aligned
4865 AVT = MVT::i8;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004866 break;
4867 }
4868
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004869 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4870 SDOperand Count = DAG.getConstant(Size / UBytes, getPointerTy());
4871 BytesLeft = Size % UBytes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004872
4873 SDOperand InFlag(0, 0);
4874 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4875 Count, InFlag);
4876 InFlag = Chain.getValue(1);
4877 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004878 Dest, InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004879 InFlag = Chain.getValue(1);
4880 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004881 Source, InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004882 InFlag = Chain.getValue(1);
4883
4884 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4885 SmallVector<SDOperand, 8> Ops;
4886 Ops.push_back(Chain);
4887 Ops.push_back(DAG.getValueType(AVT));
4888 Ops.push_back(InFlag);
4889 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4890
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004891 if (BytesLeft) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004892 // Issue loads and stores for the last 1 - 7 bytes.
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004893 unsigned Offset = Size - BytesLeft;
4894 SDOperand DstAddr = Dest;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004895 MVT::ValueType DstVT = DstAddr.getValueType();
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004896 SDOperand SrcAddr = Source;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004897 MVT::ValueType SrcVT = SrcAddr.getValueType();
4898 SDOperand Value;
4899 if (BytesLeft >= 4) {
4900 Value = DAG.getLoad(MVT::i32, Chain,
4901 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4902 DAG.getConstant(Offset, SrcVT)),
4903 NULL, 0);
4904 Chain = Value.getValue(1);
4905 Chain = DAG.getStore(Chain, Value,
4906 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4907 DAG.getConstant(Offset, DstVT)),
4908 NULL, 0);
4909 BytesLeft -= 4;
4910 Offset += 4;
4911 }
4912 if (BytesLeft >= 2) {
4913 Value = DAG.getLoad(MVT::i16, Chain,
4914 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4915 DAG.getConstant(Offset, SrcVT)),
4916 NULL, 0);
4917 Chain = Value.getValue(1);
4918 Chain = DAG.getStore(Chain, Value,
4919 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4920 DAG.getConstant(Offset, DstVT)),
4921 NULL, 0);
4922 BytesLeft -= 2;
4923 Offset += 2;
4924 }
4925
4926 if (BytesLeft == 1) {
4927 Value = DAG.getLoad(MVT::i8, Chain,
4928 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4929 DAG.getConstant(Offset, SrcVT)),
4930 NULL, 0);
4931 Chain = Value.getValue(1);
4932 Chain = DAG.getStore(Chain, Value,
4933 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4934 DAG.getConstant(Offset, DstVT)),
4935 NULL, 0);
4936 }
4937 }
4938
4939 return Chain;
4940}
4941
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004942/// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4943SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004944 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004945 SDOperand TheChain = N->getOperand(0);
4946 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004947 if (Subtarget->is64Bit()) {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004948 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4949 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4950 MVT::i64, rax.getValue(2));
4951 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004952 DAG.getConstant(32, MVT::i8));
4953 SDOperand Ops[] = {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004954 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004955 };
4956
4957 Tys = DAG.getVTList(MVT::i64, MVT::Other);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004958 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004959 }
4960
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004961 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4962 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4963 MVT::i32, eax.getValue(2));
4964 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4965 SDOperand Ops[] = { eax, edx };
4966 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4967
4968 // Use a MERGE_VALUES to return the value and chain.
4969 Ops[1] = edx.getValue(1);
4970 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4971 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004972}
4973
4974SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4975 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
4976
4977 if (!Subtarget->is64Bit()) {
4978 // vastart just stores the address of the VarArgsFrameIndex slot into the
4979 // memory location argument.
4980 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4981 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
4982 SV->getOffset());
4983 }
4984
4985 // __va_list_tag:
4986 // gp_offset (0 - 6 * 8)
4987 // fp_offset (48 - 48 + 8 * 16)
4988 // overflow_arg_area (point to parameters coming in memory).
4989 // reg_save_area
4990 SmallVector<SDOperand, 8> MemOps;
4991 SDOperand FIN = Op.getOperand(1);
4992 // Store gp_offset
4993 SDOperand Store = DAG.getStore(Op.getOperand(0),
4994 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4995 FIN, SV->getValue(), SV->getOffset());
4996 MemOps.push_back(Store);
4997
4998 // Store fp_offset
4999 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5000 DAG.getConstant(4, getPointerTy()));
5001 Store = DAG.getStore(Op.getOperand(0),
5002 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5003 FIN, SV->getValue(), SV->getOffset());
5004 MemOps.push_back(Store);
5005
5006 // Store ptr to overflow_arg_area
5007 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5008 DAG.getConstant(4, getPointerTy()));
5009 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5010 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
5011 SV->getOffset());
5012 MemOps.push_back(Store);
5013
5014 // Store ptr to reg_save_area.
5015 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5016 DAG.getConstant(8, getPointerTy()));
5017 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5018 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
5019 SV->getOffset());
5020 MemOps.push_back(Store);
5021 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5022}
5023
5024SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
5025 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5026 SDOperand Chain = Op.getOperand(0);
5027 SDOperand DstPtr = Op.getOperand(1);
5028 SDOperand SrcPtr = Op.getOperand(2);
5029 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
5030 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
5031
5032 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
5033 SrcSV->getValue(), SrcSV->getOffset());
5034 Chain = SrcPtr.getValue(1);
5035 for (unsigned i = 0; i < 3; ++i) {
5036 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
5037 SrcSV->getValue(), SrcSV->getOffset());
5038 Chain = Val.getValue(1);
5039 Chain = DAG.getStore(Chain, Val, DstPtr,
5040 DstSV->getValue(), DstSV->getOffset());
5041 if (i == 2)
5042 break;
5043 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
5044 DAG.getConstant(8, getPointerTy()));
5045 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
5046 DAG.getConstant(8, getPointerTy()));
5047 }
5048 return Chain;
5049}
5050
5051SDOperand
5052X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5053 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5054 switch (IntNo) {
5055 default: return SDOperand(); // Don't custom lower most intrinsics.
5056 // Comparison intrinsics.
5057 case Intrinsic::x86_sse_comieq_ss:
5058 case Intrinsic::x86_sse_comilt_ss:
5059 case Intrinsic::x86_sse_comile_ss:
5060 case Intrinsic::x86_sse_comigt_ss:
5061 case Intrinsic::x86_sse_comige_ss:
5062 case Intrinsic::x86_sse_comineq_ss:
5063 case Intrinsic::x86_sse_ucomieq_ss:
5064 case Intrinsic::x86_sse_ucomilt_ss:
5065 case Intrinsic::x86_sse_ucomile_ss:
5066 case Intrinsic::x86_sse_ucomigt_ss:
5067 case Intrinsic::x86_sse_ucomige_ss:
5068 case Intrinsic::x86_sse_ucomineq_ss:
5069 case Intrinsic::x86_sse2_comieq_sd:
5070 case Intrinsic::x86_sse2_comilt_sd:
5071 case Intrinsic::x86_sse2_comile_sd:
5072 case Intrinsic::x86_sse2_comigt_sd:
5073 case Intrinsic::x86_sse2_comige_sd:
5074 case Intrinsic::x86_sse2_comineq_sd:
5075 case Intrinsic::x86_sse2_ucomieq_sd:
5076 case Intrinsic::x86_sse2_ucomilt_sd:
5077 case Intrinsic::x86_sse2_ucomile_sd:
5078 case Intrinsic::x86_sse2_ucomigt_sd:
5079 case Intrinsic::x86_sse2_ucomige_sd:
5080 case Intrinsic::x86_sse2_ucomineq_sd: {
5081 unsigned Opc = 0;
5082 ISD::CondCode CC = ISD::SETCC_INVALID;
5083 switch (IntNo) {
5084 default: break;
5085 case Intrinsic::x86_sse_comieq_ss:
5086 case Intrinsic::x86_sse2_comieq_sd:
5087 Opc = X86ISD::COMI;
5088 CC = ISD::SETEQ;
5089 break;
5090 case Intrinsic::x86_sse_comilt_ss:
5091 case Intrinsic::x86_sse2_comilt_sd:
5092 Opc = X86ISD::COMI;
5093 CC = ISD::SETLT;
5094 break;
5095 case Intrinsic::x86_sse_comile_ss:
5096 case Intrinsic::x86_sse2_comile_sd:
5097 Opc = X86ISD::COMI;
5098 CC = ISD::SETLE;
5099 break;
5100 case Intrinsic::x86_sse_comigt_ss:
5101 case Intrinsic::x86_sse2_comigt_sd:
5102 Opc = X86ISD::COMI;
5103 CC = ISD::SETGT;
5104 break;
5105 case Intrinsic::x86_sse_comige_ss:
5106 case Intrinsic::x86_sse2_comige_sd:
5107 Opc = X86ISD::COMI;
5108 CC = ISD::SETGE;
5109 break;
5110 case Intrinsic::x86_sse_comineq_ss:
5111 case Intrinsic::x86_sse2_comineq_sd:
5112 Opc = X86ISD::COMI;
5113 CC = ISD::SETNE;
5114 break;
5115 case Intrinsic::x86_sse_ucomieq_ss:
5116 case Intrinsic::x86_sse2_ucomieq_sd:
5117 Opc = X86ISD::UCOMI;
5118 CC = ISD::SETEQ;
5119 break;
5120 case Intrinsic::x86_sse_ucomilt_ss:
5121 case Intrinsic::x86_sse2_ucomilt_sd:
5122 Opc = X86ISD::UCOMI;
5123 CC = ISD::SETLT;
5124 break;
5125 case Intrinsic::x86_sse_ucomile_ss:
5126 case Intrinsic::x86_sse2_ucomile_sd:
5127 Opc = X86ISD::UCOMI;
5128 CC = ISD::SETLE;
5129 break;
5130 case Intrinsic::x86_sse_ucomigt_ss:
5131 case Intrinsic::x86_sse2_ucomigt_sd:
5132 Opc = X86ISD::UCOMI;
5133 CC = ISD::SETGT;
5134 break;
5135 case Intrinsic::x86_sse_ucomige_ss:
5136 case Intrinsic::x86_sse2_ucomige_sd:
5137 Opc = X86ISD::UCOMI;
5138 CC = ISD::SETGE;
5139 break;
5140 case Intrinsic::x86_sse_ucomineq_ss:
5141 case Intrinsic::x86_sse2_ucomineq_sd:
5142 Opc = X86ISD::UCOMI;
5143 CC = ISD::SETNE;
5144 break;
5145 }
5146
5147 unsigned X86CC;
5148 SDOperand LHS = Op.getOperand(1);
5149 SDOperand RHS = Op.getOperand(2);
5150 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5151
Evan Cheng621216e2007-09-29 00:00:36 +00005152 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5153 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5154 DAG.getConstant(X86CC, MVT::i8), Cond);
5155 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005156 }
5157 }
5158}
5159
5160SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5161 // Depths > 0 not supported yet!
5162 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5163 return SDOperand();
5164
5165 // Just load the return address
5166 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5167 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5168}
5169
5170SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5171 // Depths > 0 not supported yet!
5172 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5173 return SDOperand();
5174
5175 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5176 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5177 DAG.getConstant(4, getPointerTy()));
5178}
5179
5180SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5181 SelectionDAG &DAG) {
5182 // Is not yet supported on x86-64
5183 if (Subtarget->is64Bit())
5184 return SDOperand();
5185
5186 return DAG.getConstant(8, getPointerTy());
5187}
5188
5189SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5190{
5191 assert(!Subtarget->is64Bit() &&
5192 "Lowering of eh_return builtin is not supported yet on x86-64");
5193
5194 MachineFunction &MF = DAG.getMachineFunction();
5195 SDOperand Chain = Op.getOperand(0);
5196 SDOperand Offset = Op.getOperand(1);
5197 SDOperand Handler = Op.getOperand(2);
5198
5199 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5200 getPointerTy());
5201
5202 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5203 DAG.getConstant(-4UL, getPointerTy()));
5204 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5205 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5206 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5207 MF.addLiveOut(X86::ECX);
5208
5209 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5210 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5211}
5212
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005213SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5214 SelectionDAG &DAG) {
5215 SDOperand Root = Op.getOperand(0);
5216 SDOperand Trmp = Op.getOperand(1); // trampoline
5217 SDOperand FPtr = Op.getOperand(2); // nested function
5218 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5219
5220 SrcValueSDNode *TrmpSV = cast<SrcValueSDNode>(Op.getOperand(4));
5221
5222 if (Subtarget->is64Bit()) {
5223 return SDOperand(); // not yet supported
5224 } else {
5225 Function *Func = (Function *)
5226 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5227 unsigned CC = Func->getCallingConv();
Duncan Sands466eadd2007-08-29 19:01:20 +00005228 unsigned NestReg;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005229
5230 switch (CC) {
5231 default:
5232 assert(0 && "Unsupported calling convention");
5233 case CallingConv::C:
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005234 case CallingConv::X86_StdCall: {
5235 // Pass 'nest' parameter in ECX.
5236 // Must be kept in sync with X86CallingConv.td
Duncan Sands466eadd2007-08-29 19:01:20 +00005237 NestReg = X86::ECX;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005238
5239 // Check that ECX wasn't needed by an 'inreg' parameter.
5240 const FunctionType *FTy = Func->getFunctionType();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00005241 const ParamAttrsList *Attrs = Func->getParamAttrs();
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005242
5243 if (Attrs && !Func->isVarArg()) {
5244 unsigned InRegCount = 0;
5245 unsigned Idx = 1;
5246
5247 for (FunctionType::param_iterator I = FTy->param_begin(),
5248 E = FTy->param_end(); I != E; ++I, ++Idx)
5249 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5250 // FIXME: should only count parameters that are lowered to integers.
5251 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5252
5253 if (InRegCount > 2) {
5254 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5255 abort();
5256 }
5257 }
5258 break;
5259 }
5260 case CallingConv::X86_FastCall:
5261 // Pass 'nest' parameter in EAX.
5262 // Must be kept in sync with X86CallingConv.td
Duncan Sands466eadd2007-08-29 19:01:20 +00005263 NestReg = X86::EAX;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005264 break;
5265 }
5266
Duncan Sands466eadd2007-08-29 19:01:20 +00005267 const X86InstrInfo *TII =
5268 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5269
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005270 SDOperand OutChains[4];
5271 SDOperand Addr, Disp;
5272
5273 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5274 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5275
Duncan Sands466eadd2007-08-29 19:01:20 +00005276 unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5277 unsigned char N86Reg = ((X86RegisterInfo&)RegInfo).getX86RegNum(NestReg);
5278 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005279 Trmp, TrmpSV->getValue(), TrmpSV->getOffset());
5280
5281 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5282 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpSV->getValue(),
5283 TrmpSV->getOffset() + 1, false, 1);
5284
Duncan Sands466eadd2007-08-29 19:01:20 +00005285 unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005286 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5287 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5288 TrmpSV->getValue() + 5, TrmpSV->getOffset());
5289
5290 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5291 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpSV->getValue(),
5292 TrmpSV->getOffset() + 6, false, 1);
5293
Duncan Sands7407a9f2007-09-11 14:10:23 +00005294 SDOperand Ops[] =
5295 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5296 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005297 }
5298}
5299
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +00005300SDOperand X86TargetLowering::LowerFLT_ROUNDS(SDOperand Op, SelectionDAG &DAG) {
5301 /*
5302 The rounding mode is in bits 11:10 of FPSR, and has the following
5303 settings:
5304 00 Round to nearest
5305 01 Round to -inf
5306 10 Round to +inf
5307 11 Round to 0
5308
5309 FLT_ROUNDS, on the other hand, expects the following:
5310 -1 Undefined
5311 0 Round to 0
5312 1 Round to nearest
5313 2 Round to +inf
5314 3 Round to -inf
5315
5316 To perform the conversion, we do:
5317 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5318 */
5319
5320 MachineFunction &MF = DAG.getMachineFunction();
5321 const TargetMachine &TM = MF.getTarget();
5322 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5323 unsigned StackAlignment = TFI.getStackAlignment();
5324 MVT::ValueType VT = Op.getValueType();
5325
5326 // Save FP Control Word to stack slot
5327 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5328 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5329
5330 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5331 DAG.getEntryNode(), StackSlot);
5332
5333 // Load FP Control Word from stack slot
5334 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5335
5336 // Transform as necessary
5337 SDOperand CWD1 =
5338 DAG.getNode(ISD::SRL, MVT::i16,
5339 DAG.getNode(ISD::AND, MVT::i16,
5340 CWD, DAG.getConstant(0x800, MVT::i16)),
5341 DAG.getConstant(11, MVT::i8));
5342 SDOperand CWD2 =
5343 DAG.getNode(ISD::SRL, MVT::i16,
5344 DAG.getNode(ISD::AND, MVT::i16,
5345 CWD, DAG.getConstant(0x400, MVT::i16)),
5346 DAG.getConstant(9, MVT::i8));
5347
5348 SDOperand RetVal =
5349 DAG.getNode(ISD::AND, MVT::i16,
5350 DAG.getNode(ISD::ADD, MVT::i16,
5351 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5352 DAG.getConstant(1, MVT::i16)),
5353 DAG.getConstant(3, MVT::i16));
5354
5355
5356 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5357 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5358}
5359
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005360/// LowerOperation - Provide custom lowering hooks for some operations.
5361///
5362SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5363 switch (Op.getOpcode()) {
5364 default: assert(0 && "Should not custom lower this!");
5365 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5366 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5367 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5368 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5369 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5370 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5371 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5372 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5373 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5374 case ISD::SHL_PARTS:
5375 case ISD::SRA_PARTS:
5376 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5377 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5378 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5379 case ISD::FABS: return LowerFABS(Op, DAG);
5380 case ISD::FNEG: return LowerFNEG(Op, DAG);
5381 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
Evan Cheng621216e2007-09-29 00:00:36 +00005382 case ISD::SETCC: return LowerSETCC(Op, DAG);
5383 case ISD::SELECT: return LowerSELECT(Op, DAG);
5384 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005385 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5386 case ISD::CALL: return LowerCALL(Op, DAG);
5387 case ISD::RET: return LowerRET(Op, DAG);
5388 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5389 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5390 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005391 case ISD::VASTART: return LowerVASTART(Op, DAG);
5392 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5393 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5394 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5395 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5396 case ISD::FRAME_TO_ARGS_OFFSET:
5397 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5398 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5399 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005400 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +00005401 case ISD::FLT_ROUNDS: return LowerFLT_ROUNDS(Op, DAG);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005402
5403
5404 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5405 case ISD::READCYCLECOUNTER:
5406 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005407 }
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005408}
5409
5410/// ExpandOperation - Provide custom lowering hooks for expanding operations.
5411SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5412 switch (N->getOpcode()) {
5413 default: assert(0 && "Should not custom lower this!");
5414 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5415 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5416 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005417}
5418
5419const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5420 switch (Opcode) {
5421 default: return NULL;
5422 case X86ISD::SHLD: return "X86ISD::SHLD";
5423 case X86ISD::SHRD: return "X86ISD::SHRD";
5424 case X86ISD::FAND: return "X86ISD::FAND";
5425 case X86ISD::FOR: return "X86ISD::FOR";
5426 case X86ISD::FXOR: return "X86ISD::FXOR";
5427 case X86ISD::FSRL: return "X86ISD::FSRL";
5428 case X86ISD::FILD: return "X86ISD::FILD";
5429 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5430 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5431 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5432 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5433 case X86ISD::FLD: return "X86ISD::FLD";
5434 case X86ISD::FST: return "X86ISD::FST";
5435 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5436 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5437 case X86ISD::CALL: return "X86ISD::CALL";
5438 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5439 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5440 case X86ISD::CMP: return "X86ISD::CMP";
5441 case X86ISD::COMI: return "X86ISD::COMI";
5442 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5443 case X86ISD::SETCC: return "X86ISD::SETCC";
5444 case X86ISD::CMOV: return "X86ISD::CMOV";
5445 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5446 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5447 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5448 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005449 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5450 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5451 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5452 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5453 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5454 case X86ISD::FMAX: return "X86ISD::FMAX";
5455 case X86ISD::FMIN: return "X86ISD::FMIN";
5456 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5457 case X86ISD::FRCP: return "X86ISD::FRCP";
5458 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5459 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5460 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00005461 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +00005462 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005463 }
5464}
5465
5466// isLegalAddressingMode - Return true if the addressing mode represented
5467// by AM is legal for this target, for a load/store of the specified type.
5468bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5469 const Type *Ty) const {
5470 // X86 supports extremely general addressing modes.
5471
5472 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5473 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5474 return false;
5475
5476 if (AM.BaseGV) {
Evan Cheng6a1f3f12007-08-01 23:46:47 +00005477 // We can only fold this if we don't need an extra load.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005478 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5479 return false;
Evan Cheng6a1f3f12007-08-01 23:46:47 +00005480
5481 // X86-64 only supports addr of globals in small code model.
5482 if (Subtarget->is64Bit()) {
5483 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5484 return false;
5485 // If lower 4G is not available, then we must use rip-relative addressing.
5486 if (AM.BaseOffs || AM.Scale > 1)
5487 return false;
5488 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005489 }
5490
5491 switch (AM.Scale) {
5492 case 0:
5493 case 1:
5494 case 2:
5495 case 4:
5496 case 8:
5497 // These scales always work.
5498 break;
5499 case 3:
5500 case 5:
5501 case 9:
5502 // These scales are formed with basereg+scalereg. Only accept if there is
5503 // no basereg yet.
5504 if (AM.HasBaseReg)
5505 return false;
5506 break;
5507 default: // Other stuff never works.
5508 return false;
5509 }
5510
5511 return true;
5512}
5513
5514
Evan Cheng27a820a2007-10-26 01:56:11 +00005515bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5516 if (!Ty1->isInteger() || !Ty2->isInteger())
5517 return false;
Evan Cheng7f152602007-10-29 07:57:50 +00005518 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5519 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5520 if (NumBits1 <= NumBits2)
5521 return false;
5522 return Subtarget->is64Bit() || NumBits1 < 64;
Evan Cheng27a820a2007-10-26 01:56:11 +00005523}
5524
Evan Cheng9decb332007-10-29 19:58:20 +00005525bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5526 MVT::ValueType VT2) const {
5527 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5528 return false;
5529 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5530 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5531 if (NumBits1 <= NumBits2)
5532 return false;
5533 return Subtarget->is64Bit() || NumBits1 < 64;
5534}
Evan Cheng27a820a2007-10-26 01:56:11 +00005535
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005536/// isShuffleMaskLegal - Targets can use this to indicate that they only
5537/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5538/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5539/// are assumed to be legal.
5540bool
5541X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5542 // Only do shuffles on 128-bit vector types for now.
5543 if (MVT::getSizeInBits(VT) == 64) return false;
5544 return (Mask.Val->getNumOperands() <= 4 ||
5545 isIdentityMask(Mask.Val) ||
5546 isIdentityMask(Mask.Val, true) ||
5547 isSplatMask(Mask.Val) ||
5548 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5549 X86::isUNPCKLMask(Mask.Val) ||
5550 X86::isUNPCKHMask(Mask.Val) ||
5551 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5552 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5553}
5554
5555bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5556 MVT::ValueType EVT,
5557 SelectionDAG &DAG) const {
5558 unsigned NumElts = BVOps.size();
5559 // Only do shuffles on 128-bit vector types for now.
5560 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5561 if (NumElts == 2) return true;
5562 if (NumElts == 4) {
5563 return (isMOVLMask(&BVOps[0], 4) ||
5564 isCommutedMOVL(&BVOps[0], 4, true) ||
5565 isSHUFPMask(&BVOps[0], 4) ||
5566 isCommutedSHUFP(&BVOps[0], 4));
5567 }
5568 return false;
5569}
5570
5571//===----------------------------------------------------------------------===//
5572// X86 Scheduler Hooks
5573//===----------------------------------------------------------------------===//
5574
5575MachineBasicBlock *
5576X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
5577 MachineBasicBlock *BB) {
5578 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5579 switch (MI->getOpcode()) {
5580 default: assert(false && "Unexpected instr type to insert");
5581 case X86::CMOV_FR32:
5582 case X86::CMOV_FR64:
5583 case X86::CMOV_V4F32:
5584 case X86::CMOV_V2F64:
Evan Cheng621216e2007-09-29 00:00:36 +00005585 case X86::CMOV_V2I64: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005586 // To "insert" a SELECT_CC instruction, we actually have to insert the
5587 // diamond control-flow pattern. The incoming instruction knows the
5588 // destination vreg to set, the condition code register to branch on, the
5589 // true/false values to select between, and a branch opcode to use.
5590 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5591 ilist<MachineBasicBlock>::iterator It = BB;
5592 ++It;
5593
5594 // thisMBB:
5595 // ...
5596 // TrueVal = ...
5597 // cmpTY ccX, r1, r2
5598 // bCC copy1MBB
5599 // fallthrough --> copy0MBB
5600 MachineBasicBlock *thisMBB = BB;
5601 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5602 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5603 unsigned Opc =
5604 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5605 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5606 MachineFunction *F = BB->getParent();
5607 F->getBasicBlockList().insert(It, copy0MBB);
5608 F->getBasicBlockList().insert(It, sinkMBB);
5609 // Update machine-CFG edges by first adding all successors of the current
5610 // block to the new block which will contain the Phi node for the select.
5611 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5612 e = BB->succ_end(); i != e; ++i)
5613 sinkMBB->addSuccessor(*i);
5614 // Next, remove all successors of the current block, and add the true
5615 // and fallthrough blocks as its successors.
5616 while(!BB->succ_empty())
5617 BB->removeSuccessor(BB->succ_begin());
5618 BB->addSuccessor(copy0MBB);
5619 BB->addSuccessor(sinkMBB);
5620
5621 // copy0MBB:
5622 // %FalseValue = ...
5623 // # fallthrough to sinkMBB
5624 BB = copy0MBB;
5625
5626 // Update machine-CFG edges
5627 BB->addSuccessor(sinkMBB);
5628
5629 // sinkMBB:
5630 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5631 // ...
5632 BB = sinkMBB;
5633 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5634 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5635 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5636
5637 delete MI; // The pseudo instruction is gone now.
5638 return BB;
5639 }
5640
5641 case X86::FP32_TO_INT16_IN_MEM:
5642 case X86::FP32_TO_INT32_IN_MEM:
5643 case X86::FP32_TO_INT64_IN_MEM:
5644 case X86::FP64_TO_INT16_IN_MEM:
5645 case X86::FP64_TO_INT32_IN_MEM:
Dale Johannesen6d0e36a2007-08-07 01:17:37 +00005646 case X86::FP64_TO_INT64_IN_MEM:
5647 case X86::FP80_TO_INT16_IN_MEM:
5648 case X86::FP80_TO_INT32_IN_MEM:
5649 case X86::FP80_TO_INT64_IN_MEM: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005650 // Change the floating point control register to use "round towards zero"
5651 // mode when truncating to an integer value.
5652 MachineFunction *F = BB->getParent();
5653 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5654 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5655
5656 // Load the old value of the high byte of the control word...
5657 unsigned OldCW =
5658 F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
5659 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5660
5661 // Set the high part to be round to zero...
5662 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5663 .addImm(0xC7F);
5664
5665 // Reload the modified control word now...
5666 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5667
5668 // Restore the memory image of control word to original value
5669 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5670 .addReg(OldCW);
5671
5672 // Get the X86 opcode to use.
5673 unsigned Opc;
5674 switch (MI->getOpcode()) {
5675 default: assert(0 && "illegal opcode!");
5676 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5677 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5678 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5679 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5680 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5681 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
Dale Johannesen6d0e36a2007-08-07 01:17:37 +00005682 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5683 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5684 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005685 }
5686
5687 X86AddressMode AM;
5688 MachineOperand &Op = MI->getOperand(0);
5689 if (Op.isRegister()) {
5690 AM.BaseType = X86AddressMode::RegBase;
5691 AM.Base.Reg = Op.getReg();
5692 } else {
5693 AM.BaseType = X86AddressMode::FrameIndexBase;
5694 AM.Base.FrameIndex = Op.getFrameIndex();
5695 }
5696 Op = MI->getOperand(1);
5697 if (Op.isImmediate())
5698 AM.Scale = Op.getImm();
5699 Op = MI->getOperand(2);
5700 if (Op.isImmediate())
5701 AM.IndexReg = Op.getImm();
5702 Op = MI->getOperand(3);
5703 if (Op.isGlobalAddress()) {
5704 AM.GV = Op.getGlobal();
5705 } else {
5706 AM.Disp = Op.getImm();
5707 }
5708 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5709 .addReg(MI->getOperand(4).getReg());
5710
5711 // Reload the original control word now.
5712 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5713
5714 delete MI; // The pseudo instruction is gone now.
5715 return BB;
5716 }
5717 }
5718}
5719
5720//===----------------------------------------------------------------------===//
5721// X86 Optimization Hooks
5722//===----------------------------------------------------------------------===//
5723
5724void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5725 uint64_t Mask,
5726 uint64_t &KnownZero,
5727 uint64_t &KnownOne,
5728 const SelectionDAG &DAG,
5729 unsigned Depth) const {
5730 unsigned Opc = Op.getOpcode();
5731 assert((Opc >= ISD::BUILTIN_OP_END ||
5732 Opc == ISD::INTRINSIC_WO_CHAIN ||
5733 Opc == ISD::INTRINSIC_W_CHAIN ||
5734 Opc == ISD::INTRINSIC_VOID) &&
5735 "Should use MaskedValueIsZero if you don't know whether Op"
5736 " is a target node!");
5737
5738 KnownZero = KnownOne = 0; // Don't know anything.
5739 switch (Opc) {
5740 default: break;
5741 case X86ISD::SETCC:
5742 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5743 break;
5744 }
5745}
5746
5747/// getShuffleScalarElt - Returns the scalar element that will make up the ith
5748/// element of the result of the vector shuffle.
5749static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5750 MVT::ValueType VT = N->getValueType(0);
5751 SDOperand PermMask = N->getOperand(2);
5752 unsigned NumElems = PermMask.getNumOperands();
5753 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5754 i %= NumElems;
5755 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5756 return (i == 0)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00005757 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005758 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5759 SDOperand Idx = PermMask.getOperand(i);
5760 if (Idx.getOpcode() == ISD::UNDEF)
5761 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5762 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5763 }
5764 return SDOperand();
5765}
5766
5767/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5768/// node is a GlobalAddress + an offset.
5769static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5770 unsigned Opc = N->getOpcode();
5771 if (Opc == X86ISD::Wrapper) {
5772 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5773 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5774 return true;
5775 }
5776 } else if (Opc == ISD::ADD) {
5777 SDOperand N1 = N->getOperand(0);
5778 SDOperand N2 = N->getOperand(1);
5779 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5780 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5781 if (V) {
5782 Offset += V->getSignExtended();
5783 return true;
5784 }
5785 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5786 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5787 if (V) {
5788 Offset += V->getSignExtended();
5789 return true;
5790 }
5791 }
5792 }
5793 return false;
5794}
5795
5796/// isConsecutiveLoad - Returns true if N is loading from an address of Base
5797/// + Dist * Size.
5798static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5799 MachineFrameInfo *MFI) {
5800 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5801 return false;
5802
5803 SDOperand Loc = N->getOperand(1);
5804 SDOperand BaseLoc = Base->getOperand(1);
5805 if (Loc.getOpcode() == ISD::FrameIndex) {
5806 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5807 return false;
Dan Gohman53491e92007-07-23 20:24:29 +00005808 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5809 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005810 int FS = MFI->getObjectSize(FI);
5811 int BFS = MFI->getObjectSize(BFI);
5812 if (FS != BFS || FS != Size) return false;
5813 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5814 } else {
5815 GlobalValue *GV1 = NULL;
5816 GlobalValue *GV2 = NULL;
5817 int64_t Offset1 = 0;
5818 int64_t Offset2 = 0;
5819 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5820 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5821 if (isGA1 && isGA2 && GV1 == GV2)
5822 return Offset1 == (Offset2 + Dist*Size);
5823 }
5824
5825 return false;
5826}
5827
5828static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5829 const X86Subtarget *Subtarget) {
5830 GlobalValue *GV;
5831 int64_t Offset;
5832 if (isGAPlusOffset(Base, GV, Offset))
5833 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5834 else {
5835 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
Dan Gohman53491e92007-07-23 20:24:29 +00005836 int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005837 if (BFI < 0)
5838 // Fixed objects do not specify alignment, however the offsets are known.
5839 return ((Subtarget->getStackAlignment() % 16) == 0 &&
5840 (MFI->getObjectOffset(BFI) % 16) == 0);
5841 else
5842 return MFI->getObjectAlignment(BFI) >= 16;
5843 }
5844 return false;
5845}
5846
5847
5848/// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5849/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5850/// if the load addresses are consecutive, non-overlapping, and in the right
5851/// order.
5852static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5853 const X86Subtarget *Subtarget) {
5854 MachineFunction &MF = DAG.getMachineFunction();
5855 MachineFrameInfo *MFI = MF.getFrameInfo();
5856 MVT::ValueType VT = N->getValueType(0);
5857 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5858 SDOperand PermMask = N->getOperand(2);
5859 int NumElems = (int)PermMask.getNumOperands();
5860 SDNode *Base = NULL;
5861 for (int i = 0; i < NumElems; ++i) {
5862 SDOperand Idx = PermMask.getOperand(i);
5863 if (Idx.getOpcode() == ISD::UNDEF) {
5864 if (!Base) return SDOperand();
5865 } else {
5866 SDOperand Arg =
5867 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5868 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5869 return SDOperand();
5870 if (!Base)
5871 Base = Arg.Val;
5872 else if (!isConsecutiveLoad(Arg.Val, Base,
5873 i, MVT::getSizeInBits(EVT)/8,MFI))
5874 return SDOperand();
5875 }
5876 }
5877
5878 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
Dan Gohman11821702007-07-27 17:16:43 +00005879 LoadSDNode *LD = cast<LoadSDNode>(Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005880 if (isAlign16) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005881 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
Dan Gohman11821702007-07-27 17:16:43 +00005882 LD->getSrcValueOffset(), LD->isVolatile());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005883 } else {
Dan Gohman11821702007-07-27 17:16:43 +00005884 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5885 LD->getSrcValueOffset(), LD->isVolatile(),
5886 LD->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005887 }
5888}
5889
5890/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5891static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5892 const X86Subtarget *Subtarget) {
5893 SDOperand Cond = N->getOperand(0);
5894
5895 // If we have SSE[12] support, try to form min/max nodes.
5896 if (Subtarget->hasSSE2() &&
5897 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5898 if (Cond.getOpcode() == ISD::SETCC) {
5899 // Get the LHS/RHS of the select.
5900 SDOperand LHS = N->getOperand(1);
5901 SDOperand RHS = N->getOperand(2);
5902 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5903
5904 unsigned Opcode = 0;
5905 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5906 switch (CC) {
5907 default: break;
5908 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5909 case ISD::SETULE:
5910 case ISD::SETLE:
5911 if (!UnsafeFPMath) break;
5912 // FALL THROUGH.
5913 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
5914 case ISD::SETLT:
5915 Opcode = X86ISD::FMIN;
5916 break;
5917
5918 case ISD::SETOGT: // (X > Y) ? X : Y -> max
5919 case ISD::SETUGT:
5920 case ISD::SETGT:
5921 if (!UnsafeFPMath) break;
5922 // FALL THROUGH.
5923 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
5924 case ISD::SETGE:
5925 Opcode = X86ISD::FMAX;
5926 break;
5927 }
5928 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5929 switch (CC) {
5930 default: break;
5931 case ISD::SETOGT: // (X > Y) ? Y : X -> min
5932 case ISD::SETUGT:
5933 case ISD::SETGT:
5934 if (!UnsafeFPMath) break;
5935 // FALL THROUGH.
5936 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
5937 case ISD::SETGE:
5938 Opcode = X86ISD::FMIN;
5939 break;
5940
5941 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
5942 case ISD::SETULE:
5943 case ISD::SETLE:
5944 if (!UnsafeFPMath) break;
5945 // FALL THROUGH.
5946 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
5947 case ISD::SETLT:
5948 Opcode = X86ISD::FMAX;
5949 break;
5950 }
5951 }
5952
5953 if (Opcode)
5954 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5955 }
5956
5957 }
5958
5959 return SDOperand();
5960}
5961
5962
5963SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5964 DAGCombinerInfo &DCI) const {
5965 SelectionDAG &DAG = DCI.DAG;
5966 switch (N->getOpcode()) {
5967 default: break;
5968 case ISD::VECTOR_SHUFFLE:
5969 return PerformShuffleCombine(N, DAG, Subtarget);
5970 case ISD::SELECT:
5971 return PerformSELECTCombine(N, DAG, Subtarget);
5972 }
5973
5974 return SDOperand();
5975}
5976
5977//===----------------------------------------------------------------------===//
5978// X86 Inline Assembly Support
5979//===----------------------------------------------------------------------===//
5980
5981/// getConstraintType - Given a constraint letter, return the type of
5982/// constraint it is for this target.
5983X86TargetLowering::ConstraintType
5984X86TargetLowering::getConstraintType(const std::string &Constraint) const {
5985 if (Constraint.size() == 1) {
5986 switch (Constraint[0]) {
5987 case 'A':
5988 case 'r':
5989 case 'R':
5990 case 'l':
5991 case 'q':
5992 case 'Q':
5993 case 'x':
5994 case 'Y':
5995 return C_RegisterClass;
5996 default:
5997 break;
5998 }
5999 }
6000 return TargetLowering::getConstraintType(Constraint);
6001}
6002
Chris Lattnera531abc2007-08-25 00:47:38 +00006003/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6004/// vector. If it is invalid, don't add anything to Ops.
6005void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6006 char Constraint,
6007 std::vector<SDOperand>&Ops,
6008 SelectionDAG &DAG) {
6009 SDOperand Result(0, 0);
6010
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006011 switch (Constraint) {
6012 default: break;
6013 case 'I':
6014 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
Chris Lattnera531abc2007-08-25 00:47:38 +00006015 if (C->getValue() <= 31) {
6016 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6017 break;
6018 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006019 }
Chris Lattnera531abc2007-08-25 00:47:38 +00006020 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006021 case 'N':
6022 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
Chris Lattnera531abc2007-08-25 00:47:38 +00006023 if (C->getValue() <= 255) {
6024 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6025 break;
6026 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006027 }
Chris Lattnera531abc2007-08-25 00:47:38 +00006028 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006029 case 'i': {
6030 // Literal immediates are always ok.
Chris Lattnera531abc2007-08-25 00:47:38 +00006031 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6032 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6033 break;
6034 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006035
6036 // If we are in non-pic codegen mode, we allow the address of a global (with
6037 // an optional displacement) to be used with 'i'.
6038 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6039 int64_t Offset = 0;
6040
6041 // Match either (GA) or (GA+C)
6042 if (GA) {
6043 Offset = GA->getOffset();
6044 } else if (Op.getOpcode() == ISD::ADD) {
6045 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6046 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6047 if (C && GA) {
6048 Offset = GA->getOffset()+C->getValue();
6049 } else {
6050 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6051 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6052 if (C && GA)
6053 Offset = GA->getOffset()+C->getValue();
6054 else
6055 C = 0, GA = 0;
6056 }
6057 }
6058
6059 if (GA) {
6060 // If addressing this global requires a load (e.g. in PIC mode), we can't
6061 // match.
6062 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6063 false))
Chris Lattnera531abc2007-08-25 00:47:38 +00006064 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006065
6066 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6067 Offset);
Chris Lattnera531abc2007-08-25 00:47:38 +00006068 Result = Op;
6069 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006070 }
6071
6072 // Otherwise, not valid for this mode.
Chris Lattnera531abc2007-08-25 00:47:38 +00006073 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006074 }
6075 }
Chris Lattnera531abc2007-08-25 00:47:38 +00006076
6077 if (Result.Val) {
6078 Ops.push_back(Result);
6079 return;
6080 }
6081 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006082}
6083
6084std::vector<unsigned> X86TargetLowering::
6085getRegClassForInlineAsmConstraint(const std::string &Constraint,
6086 MVT::ValueType VT) const {
6087 if (Constraint.size() == 1) {
6088 // FIXME: not handling fp-stack yet!
6089 switch (Constraint[0]) { // GCC X86 Constraint Letters
6090 default: break; // Unknown constraint letter
6091 case 'A': // EAX/EDX
6092 if (VT == MVT::i32 || VT == MVT::i64)
6093 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6094 break;
6095 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6096 case 'Q': // Q_REGS
6097 if (VT == MVT::i32)
6098 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6099 else if (VT == MVT::i16)
6100 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6101 else if (VT == MVT::i8)
Evan Chengf85c10f2007-08-13 23:27:11 +00006102 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
Chris Lattner35032592007-11-04 06:51:12 +00006103 else if (VT == MVT::i64)
6104 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6105 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006106 }
6107 }
6108
6109 return std::vector<unsigned>();
6110}
6111
6112std::pair<unsigned, const TargetRegisterClass*>
6113X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6114 MVT::ValueType VT) const {
6115 // First, see if this is a constraint that directly corresponds to an LLVM
6116 // register class.
6117 if (Constraint.size() == 1) {
6118 // GCC Constraint Letters
6119 switch (Constraint[0]) {
6120 default: break;
6121 case 'r': // GENERAL_REGS
6122 case 'R': // LEGACY_REGS
6123 case 'l': // INDEX_REGS
6124 if (VT == MVT::i64 && Subtarget->is64Bit())
6125 return std::make_pair(0U, X86::GR64RegisterClass);
6126 if (VT == MVT::i32)
6127 return std::make_pair(0U, X86::GR32RegisterClass);
6128 else if (VT == MVT::i16)
6129 return std::make_pair(0U, X86::GR16RegisterClass);
6130 else if (VT == MVT::i8)
6131 return std::make_pair(0U, X86::GR8RegisterClass);
6132 break;
6133 case 'y': // MMX_REGS if MMX allowed.
6134 if (!Subtarget->hasMMX()) break;
6135 return std::make_pair(0U, X86::VR64RegisterClass);
6136 break;
6137 case 'Y': // SSE_REGS if SSE2 allowed
6138 if (!Subtarget->hasSSE2()) break;
6139 // FALL THROUGH.
6140 case 'x': // SSE_REGS if SSE1 allowed
6141 if (!Subtarget->hasSSE1()) break;
6142
6143 switch (VT) {
6144 default: break;
6145 // Scalar SSE types.
6146 case MVT::f32:
6147 case MVT::i32:
6148 return std::make_pair(0U, X86::FR32RegisterClass);
6149 case MVT::f64:
6150 case MVT::i64:
6151 return std::make_pair(0U, X86::FR64RegisterClass);
6152 // Vector types.
6153 case MVT::v16i8:
6154 case MVT::v8i16:
6155 case MVT::v4i32:
6156 case MVT::v2i64:
6157 case MVT::v4f32:
6158 case MVT::v2f64:
6159 return std::make_pair(0U, X86::VR128RegisterClass);
6160 }
6161 break;
6162 }
6163 }
6164
6165 // Use the default implementation in TargetLowering to convert the register
6166 // constraint into a member of a register class.
6167 std::pair<unsigned, const TargetRegisterClass*> Res;
6168 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6169
6170 // Not found as a standard register?
6171 if (Res.second == 0) {
6172 // GCC calls "st(0)" just plain "st".
6173 if (StringsEqualNoCase("{st}", Constraint)) {
6174 Res.first = X86::ST0;
Chris Lattner3cfe51b2007-09-24 05:27:37 +00006175 Res.second = X86::RFP80RegisterClass;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006176 }
6177
6178 return Res;
6179 }
6180
6181 // Otherwise, check to see if this is a register class of the wrong value
6182 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6183 // turn into {ax},{dx}.
6184 if (Res.second->hasType(VT))
6185 return Res; // Correct type already, nothing to do.
6186
6187 // All of the single-register GCC register classes map their values onto
6188 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6189 // really want an 8-bit or 32-bit register, map to the appropriate register
6190 // class and return the appropriate register.
6191 if (Res.second != X86::GR16RegisterClass)
6192 return Res;
6193
6194 if (VT == MVT::i8) {
6195 unsigned DestReg = 0;
6196 switch (Res.first) {
6197 default: break;
6198 case X86::AX: DestReg = X86::AL; break;
6199 case X86::DX: DestReg = X86::DL; break;
6200 case X86::CX: DestReg = X86::CL; break;
6201 case X86::BX: DestReg = X86::BL; break;
6202 }
6203 if (DestReg) {
6204 Res.first = DestReg;
6205 Res.second = Res.second = X86::GR8RegisterClass;
6206 }
6207 } else if (VT == MVT::i32) {
6208 unsigned DestReg = 0;
6209 switch (Res.first) {
6210 default: break;
6211 case X86::AX: DestReg = X86::EAX; break;
6212 case X86::DX: DestReg = X86::EDX; break;
6213 case X86::CX: DestReg = X86::ECX; break;
6214 case X86::BX: DestReg = X86::EBX; break;
6215 case X86::SI: DestReg = X86::ESI; break;
6216 case X86::DI: DestReg = X86::EDI; break;
6217 case X86::BP: DestReg = X86::EBP; break;
6218 case X86::SP: DestReg = X86::ESP; break;
6219 }
6220 if (DestReg) {
6221 Res.first = DestReg;
6222 Res.second = Res.second = X86::GR32RegisterClass;
6223 }
6224 } else if (VT == MVT::i64) {
6225 unsigned DestReg = 0;
6226 switch (Res.first) {
6227 default: break;
6228 case X86::AX: DestReg = X86::RAX; break;
6229 case X86::DX: DestReg = X86::RDX; break;
6230 case X86::CX: DestReg = X86::RCX; break;
6231 case X86::BX: DestReg = X86::RBX; break;
6232 case X86::SI: DestReg = X86::RSI; break;
6233 case X86::DI: DestReg = X86::RDI; break;
6234 case X86::BP: DestReg = X86::RBP; break;
6235 case X86::SP: DestReg = X86::RSP; break;
6236 }
6237 if (DestReg) {
6238 Res.first = DestReg;
6239 Res.second = Res.second = X86::GR64RegisterClass;
6240 }
6241 }
6242
6243 return Res;
6244}