blob: a25710ba5aaba8d38c43f80c9c5ef4089d1b7ab8 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that X86 uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#include "X86.h"
16#include "X86InstrBuilder.h"
17#include "X86ISelLowering.h"
18#include "X86MachineFunctionInfo.h"
19#include "X86TargetMachine.h"
20#include "llvm/CallingConv.h"
21#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/Function.h"
25#include "llvm/Intrinsics.h"
26#include "llvm/ADT/VectorExtras.h"
27#include "llvm/Analysis/ScalarEvolutionExpressions.h"
28#include "llvm/CodeGen/CallingConvLower.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
32#include "llvm/CodeGen/SelectionDAG.h"
33#include "llvm/CodeGen/SSARegMap.h"
34#include "llvm/Support/MathExtras.h"
35#include "llvm/Target/TargetOptions.h"
36#include "llvm/ADT/StringExtras.h"
37using namespace llvm;
38
39X86TargetLowering::X86TargetLowering(TargetMachine &TM)
40 : TargetLowering(TM) {
41 Subtarget = &TM.getSubtarget<X86Subtarget>();
42 X86ScalarSSE = Subtarget->hasSSE2();
43 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
44
45 RegInfo = TM.getRegisterInfo();
46
47 // Set up the TargetLowering object.
48
49 // X86 is weird, it always uses i8 for shift amounts and setcc results.
50 setShiftAmountType(MVT::i8);
51 setSetCCResultType(MVT::i8);
52 setSetCCResultContents(ZeroOrOneSetCCResult);
53 setSchedulingPreference(SchedulingForRegPressure);
54 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
55 setStackPointerRegisterToSaveRestore(X86StackPtr);
56
57 if (Subtarget->isTargetDarwin()) {
58 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
59 setUseUnderscoreSetJmp(false);
60 setUseUnderscoreLongJmp(false);
61 } else if (Subtarget->isTargetMingw()) {
62 // MS runtime is weird: it exports _setjmp, but longjmp!
63 setUseUnderscoreSetJmp(true);
64 setUseUnderscoreLongJmp(false);
65 } else {
66 setUseUnderscoreSetJmp(true);
67 setUseUnderscoreLongJmp(true);
68 }
69
70 // Set up the register classes.
71 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
72 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
73 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
74 if (Subtarget->is64Bit())
75 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
76
77 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
78
79 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
80 // operation.
81 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
82 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
83 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
84
85 if (Subtarget->is64Bit()) {
86 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
87 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
88 } else {
89 if (X86ScalarSSE)
90 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
91 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
92 else
93 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
94 }
95
96 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
97 // this operation.
98 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
99 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
100 // SSE has no i16 to fp conversion, only i32
101 if (X86ScalarSSE)
102 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
103 else {
104 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
105 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
106 }
107
108 if (!Subtarget->is64Bit()) {
109 // Custom lower SINT_TO_FP and FP_TO_SINT from/to i64 in 32-bit mode.
110 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
111 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
112 }
113
114 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
115 // this operation.
116 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
117 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
118
119 if (X86ScalarSSE) {
120 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
121 } else {
122 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
123 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
124 }
125
126 // Handle FP_TO_UINT by promoting the destination to a larger signed
127 // conversion.
128 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
129 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
130 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
131
132 if (Subtarget->is64Bit()) {
133 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
134 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
135 } else {
136 if (X86ScalarSSE && !Subtarget->hasSSE3())
137 // Expand FP_TO_UINT into a select.
138 // FIXME: We would like to use a Custom expander here eventually to do
139 // the optimal thing for SSE vs. the default expansion in the legalizer.
140 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
141 else
142 // With SSE3 we can use fisttpll to convert to a signed i64.
143 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
144 }
145
146 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
147 if (!X86ScalarSSE) {
148 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
149 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
150 }
151
152 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
153 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
154 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
155 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
156 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
157 if (Subtarget->is64Bit())
158 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Expand);
159 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Expand);
160 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
161 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
162 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
163 setOperationAction(ISD::FREM , MVT::f64 , Expand);
164
165 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
166 setOperationAction(ISD::CTTZ , MVT::i8 , Expand);
167 setOperationAction(ISD::CTLZ , MVT::i8 , Expand);
168 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
169 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
170 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
171 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
172 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
173 setOperationAction(ISD::CTLZ , MVT::i32 , Expand);
174 if (Subtarget->is64Bit()) {
175 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
176 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
177 setOperationAction(ISD::CTLZ , MVT::i64 , Expand);
178 }
179
180 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
181 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
182
183 // These should be promoted to a larger select which is supported.
184 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
185 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
186 // X86 wants to expand cmov itself.
187 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
188 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
189 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
190 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
191 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
192 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
193 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
194 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
195 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
196 if (Subtarget->is64Bit()) {
197 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
198 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
199 }
200 // X86 ret instruction may pop stack.
201 setOperationAction(ISD::RET , MVT::Other, Custom);
202 if (!Subtarget->is64Bit())
203 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
204
205 // Darwin ABI issue.
206 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
207 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
208 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
209 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
210 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
211 if (Subtarget->is64Bit()) {
212 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
213 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
214 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
215 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
216 }
217 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
218 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
219 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
220 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
221 // X86 wants to expand memset / memcpy itself.
222 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
223 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
224
225 // We don't have line number support yet.
226 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
227 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
228 // FIXME - use subtarget debug flags
229 if (!Subtarget->isTargetDarwin() &&
230 !Subtarget->isTargetELF() &&
231 !Subtarget->isTargetCygMing())
232 setOperationAction(ISD::LABEL, MVT::Other, Expand);
233
234 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
235 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
236 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
237 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
238 if (Subtarget->is64Bit()) {
239 // FIXME: Verify
240 setExceptionPointerRegister(X86::RAX);
241 setExceptionSelectorRegister(X86::RDX);
242 } else {
243 setExceptionPointerRegister(X86::EAX);
244 setExceptionSelectorRegister(X86::EDX);
245 }
246
247 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
248 setOperationAction(ISD::VASTART , MVT::Other, Custom);
249 setOperationAction(ISD::VAARG , MVT::Other, Expand);
250 setOperationAction(ISD::VAEND , MVT::Other, Expand);
251 if (Subtarget->is64Bit())
252 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
253 else
254 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
255
256 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
257 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
258 if (Subtarget->is64Bit())
259 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
260 if (Subtarget->isTargetCygMing())
261 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
262 else
263 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
264
265 if (X86ScalarSSE) {
266 // Set up the FP register classes.
267 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
268 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
269
270 // Use ANDPD to simulate FABS.
271 setOperationAction(ISD::FABS , MVT::f64, Custom);
272 setOperationAction(ISD::FABS , MVT::f32, Custom);
273
274 // Use XORP to simulate FNEG.
275 setOperationAction(ISD::FNEG , MVT::f64, Custom);
276 setOperationAction(ISD::FNEG , MVT::f32, Custom);
277
278 // Use ANDPD and ORPD to simulate FCOPYSIGN.
279 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
280 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
281
282 // We don't support sin/cos/fmod
283 setOperationAction(ISD::FSIN , MVT::f64, Expand);
284 setOperationAction(ISD::FCOS , MVT::f64, Expand);
285 setOperationAction(ISD::FREM , MVT::f64, Expand);
286 setOperationAction(ISD::FSIN , MVT::f32, Expand);
287 setOperationAction(ISD::FCOS , MVT::f32, Expand);
288 setOperationAction(ISD::FREM , MVT::f32, Expand);
289
290 // Expand FP immediates into loads from the stack, except for the special
291 // cases we handle.
292 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
293 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
294 addLegalFPImmediate(+0.0); // xorps / xorpd
295 } else {
296 // Set up the FP register classes.
297 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
298 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
299
300 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
301 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
302 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
303 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
304 setOperationAction(ISD::FP_ROUND, MVT::f32, Expand);
305
306 if (!UnsafeFPMath) {
307 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
308 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
309 }
310
311 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
312 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
313 addLegalFPImmediate(+0.0); // FLD0
314 addLegalFPImmediate(+1.0); // FLD1
315 addLegalFPImmediate(-0.0); // FLD0/FCHS
316 addLegalFPImmediate(-1.0); // FLD1/FCHS
317 }
318
319 // First set operation action for all vector types to expand. Then we
320 // will selectively turn on ones that can be effectively codegen'd.
321 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
322 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
323 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
324 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
325 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
326 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
327 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
328 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
329 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
330 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
331 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
332 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
333 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
334 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
335 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
336 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
337 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
338 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
339 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
340 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
341 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
342 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
343 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
344 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
345 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
346 }
347
348 if (Subtarget->hasMMX()) {
349 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
350 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
351 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
352 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
353
354 // FIXME: add MMX packed arithmetics
355
356 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
357 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
358 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
359 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
360
361 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
362 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
363 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
364
365 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
366 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
367
368 setOperationAction(ISD::AND, MVT::v8i8, Promote);
369 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
370 setOperationAction(ISD::AND, MVT::v4i16, Promote);
371 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
372 setOperationAction(ISD::AND, MVT::v2i32, Promote);
373 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
374 setOperationAction(ISD::AND, MVT::v1i64, Legal);
375
376 setOperationAction(ISD::OR, MVT::v8i8, Promote);
377 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
378 setOperationAction(ISD::OR, MVT::v4i16, Promote);
379 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
380 setOperationAction(ISD::OR, MVT::v2i32, Promote);
381 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
382 setOperationAction(ISD::OR, MVT::v1i64, Legal);
383
384 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
385 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
386 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
387 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
388 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
389 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
390 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
391
392 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
393 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
394 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
395 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
396 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
397 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
398 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
399
400 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
401 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
402 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
403 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
404
405 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
406 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
407 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
408 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
409
410 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
411 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
412 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
413 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
414 }
415
416 if (Subtarget->hasSSE1()) {
417 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
418
419 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
420 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
421 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
422 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
423 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
424 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
426 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
427 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
428 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
429 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
430 }
431
432 if (Subtarget->hasSSE2()) {
433 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
434 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
435 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
436 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
437 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
438
439 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
440 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
441 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
442 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
443 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
444 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
445 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
446 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
447 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
448 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
449 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
450 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
451 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
452 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
453 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454
455 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
456 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
457 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
458 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
459 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
460 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
461
462 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
463 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
464 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
465 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
466 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
467 }
468 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
469 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
470 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
471 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
472 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
473 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
474
475 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
476 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
477 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
478 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
479 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
480 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
481 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
482 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
483 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
484 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
485 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
486 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
487 }
488
489 // Custom lower v2i64 and v2f64 selects.
490 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
491 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
492 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
493 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
494 }
495
496 // We want to custom lower some of our intrinsics.
497 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
498
499 // We have target-specific dag combine patterns for the following nodes:
500 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
501 setTargetDAGCombine(ISD::SELECT);
502
503 computeRegisterProperties();
504
505 // FIXME: These should be based on subtarget info. Plus, the values should
506 // be smaller when we are in optimizing for size mode.
507 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
508 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
509 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
510 allowUnalignedMemoryAccesses = true; // x86 supports it!
511}
512
513
514//===----------------------------------------------------------------------===//
515// Return Value Calling Convention Implementation
516//===----------------------------------------------------------------------===//
517
518#include "X86GenCallingConv.inc"
519
520/// LowerRET - Lower an ISD::RET node.
521SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
522 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
523
524 SmallVector<CCValAssign, 16> RVLocs;
525 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
526 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
527 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
528 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
529
530
531 // If this is the first return lowered for this function, add the regs to the
532 // liveout set for the function.
533 if (DAG.getMachineFunction().liveout_empty()) {
534 for (unsigned i = 0; i != RVLocs.size(); ++i)
535 if (RVLocs[i].isRegLoc())
536 DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
537 }
538
539 SDOperand Chain = Op.getOperand(0);
540 SDOperand Flag;
541
542 // Copy the result values into the output registers.
543 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
544 RVLocs[0].getLocReg() != X86::ST0) {
545 for (unsigned i = 0; i != RVLocs.size(); ++i) {
546 CCValAssign &VA = RVLocs[i];
547 assert(VA.isRegLoc() && "Can only return in registers!");
548 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
549 Flag);
550 Flag = Chain.getValue(1);
551 }
552 } else {
553 // We need to handle a destination of ST0 specially, because it isn't really
554 // a register.
555 SDOperand Value = Op.getOperand(1);
556
557 // If this is an FP return with ScalarSSE, we need to move the value from
558 // an XMM register onto the fp-stack.
559 if (X86ScalarSSE) {
560 SDOperand MemLoc;
561
562 // If this is a load into a scalarsse value, don't store the loaded value
563 // back to the stack, only to reload it: just replace the scalar-sse load.
564 if (ISD::isNON_EXTLoad(Value.Val) &&
565 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
566 Chain = Value.getOperand(0);
567 MemLoc = Value.getOperand(1);
568 } else {
569 // Spill the value to memory and reload it into top of stack.
570 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
571 MachineFunction &MF = DAG.getMachineFunction();
572 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
573 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
574 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
575 }
576 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
577 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
578 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
579 Chain = Value.getValue(1);
580 }
581
582 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
583 SDOperand Ops[] = { Chain, Value };
584 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
585 Flag = Chain.getValue(1);
586 }
587
588 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
589 if (Flag.Val)
590 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
591 else
592 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
593}
594
595
596/// LowerCallResult - Lower the result values of an ISD::CALL into the
597/// appropriate copies out of appropriate physical registers. This assumes that
598/// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
599/// being lowered. The returns a SDNode with the same number of values as the
600/// ISD::CALL.
601SDNode *X86TargetLowering::
602LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
603 unsigned CallingConv, SelectionDAG &DAG) {
604
605 // Assign locations to each value returned by this call.
606 SmallVector<CCValAssign, 16> RVLocs;
607 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
608 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
609 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
610
611
612 SmallVector<SDOperand, 8> ResultVals;
613
614 // Copy all of the result registers out of their specified physreg.
615 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
616 for (unsigned i = 0; i != RVLocs.size(); ++i) {
617 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
618 RVLocs[i].getValVT(), InFlag).getValue(1);
619 InFlag = Chain.getValue(2);
620 ResultVals.push_back(Chain.getValue(0));
621 }
622 } else {
623 // Copies from the FP stack are special, as ST0 isn't a valid register
624 // before the fp stackifier runs.
625
626 // Copy ST0 into an RFP register with FP_GET_RESULT.
627 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
628 SDOperand GROps[] = { Chain, InFlag };
629 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
630 Chain = RetVal.getValue(1);
631 InFlag = RetVal.getValue(2);
632
633 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
634 // an XMM register.
635 if (X86ScalarSSE) {
636 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
637 // shouldn't be necessary except that RFP cannot be live across
638 // multiple blocks. When stackifier is fixed, they can be uncoupled.
639 MachineFunction &MF = DAG.getMachineFunction();
640 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
641 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
642 SDOperand Ops[] = {
643 Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
644 };
645 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
646 RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
647 Chain = RetVal.getValue(1);
648 }
649 ResultVals.push_back(RetVal);
650 }
651
652 // Merge everything together with a MERGE_VALUES node.
653 ResultVals.push_back(Chain);
654 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
655 &ResultVals[0], ResultVals.size()).Val;
656}
657
658
659//===----------------------------------------------------------------------===//
660// C & StdCall Calling Convention implementation
661//===----------------------------------------------------------------------===//
662// StdCall calling convention seems to be standard for many Windows' API
663// routines and around. It differs from C calling convention just a little:
664// callee should clean up the stack, not caller. Symbols should be also
665// decorated in some fancy way :) It doesn't support any vector arguments.
666
667/// AddLiveIn - This helper function adds the specified physical register to the
668/// MachineFunction as a live in value. It also creates a corresponding virtual
669/// register for it.
670static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
671 const TargetRegisterClass *RC) {
672 assert(RC->contains(PReg) && "Not the correct regclass!");
673 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
674 MF.addLiveIn(PReg, VReg);
675 return VReg;
676}
677
678SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
679 bool isStdCall) {
680 unsigned NumArgs = Op.Val->getNumValues() - 1;
681 MachineFunction &MF = DAG.getMachineFunction();
682 MachineFrameInfo *MFI = MF.getFrameInfo();
683 SDOperand Root = Op.getOperand(0);
684 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
685
686 // Assign locations to all of the incoming arguments.
687 SmallVector<CCValAssign, 16> ArgLocs;
688 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
689 getTargetMachine(), ArgLocs);
690 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
691
692 SmallVector<SDOperand, 8> ArgValues;
693 unsigned LastVal = ~0U;
694 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
695 CCValAssign &VA = ArgLocs[i];
696 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
697 // places.
698 assert(VA.getValNo() != LastVal &&
699 "Don't support value assigned to multiple locs yet");
700 LastVal = VA.getValNo();
701
702 if (VA.isRegLoc()) {
703 MVT::ValueType RegVT = VA.getLocVT();
704 TargetRegisterClass *RC;
705 if (RegVT == MVT::i32)
706 RC = X86::GR32RegisterClass;
707 else {
708 assert(MVT::isVector(RegVT));
709 RC = X86::VR128RegisterClass;
710 }
711
712 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
713 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
714
715 // If this is an 8 or 16-bit value, it is really passed promoted to 32
716 // bits. Insert an assert[sz]ext to capture this, then truncate to the
717 // right size.
718 if (VA.getLocInfo() == CCValAssign::SExt)
719 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
720 DAG.getValueType(VA.getValVT()));
721 else if (VA.getLocInfo() == CCValAssign::ZExt)
722 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
723 DAG.getValueType(VA.getValVT()));
724
725 if (VA.getLocInfo() != CCValAssign::Full)
726 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
727
728 ArgValues.push_back(ArgValue);
729 } else {
730 assert(VA.isMemLoc());
731
732 // Create the nodes corresponding to a load from this parameter slot.
733 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
734 VA.getLocMemOffset());
735 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
736 ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
737 }
738 }
739
740 unsigned StackSize = CCInfo.getNextStackOffset();
741
742 ArgValues.push_back(Root);
743
744 // If the function takes variable number of arguments, make a frame index for
745 // the start of the first vararg value... for expansion of llvm.va_start.
746 if (isVarArg)
747 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
748
749 if (isStdCall && !isVarArg) {
750 BytesToPopOnReturn = StackSize; // Callee pops everything..
751 BytesCallerReserves = 0;
752 } else {
753 BytesToPopOnReturn = 0; // Callee pops nothing.
754
755 // If this is an sret function, the return should pop the hidden pointer.
756 if (NumArgs &&
757 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
758 ISD::ParamFlags::StructReturn))
759 BytesToPopOnReturn = 4;
760
761 BytesCallerReserves = StackSize;
762 }
763
764 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
765 ReturnAddrIndex = 0; // No return address slot generated yet.
766
767 MF.getInfo<X86MachineFunctionInfo>()
768 ->setBytesToPopOnReturn(BytesToPopOnReturn);
769
770 // Return the new list of results.
771 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
772 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
773}
774
775SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
776 unsigned CC) {
777 SDOperand Chain = Op.getOperand(0);
778 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
779 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
780 SDOperand Callee = Op.getOperand(4);
781 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
782
783 // Analyze operands of the call, assigning locations to each operand.
784 SmallVector<CCValAssign, 16> ArgLocs;
785 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
786 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
787
788 // Get a count of how many bytes are to be pushed on the stack.
789 unsigned NumBytes = CCInfo.getNextStackOffset();
790
791 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
792
793 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
794 SmallVector<SDOperand, 8> MemOpChains;
795
796 SDOperand StackPtr;
797
798 // Walk the register/memloc assignments, inserting copies/loads.
799 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
800 CCValAssign &VA = ArgLocs[i];
801 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
802
803 // Promote the value if needed.
804 switch (VA.getLocInfo()) {
805 default: assert(0 && "Unknown loc info!");
806 case CCValAssign::Full: break;
807 case CCValAssign::SExt:
808 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
809 break;
810 case CCValAssign::ZExt:
811 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
812 break;
813 case CCValAssign::AExt:
814 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
815 break;
816 }
817
818 if (VA.isRegLoc()) {
819 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
820 } else {
821 assert(VA.isMemLoc());
822 if (StackPtr.Val == 0)
823 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
824 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
825 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
826 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
827 }
828 }
829
830 // If the first argument is an sret pointer, remember it.
831 bool isSRet = NumOps &&
832 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
833 ISD::ParamFlags::StructReturn);
834
835 if (!MemOpChains.empty())
836 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
837 &MemOpChains[0], MemOpChains.size());
838
839 // Build a sequence of copy-to-reg nodes chained together with token chain
840 // and flag operands which copy the outgoing args into registers.
841 SDOperand InFlag;
842 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
843 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
844 InFlag);
845 InFlag = Chain.getValue(1);
846 }
847
848 // ELF / PIC requires GOT in the EBX register before function calls via PLT
849 // GOT pointer.
850 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
851 Subtarget->isPICStyleGOT()) {
852 Chain = DAG.getCopyToReg(Chain, X86::EBX,
853 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
854 InFlag);
855 InFlag = Chain.getValue(1);
856 }
857
858 // If the callee is a GlobalAddress node (quite common, every direct call is)
859 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
860 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
861 // We should use extra load for direct calls to dllimported functions in
862 // non-JIT mode.
863 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
864 getTargetMachine(), true))
865 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
866 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
867 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
868
869 // Returns a chain & a flag for retval copy to use.
870 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
871 SmallVector<SDOperand, 8> Ops;
872 Ops.push_back(Chain);
873 Ops.push_back(Callee);
874
875 // Add argument registers to the end of the list so that they are known live
876 // into the call.
877 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
878 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
879 RegsToPass[i].second.getValueType()));
880
881 // Add an implicit use GOT pointer in EBX.
882 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
883 Subtarget->isPICStyleGOT())
884 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
885
886 if (InFlag.Val)
887 Ops.push_back(InFlag);
888
889 Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
890 NodeTys, &Ops[0], Ops.size());
891 InFlag = Chain.getValue(1);
892
893 // Create the CALLSEQ_END node.
894 unsigned NumBytesForCalleeToPush = 0;
895
896 if (CC == CallingConv::X86_StdCall) {
897 if (isVarArg)
898 NumBytesForCalleeToPush = isSRet ? 4 : 0;
899 else
900 NumBytesForCalleeToPush = NumBytes;
901 } else {
902 // If this is is a call to a struct-return function, the callee
903 // pops the hidden struct pointer, so we have to push it back.
904 // This is common for Darwin/X86, Linux & Mingw32 targets.
905 NumBytesForCalleeToPush = isSRet ? 4 : 0;
906 }
907
908 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
909 Ops.clear();
910 Ops.push_back(Chain);
911 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
912 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
913 Ops.push_back(InFlag);
914 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
915 InFlag = Chain.getValue(1);
916
917 // Handle result values, copying them out of physregs into vregs that we
918 // return.
919 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
920}
921
922
923//===----------------------------------------------------------------------===//
924// FastCall Calling Convention implementation
925//===----------------------------------------------------------------------===//
926//
927// The X86 'fastcall' calling convention passes up to two integer arguments in
928// registers (an appropriate portion of ECX/EDX), passes arguments in C order,
929// and requires that the callee pop its arguments off the stack (allowing proper
930// tail calls), and has the same return value conventions as C calling convs.
931//
932// This calling convention always arranges for the callee pop value to be 8n+4
933// bytes, which is needed for tail recursion elimination and stack alignment
934// reasons.
935SDOperand
936X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
937 MachineFunction &MF = DAG.getMachineFunction();
938 MachineFrameInfo *MFI = MF.getFrameInfo();
939 SDOperand Root = Op.getOperand(0);
940 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
941
942 // Assign locations to all of the incoming arguments.
943 SmallVector<CCValAssign, 16> ArgLocs;
944 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
945 getTargetMachine(), ArgLocs);
946 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
947
948 SmallVector<SDOperand, 8> ArgValues;
949 unsigned LastVal = ~0U;
950 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
951 CCValAssign &VA = ArgLocs[i];
952 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
953 // places.
954 assert(VA.getValNo() != LastVal &&
955 "Don't support value assigned to multiple locs yet");
956 LastVal = VA.getValNo();
957
958 if (VA.isRegLoc()) {
959 MVT::ValueType RegVT = VA.getLocVT();
960 TargetRegisterClass *RC;
961 if (RegVT == MVT::i32)
962 RC = X86::GR32RegisterClass;
963 else {
964 assert(MVT::isVector(RegVT));
965 RC = X86::VR128RegisterClass;
966 }
967
968 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
969 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
970
971 // If this is an 8 or 16-bit value, it is really passed promoted to 32
972 // bits. Insert an assert[sz]ext to capture this, then truncate to the
973 // right size.
974 if (VA.getLocInfo() == CCValAssign::SExt)
975 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
976 DAG.getValueType(VA.getValVT()));
977 else if (VA.getLocInfo() == CCValAssign::ZExt)
978 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
979 DAG.getValueType(VA.getValVT()));
980
981 if (VA.getLocInfo() != CCValAssign::Full)
982 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
983
984 ArgValues.push_back(ArgValue);
985 } else {
986 assert(VA.isMemLoc());
987
988 // Create the nodes corresponding to a load from this parameter slot.
989 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
990 VA.getLocMemOffset());
991 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
992 ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
993 }
994 }
995
996 ArgValues.push_back(Root);
997
998 unsigned StackSize = CCInfo.getNextStackOffset();
999
1000 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1001 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1002 // arguments and the arguments after the retaddr has been pushed are aligned.
1003 if ((StackSize & 7) == 0)
1004 StackSize += 4;
1005 }
1006
1007 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1008 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
1009 ReturnAddrIndex = 0; // No return address slot generated yet.
1010 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
1011 BytesCallerReserves = 0;
1012
1013 MF.getInfo<X86MachineFunctionInfo>()
1014 ->setBytesToPopOnReturn(BytesToPopOnReturn);
1015
1016 // Return the new list of results.
1017 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1018 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1019}
1020
1021SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1022 unsigned CC) {
1023 SDOperand Chain = Op.getOperand(0);
1024 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1025 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1026 SDOperand Callee = Op.getOperand(4);
1027
1028 // Analyze operands of the call, assigning locations to each operand.
1029 SmallVector<CCValAssign, 16> ArgLocs;
1030 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1031 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1032
1033 // Get a count of how many bytes are to be pushed on the stack.
1034 unsigned NumBytes = CCInfo.getNextStackOffset();
1035
1036 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1037 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1038 // arguments and the arguments after the retaddr has been pushed are aligned.
1039 if ((NumBytes & 7) == 0)
1040 NumBytes += 4;
1041 }
1042
1043 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1044
1045 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1046 SmallVector<SDOperand, 8> MemOpChains;
1047
1048 SDOperand StackPtr;
1049
1050 // Walk the register/memloc assignments, inserting copies/loads.
1051 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1052 CCValAssign &VA = ArgLocs[i];
1053 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1054
1055 // Promote the value if needed.
1056 switch (VA.getLocInfo()) {
1057 default: assert(0 && "Unknown loc info!");
1058 case CCValAssign::Full: break;
1059 case CCValAssign::SExt:
1060 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1061 break;
1062 case CCValAssign::ZExt:
1063 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1064 break;
1065 case CCValAssign::AExt:
1066 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1067 break;
1068 }
1069
1070 if (VA.isRegLoc()) {
1071 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1072 } else {
1073 assert(VA.isMemLoc());
1074 if (StackPtr.Val == 0)
1075 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1076 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1077 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1078 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
1079 }
1080 }
1081
1082 if (!MemOpChains.empty())
1083 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1084 &MemOpChains[0], MemOpChains.size());
1085
1086 // Build a sequence of copy-to-reg nodes chained together with token chain
1087 // and flag operands which copy the outgoing args into registers.
1088 SDOperand InFlag;
1089 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1090 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1091 InFlag);
1092 InFlag = Chain.getValue(1);
1093 }
1094
1095 // If the callee is a GlobalAddress node (quite common, every direct call is)
1096 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1097 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1098 // We should use extra load for direct calls to dllimported functions in
1099 // non-JIT mode.
1100 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1101 getTargetMachine(), true))
1102 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1103 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1104 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1105
1106 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1107 // GOT pointer.
1108 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1109 Subtarget->isPICStyleGOT()) {
1110 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1111 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1112 InFlag);
1113 InFlag = Chain.getValue(1);
1114 }
1115
1116 // Returns a chain & a flag for retval copy to use.
1117 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1118 SmallVector<SDOperand, 8> Ops;
1119 Ops.push_back(Chain);
1120 Ops.push_back(Callee);
1121
1122 // Add argument registers to the end of the list so that they are known live
1123 // into the call.
1124 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1125 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1126 RegsToPass[i].second.getValueType()));
1127
1128 // Add an implicit use GOT pointer in EBX.
1129 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1130 Subtarget->isPICStyleGOT())
1131 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1132
1133 if (InFlag.Val)
1134 Ops.push_back(InFlag);
1135
1136 // FIXME: Do not generate X86ISD::TAILCALL for now.
1137 Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1138 NodeTys, &Ops[0], Ops.size());
1139 InFlag = Chain.getValue(1);
1140
1141 // Returns a flag for retval copy to use.
1142 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1143 Ops.clear();
1144 Ops.push_back(Chain);
1145 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1146 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1147 Ops.push_back(InFlag);
1148 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1149 InFlag = Chain.getValue(1);
1150
1151 // Handle result values, copying them out of physregs into vregs that we
1152 // return.
1153 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1154}
1155
1156
1157//===----------------------------------------------------------------------===//
1158// X86-64 C Calling Convention implementation
1159//===----------------------------------------------------------------------===//
1160
1161SDOperand
1162X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1163 MachineFunction &MF = DAG.getMachineFunction();
1164 MachineFrameInfo *MFI = MF.getFrameInfo();
1165 SDOperand Root = Op.getOperand(0);
1166 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1167
1168 static const unsigned GPR64ArgRegs[] = {
1169 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1170 };
1171 static const unsigned XMMArgRegs[] = {
1172 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1173 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1174 };
1175
1176
1177 // Assign locations to all of the incoming arguments.
1178 SmallVector<CCValAssign, 16> ArgLocs;
1179 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
1180 getTargetMachine(), ArgLocs);
1181 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
1182
1183 SmallVector<SDOperand, 8> ArgValues;
1184 unsigned LastVal = ~0U;
1185 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1186 CCValAssign &VA = ArgLocs[i];
1187 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1188 // places.
1189 assert(VA.getValNo() != LastVal &&
1190 "Don't support value assigned to multiple locs yet");
1191 LastVal = VA.getValNo();
1192
1193 if (VA.isRegLoc()) {
1194 MVT::ValueType RegVT = VA.getLocVT();
1195 TargetRegisterClass *RC;
1196 if (RegVT == MVT::i32)
1197 RC = X86::GR32RegisterClass;
1198 else if (RegVT == MVT::i64)
1199 RC = X86::GR64RegisterClass;
1200 else if (RegVT == MVT::f32)
1201 RC = X86::FR32RegisterClass;
1202 else if (RegVT == MVT::f64)
1203 RC = X86::FR64RegisterClass;
1204 else {
1205 assert(MVT::isVector(RegVT));
1206 if (MVT::getSizeInBits(RegVT) == 64) {
1207 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1208 RegVT = MVT::i64;
1209 } else
1210 RC = X86::VR128RegisterClass;
1211 }
1212
1213 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1214 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1215
1216 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1217 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1218 // right size.
1219 if (VA.getLocInfo() == CCValAssign::SExt)
1220 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1221 DAG.getValueType(VA.getValVT()));
1222 else if (VA.getLocInfo() == CCValAssign::ZExt)
1223 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1224 DAG.getValueType(VA.getValVT()));
1225
1226 if (VA.getLocInfo() != CCValAssign::Full)
1227 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1228
1229 // Handle MMX values passed in GPRs.
1230 if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1231 MVT::getSizeInBits(RegVT) == 64)
1232 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1233
1234 ArgValues.push_back(ArgValue);
1235 } else {
1236 assert(VA.isMemLoc());
1237
1238 // Create the nodes corresponding to a load from this parameter slot.
1239 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1240 VA.getLocMemOffset());
1241 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1242 ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
1243 }
1244 }
1245
1246 unsigned StackSize = CCInfo.getNextStackOffset();
1247
1248 // If the function takes variable number of arguments, make a frame index for
1249 // the start of the first vararg value... for expansion of llvm.va_start.
1250 if (isVarArg) {
1251 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1252 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1253
1254 // For X86-64, if there are vararg parameters that are passed via
1255 // registers, then we must store them to their spots on the stack so they
1256 // may be loaded by deferencing the result of va_next.
1257 VarArgsGPOffset = NumIntRegs * 8;
1258 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1259 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1260 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1261
1262 // Store the integer parameter registers.
1263 SmallVector<SDOperand, 8> MemOps;
1264 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1265 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1266 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1267 for (; NumIntRegs != 6; ++NumIntRegs) {
1268 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1269 X86::GR64RegisterClass);
1270 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1271 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1272 MemOps.push_back(Store);
1273 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1274 DAG.getConstant(8, getPointerTy()));
1275 }
1276
1277 // Now store the XMM (fp + vector) parameter registers.
1278 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1279 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1280 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1281 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1282 X86::VR128RegisterClass);
1283 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1284 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1285 MemOps.push_back(Store);
1286 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1287 DAG.getConstant(16, getPointerTy()));
1288 }
1289 if (!MemOps.empty())
1290 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1291 &MemOps[0], MemOps.size());
1292 }
1293
1294 ArgValues.push_back(Root);
1295
1296 ReturnAddrIndex = 0; // No return address slot generated yet.
1297 BytesToPopOnReturn = 0; // Callee pops nothing.
1298 BytesCallerReserves = StackSize;
1299
1300 // Return the new list of results.
1301 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1302 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1303}
1304
1305SDOperand
1306X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1307 unsigned CC) {
1308 SDOperand Chain = Op.getOperand(0);
1309 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1310 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1311 SDOperand Callee = Op.getOperand(4);
1312
1313 // Analyze operands of the call, assigning locations to each operand.
1314 SmallVector<CCValAssign, 16> ArgLocs;
1315 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1316 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
1317
1318 // Get a count of how many bytes are to be pushed on the stack.
1319 unsigned NumBytes = CCInfo.getNextStackOffset();
1320 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1321
1322 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1323 SmallVector<SDOperand, 8> MemOpChains;
1324
1325 SDOperand StackPtr;
1326
1327 // Walk the register/memloc assignments, inserting copies/loads.
1328 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1329 CCValAssign &VA = ArgLocs[i];
1330 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1331
1332 // Promote the value if needed.
1333 switch (VA.getLocInfo()) {
1334 default: assert(0 && "Unknown loc info!");
1335 case CCValAssign::Full: break;
1336 case CCValAssign::SExt:
1337 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1338 break;
1339 case CCValAssign::ZExt:
1340 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1341 break;
1342 case CCValAssign::AExt:
1343 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1344 break;
1345 }
1346
1347 if (VA.isRegLoc()) {
1348 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1349 } else {
1350 assert(VA.isMemLoc());
1351 if (StackPtr.Val == 0)
1352 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1353 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1354 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1355 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
1356 }
1357 }
1358
1359 if (!MemOpChains.empty())
1360 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1361 &MemOpChains[0], MemOpChains.size());
1362
1363 // Build a sequence of copy-to-reg nodes chained together with token chain
1364 // and flag operands which copy the outgoing args into registers.
1365 SDOperand InFlag;
1366 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1367 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1368 InFlag);
1369 InFlag = Chain.getValue(1);
1370 }
1371
1372 if (isVarArg) {
1373 // From AMD64 ABI document:
1374 // For calls that may call functions that use varargs or stdargs
1375 // (prototype-less calls or calls to functions containing ellipsis (...) in
1376 // the declaration) %al is used as hidden argument to specify the number
1377 // of SSE registers used. The contents of %al do not need to match exactly
1378 // the number of registers, but must be an ubound on the number of SSE
1379 // registers used and is in the range 0 - 8 inclusive.
1380
1381 // Count the number of XMM registers allocated.
1382 static const unsigned XMMArgRegs[] = {
1383 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1384 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1385 };
1386 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1387
1388 Chain = DAG.getCopyToReg(Chain, X86::AL,
1389 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1390 InFlag = Chain.getValue(1);
1391 }
1392
1393 // If the callee is a GlobalAddress node (quite common, every direct call is)
1394 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1395 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1396 // We should use extra load for direct calls to dllimported functions in
1397 // non-JIT mode.
1398 if (getTargetMachine().getCodeModel() != CodeModel::Large
1399 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1400 getTargetMachine(), true))
1401 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1402 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1403 if (getTargetMachine().getCodeModel() != CodeModel::Large)
1404 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1405
1406 // Returns a chain & a flag for retval copy to use.
1407 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1408 SmallVector<SDOperand, 8> Ops;
1409 Ops.push_back(Chain);
1410 Ops.push_back(Callee);
1411
1412 // Add argument registers to the end of the list so that they are known live
1413 // into the call.
1414 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1415 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1416 RegsToPass[i].second.getValueType()));
1417
1418 if (InFlag.Val)
1419 Ops.push_back(InFlag);
1420
1421 // FIXME: Do not generate X86ISD::TAILCALL for now.
1422 Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1423 NodeTys, &Ops[0], Ops.size());
1424 InFlag = Chain.getValue(1);
1425
1426 // Returns a flag for retval copy to use.
1427 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1428 Ops.clear();
1429 Ops.push_back(Chain);
1430 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1431 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1432 Ops.push_back(InFlag);
1433 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1434 InFlag = Chain.getValue(1);
1435
1436 // Handle result values, copying them out of physregs into vregs that we
1437 // return.
1438 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1439}
1440
1441
1442//===----------------------------------------------------------------------===//
1443// Other Lowering Hooks
1444//===----------------------------------------------------------------------===//
1445
1446
1447SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1448 if (ReturnAddrIndex == 0) {
1449 // Set up a frame object for the return address.
1450 MachineFunction &MF = DAG.getMachineFunction();
1451 if (Subtarget->is64Bit())
1452 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1453 else
1454 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1455 }
1456
1457 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1458}
1459
1460
1461
1462/// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1463/// specific condition code. It returns a false if it cannot do a direct
1464/// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1465/// needed.
1466static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1467 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1468 SelectionDAG &DAG) {
1469 X86CC = X86::COND_INVALID;
1470 if (!isFP) {
1471 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1472 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1473 // X > -1 -> X == 0, jump !sign.
1474 RHS = DAG.getConstant(0, RHS.getValueType());
1475 X86CC = X86::COND_NS;
1476 return true;
1477 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1478 // X < 0 -> X == 0, jump on sign.
1479 X86CC = X86::COND_S;
1480 return true;
1481 }
1482 }
1483
1484 switch (SetCCOpcode) {
1485 default: break;
1486 case ISD::SETEQ: X86CC = X86::COND_E; break;
1487 case ISD::SETGT: X86CC = X86::COND_G; break;
1488 case ISD::SETGE: X86CC = X86::COND_GE; break;
1489 case ISD::SETLT: X86CC = X86::COND_L; break;
1490 case ISD::SETLE: X86CC = X86::COND_LE; break;
1491 case ISD::SETNE: X86CC = X86::COND_NE; break;
1492 case ISD::SETULT: X86CC = X86::COND_B; break;
1493 case ISD::SETUGT: X86CC = X86::COND_A; break;
1494 case ISD::SETULE: X86CC = X86::COND_BE; break;
1495 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1496 }
1497 } else {
1498 // On a floating point condition, the flags are set as follows:
1499 // ZF PF CF op
1500 // 0 | 0 | 0 | X > Y
1501 // 0 | 0 | 1 | X < Y
1502 // 1 | 0 | 0 | X == Y
1503 // 1 | 1 | 1 | unordered
1504 bool Flip = false;
1505 switch (SetCCOpcode) {
1506 default: break;
1507 case ISD::SETUEQ:
1508 case ISD::SETEQ: X86CC = X86::COND_E; break;
1509 case ISD::SETOLT: Flip = true; // Fallthrough
1510 case ISD::SETOGT:
1511 case ISD::SETGT: X86CC = X86::COND_A; break;
1512 case ISD::SETOLE: Flip = true; // Fallthrough
1513 case ISD::SETOGE:
1514 case ISD::SETGE: X86CC = X86::COND_AE; break;
1515 case ISD::SETUGT: Flip = true; // Fallthrough
1516 case ISD::SETULT:
1517 case ISD::SETLT: X86CC = X86::COND_B; break;
1518 case ISD::SETUGE: Flip = true; // Fallthrough
1519 case ISD::SETULE:
1520 case ISD::SETLE: X86CC = X86::COND_BE; break;
1521 case ISD::SETONE:
1522 case ISD::SETNE: X86CC = X86::COND_NE; break;
1523 case ISD::SETUO: X86CC = X86::COND_P; break;
1524 case ISD::SETO: X86CC = X86::COND_NP; break;
1525 }
1526 if (Flip)
1527 std::swap(LHS, RHS);
1528 }
1529
1530 return X86CC != X86::COND_INVALID;
1531}
1532
1533/// hasFPCMov - is there a floating point cmov for the specific X86 condition
1534/// code. Current x86 isa includes the following FP cmov instructions:
1535/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1536static bool hasFPCMov(unsigned X86CC) {
1537 switch (X86CC) {
1538 default:
1539 return false;
1540 case X86::COND_B:
1541 case X86::COND_BE:
1542 case X86::COND_E:
1543 case X86::COND_P:
1544 case X86::COND_A:
1545 case X86::COND_AE:
1546 case X86::COND_NE:
1547 case X86::COND_NP:
1548 return true;
1549 }
1550}
1551
1552/// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1553/// true if Op is undef or if its value falls within the specified range (L, H].
1554static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1555 if (Op.getOpcode() == ISD::UNDEF)
1556 return true;
1557
1558 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1559 return (Val >= Low && Val < Hi);
1560}
1561
1562/// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
1563/// true if Op is undef or if its value equal to the specified value.
1564static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1565 if (Op.getOpcode() == ISD::UNDEF)
1566 return true;
1567 return cast<ConstantSDNode>(Op)->getValue() == Val;
1568}
1569
1570/// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1571/// specifies a shuffle of elements that is suitable for input to PSHUFD.
1572bool X86::isPSHUFDMask(SDNode *N) {
1573 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1574
1575 if (N->getNumOperands() != 4)
1576 return false;
1577
1578 // Check if the value doesn't reference the second vector.
1579 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1580 SDOperand Arg = N->getOperand(i);
1581 if (Arg.getOpcode() == ISD::UNDEF) continue;
1582 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1583 if (cast<ConstantSDNode>(Arg)->getValue() >= 4)
1584 return false;
1585 }
1586
1587 return true;
1588}
1589
1590/// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1591/// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1592bool X86::isPSHUFHWMask(SDNode *N) {
1593 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1594
1595 if (N->getNumOperands() != 8)
1596 return false;
1597
1598 // Lower quadword copied in order.
1599 for (unsigned i = 0; i != 4; ++i) {
1600 SDOperand Arg = N->getOperand(i);
1601 if (Arg.getOpcode() == ISD::UNDEF) continue;
1602 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1603 if (cast<ConstantSDNode>(Arg)->getValue() != i)
1604 return false;
1605 }
1606
1607 // Upper quadword shuffled.
1608 for (unsigned i = 4; i != 8; ++i) {
1609 SDOperand Arg = N->getOperand(i);
1610 if (Arg.getOpcode() == ISD::UNDEF) continue;
1611 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1612 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1613 if (Val < 4 || Val > 7)
1614 return false;
1615 }
1616
1617 return true;
1618}
1619
1620/// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
1621/// specifies a shuffle of elements that is suitable for input to PSHUFLW.
1622bool X86::isPSHUFLWMask(SDNode *N) {
1623 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1624
1625 if (N->getNumOperands() != 8)
1626 return false;
1627
1628 // Upper quadword copied in order.
1629 for (unsigned i = 4; i != 8; ++i)
1630 if (!isUndefOrEqual(N->getOperand(i), i))
1631 return false;
1632
1633 // Lower quadword shuffled.
1634 for (unsigned i = 0; i != 4; ++i)
1635 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
1636 return false;
1637
1638 return true;
1639}
1640
1641/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
1642/// specifies a shuffle of elements that is suitable for input to SHUFP*.
1643static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
1644 if (NumElems != 2 && NumElems != 4) return false;
1645
1646 unsigned Half = NumElems / 2;
1647 for (unsigned i = 0; i < Half; ++i)
1648 if (!isUndefOrInRange(Elems[i], 0, NumElems))
1649 return false;
1650 for (unsigned i = Half; i < NumElems; ++i)
1651 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
1652 return false;
1653
1654 return true;
1655}
1656
1657bool X86::isSHUFPMask(SDNode *N) {
1658 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1659 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
1660}
1661
1662/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
1663/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
1664/// half elements to come from vector 1 (which would equal the dest.) and
1665/// the upper half to come from vector 2.
1666static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
1667 if (NumOps != 2 && NumOps != 4) return false;
1668
1669 unsigned Half = NumOps / 2;
1670 for (unsigned i = 0; i < Half; ++i)
1671 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
1672 return false;
1673 for (unsigned i = Half; i < NumOps; ++i)
1674 if (!isUndefOrInRange(Ops[i], 0, NumOps))
1675 return false;
1676 return true;
1677}
1678
1679static bool isCommutedSHUFP(SDNode *N) {
1680 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1681 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
1682}
1683
1684/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
1685/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
1686bool X86::isMOVHLPSMask(SDNode *N) {
1687 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1688
1689 if (N->getNumOperands() != 4)
1690 return false;
1691
1692 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
1693 return isUndefOrEqual(N->getOperand(0), 6) &&
1694 isUndefOrEqual(N->getOperand(1), 7) &&
1695 isUndefOrEqual(N->getOperand(2), 2) &&
1696 isUndefOrEqual(N->getOperand(3), 3);
1697}
1698
1699/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
1700/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
1701/// <2, 3, 2, 3>
1702bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
1703 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1704
1705 if (N->getNumOperands() != 4)
1706 return false;
1707
1708 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
1709 return isUndefOrEqual(N->getOperand(0), 2) &&
1710 isUndefOrEqual(N->getOperand(1), 3) &&
1711 isUndefOrEqual(N->getOperand(2), 2) &&
1712 isUndefOrEqual(N->getOperand(3), 3);
1713}
1714
1715/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
1716/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
1717bool X86::isMOVLPMask(SDNode *N) {
1718 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1719
1720 unsigned NumElems = N->getNumOperands();
1721 if (NumElems != 2 && NumElems != 4)
1722 return false;
1723
1724 for (unsigned i = 0; i < NumElems/2; ++i)
1725 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
1726 return false;
1727
1728 for (unsigned i = NumElems/2; i < NumElems; ++i)
1729 if (!isUndefOrEqual(N->getOperand(i), i))
1730 return false;
1731
1732 return true;
1733}
1734
1735/// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
1736/// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
1737/// and MOVLHPS.
1738bool X86::isMOVHPMask(SDNode *N) {
1739 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1740
1741 unsigned NumElems = N->getNumOperands();
1742 if (NumElems != 2 && NumElems != 4)
1743 return false;
1744
1745 for (unsigned i = 0; i < NumElems/2; ++i)
1746 if (!isUndefOrEqual(N->getOperand(i), i))
1747 return false;
1748
1749 for (unsigned i = 0; i < NumElems/2; ++i) {
1750 SDOperand Arg = N->getOperand(i + NumElems/2);
1751 if (!isUndefOrEqual(Arg, i + NumElems))
1752 return false;
1753 }
1754
1755 return true;
1756}
1757
1758/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
1759/// specifies a shuffle of elements that is suitable for input to UNPCKL.
1760bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
1761 bool V2IsSplat = false) {
1762 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1763 return false;
1764
1765 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
1766 SDOperand BitI = Elts[i];
1767 SDOperand BitI1 = Elts[i+1];
1768 if (!isUndefOrEqual(BitI, j))
1769 return false;
1770 if (V2IsSplat) {
1771 if (isUndefOrEqual(BitI1, NumElts))
1772 return false;
1773 } else {
1774 if (!isUndefOrEqual(BitI1, j + NumElts))
1775 return false;
1776 }
1777 }
1778
1779 return true;
1780}
1781
1782bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
1783 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1784 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
1785}
1786
1787/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
1788/// specifies a shuffle of elements that is suitable for input to UNPCKH.
1789bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
1790 bool V2IsSplat = false) {
1791 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1792 return false;
1793
1794 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
1795 SDOperand BitI = Elts[i];
1796 SDOperand BitI1 = Elts[i+1];
1797 if (!isUndefOrEqual(BitI, j + NumElts/2))
1798 return false;
1799 if (V2IsSplat) {
1800 if (isUndefOrEqual(BitI1, NumElts))
1801 return false;
1802 } else {
1803 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
1804 return false;
1805 }
1806 }
1807
1808 return true;
1809}
1810
1811bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
1812 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1813 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
1814}
1815
1816/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
1817/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
1818/// <0, 0, 1, 1>
1819bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
1820 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1821
1822 unsigned NumElems = N->getNumOperands();
1823 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1824 return false;
1825
1826 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
1827 SDOperand BitI = N->getOperand(i);
1828 SDOperand BitI1 = N->getOperand(i+1);
1829
1830 if (!isUndefOrEqual(BitI, j))
1831 return false;
1832 if (!isUndefOrEqual(BitI1, j))
1833 return false;
1834 }
1835
1836 return true;
1837}
1838
1839/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
1840/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
1841/// <2, 2, 3, 3>
1842bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
1843 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1844
1845 unsigned NumElems = N->getNumOperands();
1846 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1847 return false;
1848
1849 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
1850 SDOperand BitI = N->getOperand(i);
1851 SDOperand BitI1 = N->getOperand(i + 1);
1852
1853 if (!isUndefOrEqual(BitI, j))
1854 return false;
1855 if (!isUndefOrEqual(BitI1, j))
1856 return false;
1857 }
1858
1859 return true;
1860}
1861
1862/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
1863/// specifies a shuffle of elements that is suitable for input to MOVSS,
1864/// MOVSD, and MOVD, i.e. setting the lowest element.
1865static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
1866 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1867 return false;
1868
1869 if (!isUndefOrEqual(Elts[0], NumElts))
1870 return false;
1871
1872 for (unsigned i = 1; i < NumElts; ++i) {
1873 if (!isUndefOrEqual(Elts[i], i))
1874 return false;
1875 }
1876
1877 return true;
1878}
1879
1880bool X86::isMOVLMask(SDNode *N) {
1881 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1882 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
1883}
1884
1885/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
1886/// of what x86 movss want. X86 movs requires the lowest element to be lowest
1887/// element of vector 2 and the other elements to come from vector 1 in order.
1888static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
1889 bool V2IsSplat = false,
1890 bool V2IsUndef = false) {
1891 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
1892 return false;
1893
1894 if (!isUndefOrEqual(Ops[0], 0))
1895 return false;
1896
1897 for (unsigned i = 1; i < NumOps; ++i) {
1898 SDOperand Arg = Ops[i];
1899 if (!(isUndefOrEqual(Arg, i+NumOps) ||
1900 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
1901 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
1902 return false;
1903 }
1904
1905 return true;
1906}
1907
1908static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
1909 bool V2IsUndef = false) {
1910 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1911 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
1912 V2IsSplat, V2IsUndef);
1913}
1914
1915/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1916/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
1917bool X86::isMOVSHDUPMask(SDNode *N) {
1918 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1919
1920 if (N->getNumOperands() != 4)
1921 return false;
1922
1923 // Expect 1, 1, 3, 3
1924 for (unsigned i = 0; i < 2; ++i) {
1925 SDOperand Arg = N->getOperand(i);
1926 if (Arg.getOpcode() == ISD::UNDEF) continue;
1927 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1928 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1929 if (Val != 1) return false;
1930 }
1931
1932 bool HasHi = false;
1933 for (unsigned i = 2; i < 4; ++i) {
1934 SDOperand Arg = N->getOperand(i);
1935 if (Arg.getOpcode() == ISD::UNDEF) continue;
1936 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1937 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1938 if (Val != 3) return false;
1939 HasHi = true;
1940 }
1941
1942 // Don't use movshdup if it can be done with a shufps.
1943 return HasHi;
1944}
1945
1946/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1947/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
1948bool X86::isMOVSLDUPMask(SDNode *N) {
1949 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1950
1951 if (N->getNumOperands() != 4)
1952 return false;
1953
1954 // Expect 0, 0, 2, 2
1955 for (unsigned i = 0; i < 2; ++i) {
1956 SDOperand Arg = N->getOperand(i);
1957 if (Arg.getOpcode() == ISD::UNDEF) continue;
1958 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1959 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1960 if (Val != 0) return false;
1961 }
1962
1963 bool HasHi = false;
1964 for (unsigned i = 2; i < 4; ++i) {
1965 SDOperand Arg = N->getOperand(i);
1966 if (Arg.getOpcode() == ISD::UNDEF) continue;
1967 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1968 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1969 if (Val != 2) return false;
1970 HasHi = true;
1971 }
1972
1973 // Don't use movshdup if it can be done with a shufps.
1974 return HasHi;
1975}
1976
1977/// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
1978/// specifies a identity operation on the LHS or RHS.
1979static bool isIdentityMask(SDNode *N, bool RHS = false) {
1980 unsigned NumElems = N->getNumOperands();
1981 for (unsigned i = 0; i < NumElems; ++i)
1982 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
1983 return false;
1984 return true;
1985}
1986
1987/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
1988/// a splat of a single element.
1989static bool isSplatMask(SDNode *N) {
1990 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1991
1992 // This is a splat operation if each element of the permute is the same, and
1993 // if the value doesn't reference the second vector.
1994 unsigned NumElems = N->getNumOperands();
1995 SDOperand ElementBase;
1996 unsigned i = 0;
1997 for (; i != NumElems; ++i) {
1998 SDOperand Elt = N->getOperand(i);
1999 if (isa<ConstantSDNode>(Elt)) {
2000 ElementBase = Elt;
2001 break;
2002 }
2003 }
2004
2005 if (!ElementBase.Val)
2006 return false;
2007
2008 for (; i != NumElems; ++i) {
2009 SDOperand Arg = N->getOperand(i);
2010 if (Arg.getOpcode() == ISD::UNDEF) continue;
2011 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2012 if (Arg != ElementBase) return false;
2013 }
2014
2015 // Make sure it is a splat of the first vector operand.
2016 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2017}
2018
2019/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2020/// a splat of a single element and it's a 2 or 4 element mask.
2021bool X86::isSplatMask(SDNode *N) {
2022 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2023
2024 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2025 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2026 return false;
2027 return ::isSplatMask(N);
2028}
2029
2030/// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2031/// specifies a splat of zero element.
2032bool X86::isSplatLoMask(SDNode *N) {
2033 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2034
2035 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2036 if (!isUndefOrEqual(N->getOperand(i), 0))
2037 return false;
2038 return true;
2039}
2040
2041/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2042/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2043/// instructions.
2044unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2045 unsigned NumOperands = N->getNumOperands();
2046 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2047 unsigned Mask = 0;
2048 for (unsigned i = 0; i < NumOperands; ++i) {
2049 unsigned Val = 0;
2050 SDOperand Arg = N->getOperand(NumOperands-i-1);
2051 if (Arg.getOpcode() != ISD::UNDEF)
2052 Val = cast<ConstantSDNode>(Arg)->getValue();
2053 if (Val >= NumOperands) Val -= NumOperands;
2054 Mask |= Val;
2055 if (i != NumOperands - 1)
2056 Mask <<= Shift;
2057 }
2058
2059 return Mask;
2060}
2061
2062/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2063/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2064/// instructions.
2065unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2066 unsigned Mask = 0;
2067 // 8 nodes, but we only care about the last 4.
2068 for (unsigned i = 7; i >= 4; --i) {
2069 unsigned Val = 0;
2070 SDOperand Arg = N->getOperand(i);
2071 if (Arg.getOpcode() != ISD::UNDEF)
2072 Val = cast<ConstantSDNode>(Arg)->getValue();
2073 Mask |= (Val - 4);
2074 if (i != 4)
2075 Mask <<= 2;
2076 }
2077
2078 return Mask;
2079}
2080
2081/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2082/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2083/// instructions.
2084unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2085 unsigned Mask = 0;
2086 // 8 nodes, but we only care about the first 4.
2087 for (int i = 3; i >= 0; --i) {
2088 unsigned Val = 0;
2089 SDOperand Arg = N->getOperand(i);
2090 if (Arg.getOpcode() != ISD::UNDEF)
2091 Val = cast<ConstantSDNode>(Arg)->getValue();
2092 Mask |= Val;
2093 if (i != 0)
2094 Mask <<= 2;
2095 }
2096
2097 return Mask;
2098}
2099
2100/// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2101/// specifies a 8 element shuffle that can be broken into a pair of
2102/// PSHUFHW and PSHUFLW.
2103static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2104 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2105
2106 if (N->getNumOperands() != 8)
2107 return false;
2108
2109 // Lower quadword shuffled.
2110 for (unsigned i = 0; i != 4; ++i) {
2111 SDOperand Arg = N->getOperand(i);
2112 if (Arg.getOpcode() == ISD::UNDEF) continue;
2113 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2114 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2115 if (Val > 4)
2116 return false;
2117 }
2118
2119 // Upper quadword shuffled.
2120 for (unsigned i = 4; i != 8; ++i) {
2121 SDOperand Arg = N->getOperand(i);
2122 if (Arg.getOpcode() == ISD::UNDEF) continue;
2123 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2124 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2125 if (Val < 4 || Val > 7)
2126 return false;
2127 }
2128
2129 return true;
2130}
2131
2132/// CommuteVectorShuffle - Swap vector_shuffle operandsas well as
2133/// values in ther permute mask.
2134static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2135 SDOperand &V2, SDOperand &Mask,
2136 SelectionDAG &DAG) {
2137 MVT::ValueType VT = Op.getValueType();
2138 MVT::ValueType MaskVT = Mask.getValueType();
2139 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2140 unsigned NumElems = Mask.getNumOperands();
2141 SmallVector<SDOperand, 8> MaskVec;
2142
2143 for (unsigned i = 0; i != NumElems; ++i) {
2144 SDOperand Arg = Mask.getOperand(i);
2145 if (Arg.getOpcode() == ISD::UNDEF) {
2146 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2147 continue;
2148 }
2149 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2150 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2151 if (Val < NumElems)
2152 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2153 else
2154 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2155 }
2156
2157 std::swap(V1, V2);
2158 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2159 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2160}
2161
2162/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2163/// match movhlps. The lower half elements should come from upper half of
2164/// V1 (and in order), and the upper half elements should come from the upper
2165/// half of V2 (and in order).
2166static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2167 unsigned NumElems = Mask->getNumOperands();
2168 if (NumElems != 4)
2169 return false;
2170 for (unsigned i = 0, e = 2; i != e; ++i)
2171 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2172 return false;
2173 for (unsigned i = 2; i != 4; ++i)
2174 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2175 return false;
2176 return true;
2177}
2178
2179/// isScalarLoadToVector - Returns true if the node is a scalar load that
2180/// is promoted to a vector.
2181static inline bool isScalarLoadToVector(SDNode *N) {
2182 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2183 N = N->getOperand(0).Val;
2184 return ISD::isNON_EXTLoad(N);
2185 }
2186 return false;
2187}
2188
2189/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2190/// match movlp{s|d}. The lower half elements should come from lower half of
2191/// V1 (and in order), and the upper half elements should come from the upper
2192/// half of V2 (and in order). And since V1 will become the source of the
2193/// MOVLP, it must be either a vector load or a scalar load to vector.
2194static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2195 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2196 return false;
2197 // Is V2 is a vector load, don't do this transformation. We will try to use
2198 // load folding shufps op.
2199 if (ISD::isNON_EXTLoad(V2))
2200 return false;
2201
2202 unsigned NumElems = Mask->getNumOperands();
2203 if (NumElems != 2 && NumElems != 4)
2204 return false;
2205 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2206 if (!isUndefOrEqual(Mask->getOperand(i), i))
2207 return false;
2208 for (unsigned i = NumElems/2; i != NumElems; ++i)
2209 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2210 return false;
2211 return true;
2212}
2213
2214/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2215/// all the same.
2216static bool isSplatVector(SDNode *N) {
2217 if (N->getOpcode() != ISD::BUILD_VECTOR)
2218 return false;
2219
2220 SDOperand SplatValue = N->getOperand(0);
2221 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2222 if (N->getOperand(i) != SplatValue)
2223 return false;
2224 return true;
2225}
2226
2227/// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2228/// to an undef.
2229static bool isUndefShuffle(SDNode *N) {
2230 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2231 return false;
2232
2233 SDOperand V1 = N->getOperand(0);
2234 SDOperand V2 = N->getOperand(1);
2235 SDOperand Mask = N->getOperand(2);
2236 unsigned NumElems = Mask.getNumOperands();
2237 for (unsigned i = 0; i != NumElems; ++i) {
2238 SDOperand Arg = Mask.getOperand(i);
2239 if (Arg.getOpcode() != ISD::UNDEF) {
2240 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2241 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2242 return false;
2243 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2244 return false;
2245 }
2246 }
2247 return true;
2248}
2249
2250/// isZeroNode - Returns true if Elt is a constant zero or a floating point
2251/// constant +0.0.
2252static inline bool isZeroNode(SDOperand Elt) {
2253 return ((isa<ConstantSDNode>(Elt) &&
2254 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2255 (isa<ConstantFPSDNode>(Elt) &&
2256 cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
2257}
2258
2259/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2260/// to an zero vector.
2261static bool isZeroShuffle(SDNode *N) {
2262 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2263 return false;
2264
2265 SDOperand V1 = N->getOperand(0);
2266 SDOperand V2 = N->getOperand(1);
2267 SDOperand Mask = N->getOperand(2);
2268 unsigned NumElems = Mask.getNumOperands();
2269 for (unsigned i = 0; i != NumElems; ++i) {
2270 SDOperand Arg = Mask.getOperand(i);
2271 if (Arg.getOpcode() != ISD::UNDEF) {
2272 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2273 if (Idx < NumElems) {
2274 unsigned Opc = V1.Val->getOpcode();
2275 if (Opc == ISD::UNDEF)
2276 continue;
2277 if (Opc != ISD::BUILD_VECTOR ||
2278 !isZeroNode(V1.Val->getOperand(Idx)))
2279 return false;
2280 } else if (Idx >= NumElems) {
2281 unsigned Opc = V2.Val->getOpcode();
2282 if (Opc == ISD::UNDEF)
2283 continue;
2284 if (Opc != ISD::BUILD_VECTOR ||
2285 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2286 return false;
2287 }
2288 }
2289 }
2290 return true;
2291}
2292
2293/// getZeroVector - Returns a vector of specified type with all zero elements.
2294///
2295static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2296 assert(MVT::isVector(VT) && "Expected a vector type");
2297 unsigned NumElems = MVT::getVectorNumElements(VT);
2298 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2299 bool isFP = MVT::isFloatingPoint(EVT);
2300 SDOperand Zero = isFP ? DAG.getConstantFP(0.0, EVT) : DAG.getConstant(0, EVT);
2301 SmallVector<SDOperand, 8> ZeroVec(NumElems, Zero);
2302 return DAG.getNode(ISD::BUILD_VECTOR, VT, &ZeroVec[0], ZeroVec.size());
2303}
2304
2305/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2306/// that point to V2 points to its first element.
2307static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2308 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2309
2310 bool Changed = false;
2311 SmallVector<SDOperand, 8> MaskVec;
2312 unsigned NumElems = Mask.getNumOperands();
2313 for (unsigned i = 0; i != NumElems; ++i) {
2314 SDOperand Arg = Mask.getOperand(i);
2315 if (Arg.getOpcode() != ISD::UNDEF) {
2316 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2317 if (Val > NumElems) {
2318 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2319 Changed = true;
2320 }
2321 }
2322 MaskVec.push_back(Arg);
2323 }
2324
2325 if (Changed)
2326 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2327 &MaskVec[0], MaskVec.size());
2328 return Mask;
2329}
2330
2331/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2332/// operation of specified width.
2333static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2334 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2335 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2336
2337 SmallVector<SDOperand, 8> MaskVec;
2338 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2339 for (unsigned i = 1; i != NumElems; ++i)
2340 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2341 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2342}
2343
2344/// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2345/// of specified width.
2346static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2347 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2348 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2349 SmallVector<SDOperand, 8> MaskVec;
2350 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2351 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2352 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2353 }
2354 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2355}
2356
2357/// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2358/// of specified width.
2359static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2360 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2361 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2362 unsigned Half = NumElems/2;
2363 SmallVector<SDOperand, 8> MaskVec;
2364 for (unsigned i = 0; i != Half; ++i) {
2365 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2366 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2367 }
2368 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2369}
2370
2371/// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2372///
2373static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2374 SDOperand V1 = Op.getOperand(0);
2375 SDOperand Mask = Op.getOperand(2);
2376 MVT::ValueType VT = Op.getValueType();
2377 unsigned NumElems = Mask.getNumOperands();
2378 Mask = getUnpacklMask(NumElems, DAG);
2379 while (NumElems != 4) {
2380 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2381 NumElems >>= 1;
2382 }
2383 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2384
2385 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2386 Mask = getZeroVector(MaskVT, DAG);
2387 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2388 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2389 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2390}
2391
2392/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2393/// vector of zero or undef vector.
2394static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2395 unsigned NumElems, unsigned Idx,
2396 bool isZero, SelectionDAG &DAG) {
2397 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2398 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2399 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2400 SDOperand Zero = DAG.getConstant(0, EVT);
2401 SmallVector<SDOperand, 8> MaskVec(NumElems, Zero);
2402 MaskVec[Idx] = DAG.getConstant(NumElems, EVT);
2403 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2404 &MaskVec[0], MaskVec.size());
2405 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2406}
2407
2408/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2409///
2410static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2411 unsigned NumNonZero, unsigned NumZero,
2412 SelectionDAG &DAG, TargetLowering &TLI) {
2413 if (NumNonZero > 8)
2414 return SDOperand();
2415
2416 SDOperand V(0, 0);
2417 bool First = true;
2418 for (unsigned i = 0; i < 16; ++i) {
2419 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2420 if (ThisIsNonZero && First) {
2421 if (NumZero)
2422 V = getZeroVector(MVT::v8i16, DAG);
2423 else
2424 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2425 First = false;
2426 }
2427
2428 if ((i & 1) != 0) {
2429 SDOperand ThisElt(0, 0), LastElt(0, 0);
2430 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2431 if (LastIsNonZero) {
2432 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2433 }
2434 if (ThisIsNonZero) {
2435 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2436 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2437 ThisElt, DAG.getConstant(8, MVT::i8));
2438 if (LastIsNonZero)
2439 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2440 } else
2441 ThisElt = LastElt;
2442
2443 if (ThisElt.Val)
2444 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2445 DAG.getConstant(i/2, TLI.getPointerTy()));
2446 }
2447 }
2448
2449 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2450}
2451
2452/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2453///
2454static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2455 unsigned NumNonZero, unsigned NumZero,
2456 SelectionDAG &DAG, TargetLowering &TLI) {
2457 if (NumNonZero > 4)
2458 return SDOperand();
2459
2460 SDOperand V(0, 0);
2461 bool First = true;
2462 for (unsigned i = 0; i < 8; ++i) {
2463 bool isNonZero = (NonZeros & (1 << i)) != 0;
2464 if (isNonZero) {
2465 if (First) {
2466 if (NumZero)
2467 V = getZeroVector(MVT::v8i16, DAG);
2468 else
2469 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2470 First = false;
2471 }
2472 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2473 DAG.getConstant(i, TLI.getPointerTy()));
2474 }
2475 }
2476
2477 return V;
2478}
2479
2480SDOperand
2481X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2482 // All zero's are handled with pxor.
2483 if (ISD::isBuildVectorAllZeros(Op.Val))
2484 return Op;
2485
2486 // All one's are handled with pcmpeqd.
2487 if (ISD::isBuildVectorAllOnes(Op.Val))
2488 return Op;
2489
2490 MVT::ValueType VT = Op.getValueType();
2491 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2492 unsigned EVTBits = MVT::getSizeInBits(EVT);
2493
2494 unsigned NumElems = Op.getNumOperands();
2495 unsigned NumZero = 0;
2496 unsigned NumNonZero = 0;
2497 unsigned NonZeros = 0;
2498 std::set<SDOperand> Values;
2499 for (unsigned i = 0; i < NumElems; ++i) {
2500 SDOperand Elt = Op.getOperand(i);
2501 if (Elt.getOpcode() != ISD::UNDEF) {
2502 Values.insert(Elt);
2503 if (isZeroNode(Elt))
2504 NumZero++;
2505 else {
2506 NonZeros |= (1 << i);
2507 NumNonZero++;
2508 }
2509 }
2510 }
2511
2512 if (NumNonZero == 0) {
2513 if (NumZero == 0)
2514 // All undef vector. Return an UNDEF.
2515 return DAG.getNode(ISD::UNDEF, VT);
2516 else
2517 // A mix of zero and undef. Return a zero vector.
2518 return getZeroVector(VT, DAG);
2519 }
2520
2521 // Splat is obviously ok. Let legalizer expand it to a shuffle.
2522 if (Values.size() == 1)
2523 return SDOperand();
2524
2525 // Special case for single non-zero element.
2526 if (NumNonZero == 1) {
2527 unsigned Idx = CountTrailingZeros_32(NonZeros);
2528 SDOperand Item = Op.getOperand(Idx);
2529 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
2530 if (Idx == 0)
2531 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
2532 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
2533 NumZero > 0, DAG);
2534
2535 if (EVTBits == 32) {
2536 // Turn it into a shuffle of zero and zero-extended scalar to vector.
2537 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
2538 DAG);
2539 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2540 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
2541 SmallVector<SDOperand, 8> MaskVec;
2542 for (unsigned i = 0; i < NumElems; i++)
2543 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
2544 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2545 &MaskVec[0], MaskVec.size());
2546 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
2547 DAG.getNode(ISD::UNDEF, VT), Mask);
2548 }
2549 }
2550
2551 // Let legalizer expand 2-wide build_vectors.
2552 if (EVTBits == 64)
2553 return SDOperand();
2554
2555 // If element VT is < 32 bits, convert it to inserts into a zero vector.
2556 if (EVTBits == 8 && NumElems == 16) {
2557 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
2558 *this);
2559 if (V.Val) return V;
2560 }
2561
2562 if (EVTBits == 16 && NumElems == 8) {
2563 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
2564 *this);
2565 if (V.Val) return V;
2566 }
2567
2568 // If element VT is == 32 bits, turn it into a number of shuffles.
2569 SmallVector<SDOperand, 8> V;
2570 V.resize(NumElems);
2571 if (NumElems == 4 && NumZero > 0) {
2572 for (unsigned i = 0; i < 4; ++i) {
2573 bool isZero = !(NonZeros & (1 << i));
2574 if (isZero)
2575 V[i] = getZeroVector(VT, DAG);
2576 else
2577 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2578 }
2579
2580 for (unsigned i = 0; i < 2; ++i) {
2581 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
2582 default: break;
2583 case 0:
2584 V[i] = V[i*2]; // Must be a zero vector.
2585 break;
2586 case 1:
2587 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
2588 getMOVLMask(NumElems, DAG));
2589 break;
2590 case 2:
2591 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2592 getMOVLMask(NumElems, DAG));
2593 break;
2594 case 3:
2595 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2596 getUnpacklMask(NumElems, DAG));
2597 break;
2598 }
2599 }
2600
2601 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
2602 // clears the upper bits.
2603 // FIXME: we can do the same for v4f32 case when we know both parts of
2604 // the lower half come from scalar_to_vector (loadf32). We should do
2605 // that in post legalizer dag combiner with target specific hooks.
2606 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
2607 return V[0];
2608 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2609 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2610 SmallVector<SDOperand, 8> MaskVec;
2611 bool Reverse = (NonZeros & 0x3) == 2;
2612 for (unsigned i = 0; i < 2; ++i)
2613 if (Reverse)
2614 MaskVec.push_back(DAG.getConstant(1-i, EVT));
2615 else
2616 MaskVec.push_back(DAG.getConstant(i, EVT));
2617 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
2618 for (unsigned i = 0; i < 2; ++i)
2619 if (Reverse)
2620 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
2621 else
2622 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
2623 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2624 &MaskVec[0], MaskVec.size());
2625 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
2626 }
2627
2628 if (Values.size() > 2) {
2629 // Expand into a number of unpckl*.
2630 // e.g. for v4f32
2631 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
2632 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
2633 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
2634 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
2635 for (unsigned i = 0; i < NumElems; ++i)
2636 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2637 NumElems >>= 1;
2638 while (NumElems != 0) {
2639 for (unsigned i = 0; i < NumElems; ++i)
2640 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
2641 UnpckMask);
2642 NumElems >>= 1;
2643 }
2644 return V[0];
2645 }
2646
2647 return SDOperand();
2648}
2649
2650SDOperand
2651X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
2652 SDOperand V1 = Op.getOperand(0);
2653 SDOperand V2 = Op.getOperand(1);
2654 SDOperand PermMask = Op.getOperand(2);
2655 MVT::ValueType VT = Op.getValueType();
2656 unsigned NumElems = PermMask.getNumOperands();
2657 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
2658 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
2659 bool V1IsSplat = false;
2660 bool V2IsSplat = false;
2661
2662 if (isUndefShuffle(Op.Val))
2663 return DAG.getNode(ISD::UNDEF, VT);
2664
2665 if (isZeroShuffle(Op.Val))
2666 return getZeroVector(VT, DAG);
2667
2668 if (isIdentityMask(PermMask.Val))
2669 return V1;
2670 else if (isIdentityMask(PermMask.Val, true))
2671 return V2;
2672
2673 if (isSplatMask(PermMask.Val)) {
2674 if (NumElems <= 4) return Op;
2675 // Promote it to a v4i32 splat.
2676 return PromoteSplat(Op, DAG);
2677 }
2678
2679 if (X86::isMOVLMask(PermMask.Val))
2680 return (V1IsUndef) ? V2 : Op;
2681
2682 if (X86::isMOVSHDUPMask(PermMask.Val) ||
2683 X86::isMOVSLDUPMask(PermMask.Val) ||
2684 X86::isMOVHLPSMask(PermMask.Val) ||
2685 X86::isMOVHPMask(PermMask.Val) ||
2686 X86::isMOVLPMask(PermMask.Val))
2687 return Op;
2688
2689 if (ShouldXformToMOVHLPS(PermMask.Val) ||
2690 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
2691 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2692
2693 bool Commuted = false;
2694 V1IsSplat = isSplatVector(V1.Val);
2695 V2IsSplat = isSplatVector(V2.Val);
2696 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
2697 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2698 std::swap(V1IsSplat, V2IsSplat);
2699 std::swap(V1IsUndef, V2IsUndef);
2700 Commuted = true;
2701 }
2702
2703 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
2704 if (V2IsUndef) return V1;
2705 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2706 if (V2IsSplat) {
2707 // V2 is a splat, so the mask may be malformed. That is, it may point
2708 // to any V2 element. The instruction selectior won't like this. Get
2709 // a corrected mask and commute to form a proper MOVS{S|D}.
2710 SDOperand NewMask = getMOVLMask(NumElems, DAG);
2711 if (NewMask.Val != PermMask.Val)
2712 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2713 }
2714 return Op;
2715 }
2716
2717 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
2718 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
2719 X86::isUNPCKLMask(PermMask.Val) ||
2720 X86::isUNPCKHMask(PermMask.Val))
2721 return Op;
2722
2723 if (V2IsSplat) {
2724 // Normalize mask so all entries that point to V2 points to its first
2725 // element then try to match unpck{h|l} again. If match, return a
2726 // new vector_shuffle with the corrected mask.
2727 SDOperand NewMask = NormalizeMask(PermMask, DAG);
2728 if (NewMask.Val != PermMask.Val) {
2729 if (X86::isUNPCKLMask(PermMask.Val, true)) {
2730 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
2731 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2732 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
2733 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
2734 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2735 }
2736 }
2737 }
2738
2739 // Normalize the node to match x86 shuffle ops if needed
2740 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
2741 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2742
2743 if (Commuted) {
2744 // Commute is back and try unpck* again.
2745 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2746 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
2747 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
2748 X86::isUNPCKLMask(PermMask.Val) ||
2749 X86::isUNPCKHMask(PermMask.Val))
2750 return Op;
2751 }
2752
2753 // If VT is integer, try PSHUF* first, then SHUFP*.
2754 if (MVT::isInteger(VT)) {
2755 if (X86::isPSHUFDMask(PermMask.Val) ||
2756 X86::isPSHUFHWMask(PermMask.Val) ||
2757 X86::isPSHUFLWMask(PermMask.Val)) {
2758 if (V2.getOpcode() != ISD::UNDEF)
2759 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2760 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2761 return Op;
2762 }
2763
2764 if (X86::isSHUFPMask(PermMask.Val) &&
2765 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
2766 return Op;
2767
2768 // Handle v8i16 shuffle high / low shuffle node pair.
2769 if (VT == MVT::v8i16 && isPSHUFHW_PSHUFLWMask(PermMask.Val)) {
2770 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2771 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2772 SmallVector<SDOperand, 8> MaskVec;
2773 for (unsigned i = 0; i != 4; ++i)
2774 MaskVec.push_back(PermMask.getOperand(i));
2775 for (unsigned i = 4; i != 8; ++i)
2776 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2777 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2778 &MaskVec[0], MaskVec.size());
2779 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2780 MaskVec.clear();
2781 for (unsigned i = 0; i != 4; ++i)
2782 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2783 for (unsigned i = 4; i != 8; ++i)
2784 MaskVec.push_back(PermMask.getOperand(i));
2785 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0],MaskVec.size());
2786 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2787 }
2788 } else {
2789 // Floating point cases in the other order.
2790 if (X86::isSHUFPMask(PermMask.Val))
2791 return Op;
2792 if (X86::isPSHUFDMask(PermMask.Val) ||
2793 X86::isPSHUFHWMask(PermMask.Val) ||
2794 X86::isPSHUFLWMask(PermMask.Val)) {
2795 if (V2.getOpcode() != ISD::UNDEF)
2796 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2797 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2798 return Op;
2799 }
2800 }
2801
2802 if (NumElems == 4 &&
2803 // Don't do this for MMX.
2804 MVT::getSizeInBits(VT) != 64) {
2805 MVT::ValueType MaskVT = PermMask.getValueType();
2806 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
2807 SmallVector<std::pair<int, int>, 8> Locs;
2808 Locs.reserve(NumElems);
2809 SmallVector<SDOperand, 8> Mask1(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2810 SmallVector<SDOperand, 8> Mask2(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2811 unsigned NumHi = 0;
2812 unsigned NumLo = 0;
2813 // If no more than two elements come from either vector. This can be
2814 // implemented with two shuffles. First shuffle gather the elements.
2815 // The second shuffle, which takes the first shuffle as both of its
2816 // vector operands, put the elements into the right order.
2817 for (unsigned i = 0; i != NumElems; ++i) {
2818 SDOperand Elt = PermMask.getOperand(i);
2819 if (Elt.getOpcode() == ISD::UNDEF) {
2820 Locs[i] = std::make_pair(-1, -1);
2821 } else {
2822 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
2823 if (Val < NumElems) {
2824 Locs[i] = std::make_pair(0, NumLo);
2825 Mask1[NumLo] = Elt;
2826 NumLo++;
2827 } else {
2828 Locs[i] = std::make_pair(1, NumHi);
2829 if (2+NumHi < NumElems)
2830 Mask1[2+NumHi] = Elt;
2831 NumHi++;
2832 }
2833 }
2834 }
2835 if (NumLo <= 2 && NumHi <= 2) {
2836 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2837 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2838 &Mask1[0], Mask1.size()));
2839 for (unsigned i = 0; i != NumElems; ++i) {
2840 if (Locs[i].first == -1)
2841 continue;
2842 else {
2843 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
2844 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
2845 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
2846 }
2847 }
2848
2849 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
2850 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2851 &Mask2[0], Mask2.size()));
2852 }
2853
2854 // Break it into (shuffle shuffle_hi, shuffle_lo).
2855 Locs.clear();
2856 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2857 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2858 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
2859 unsigned MaskIdx = 0;
2860 unsigned LoIdx = 0;
2861 unsigned HiIdx = NumElems/2;
2862 for (unsigned i = 0; i != NumElems; ++i) {
2863 if (i == NumElems/2) {
2864 MaskPtr = &HiMask;
2865 MaskIdx = 1;
2866 LoIdx = 0;
2867 HiIdx = NumElems/2;
2868 }
2869 SDOperand Elt = PermMask.getOperand(i);
2870 if (Elt.getOpcode() == ISD::UNDEF) {
2871 Locs[i] = std::make_pair(-1, -1);
2872 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
2873 Locs[i] = std::make_pair(MaskIdx, LoIdx);
2874 (*MaskPtr)[LoIdx] = Elt;
2875 LoIdx++;
2876 } else {
2877 Locs[i] = std::make_pair(MaskIdx, HiIdx);
2878 (*MaskPtr)[HiIdx] = Elt;
2879 HiIdx++;
2880 }
2881 }
2882
2883 SDOperand LoShuffle =
2884 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2885 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2886 &LoMask[0], LoMask.size()));
2887 SDOperand HiShuffle =
2888 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2889 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2890 &HiMask[0], HiMask.size()));
2891 SmallVector<SDOperand, 8> MaskOps;
2892 for (unsigned i = 0; i != NumElems; ++i) {
2893 if (Locs[i].first == -1) {
2894 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
2895 } else {
2896 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
2897 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
2898 }
2899 }
2900 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
2901 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2902 &MaskOps[0], MaskOps.size()));
2903 }
2904
2905 return SDOperand();
2906}
2907
2908SDOperand
2909X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2910 if (!isa<ConstantSDNode>(Op.getOperand(1)))
2911 return SDOperand();
2912
2913 MVT::ValueType VT = Op.getValueType();
2914 // TODO: handle v16i8.
2915 if (MVT::getSizeInBits(VT) == 16) {
2916 // Transform it so it match pextrw which produces a 32-bit result.
2917 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
2918 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
2919 Op.getOperand(0), Op.getOperand(1));
2920 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
2921 DAG.getValueType(VT));
2922 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
2923 } else if (MVT::getSizeInBits(VT) == 32) {
2924 SDOperand Vec = Op.getOperand(0);
2925 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2926 if (Idx == 0)
2927 return Op;
2928 // SHUFPS the element to the lowest double word, then movss.
2929 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2930 SmallVector<SDOperand, 8> IdxVec;
2931 IdxVec.push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
2932 IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
2933 IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
2934 IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
2935 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2936 &IdxVec[0], IdxVec.size());
2937 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2938 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
2939 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2940 DAG.getConstant(0, getPointerTy()));
2941 } else if (MVT::getSizeInBits(VT) == 64) {
2942 SDOperand Vec = Op.getOperand(0);
2943 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2944 if (Idx == 0)
2945 return Op;
2946
2947 // UNPCKHPD the element to the lowest double word, then movsd.
2948 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
2949 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
2950 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2951 SmallVector<SDOperand, 8> IdxVec;
2952 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
2953 IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
2954 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2955 &IdxVec[0], IdxVec.size());
2956 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2957 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
2958 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2959 DAG.getConstant(0, getPointerTy()));
2960 }
2961
2962 return SDOperand();
2963}
2964
2965SDOperand
2966X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2967 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
2968 // as its second argument.
2969 MVT::ValueType VT = Op.getValueType();
2970 MVT::ValueType BaseVT = MVT::getVectorElementType(VT);
2971 SDOperand N0 = Op.getOperand(0);
2972 SDOperand N1 = Op.getOperand(1);
2973 SDOperand N2 = Op.getOperand(2);
2974 if (MVT::getSizeInBits(BaseVT) == 16) {
2975 if (N1.getValueType() != MVT::i32)
2976 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
2977 if (N2.getValueType() != MVT::i32)
2978 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
2979 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
2980 } else if (MVT::getSizeInBits(BaseVT) == 32) {
2981 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
2982 if (Idx == 0) {
2983 // Use a movss.
2984 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
2985 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2986 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2987 SmallVector<SDOperand, 8> MaskVec;
2988 MaskVec.push_back(DAG.getConstant(4, BaseVT));
2989 for (unsigned i = 1; i <= 3; ++i)
2990 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2991 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
2992 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2993 &MaskVec[0], MaskVec.size()));
2994 } else {
2995 // Use two pinsrw instructions to insert a 32 bit value.
2996 Idx <<= 1;
2997 if (MVT::isFloatingPoint(N1.getValueType())) {
2998 if (ISD::isNON_EXTLoad(N1.Val)) {
2999 // Just load directly from f32mem to GR32.
3000 LoadSDNode *LD = cast<LoadSDNode>(N1);
3001 N1 = DAG.getLoad(MVT::i32, LD->getChain(), LD->getBasePtr(),
3002 LD->getSrcValue(), LD->getSrcValueOffset());
3003 } else {
3004 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
3005 N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
3006 N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
3007 DAG.getConstant(0, getPointerTy()));
3008 }
3009 }
3010 N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
3011 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3012 DAG.getConstant(Idx, getPointerTy()));
3013 N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
3014 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3015 DAG.getConstant(Idx+1, getPointerTy()));
3016 return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3017 }
3018 }
3019
3020 return SDOperand();
3021}
3022
3023SDOperand
3024X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3025 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3026 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3027}
3028
3029// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3030// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3031// one of the above mentioned nodes. It has to be wrapped because otherwise
3032// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3033// be used to form addressing mode. These wrapped nodes will be selected
3034// into MOV32ri.
3035SDOperand
3036X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3037 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3038 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3039 getPointerTy(),
3040 CP->getAlignment());
3041 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3042 // With PIC, the address is actually $g + Offset.
3043 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3044 !Subtarget->isPICStyleRIPRel()) {
3045 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3046 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3047 Result);
3048 }
3049
3050 return Result;
3051}
3052
3053SDOperand
3054X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3055 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3056 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3057 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3058 // With PIC, the address is actually $g + Offset.
3059 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3060 !Subtarget->isPICStyleRIPRel()) {
3061 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3062 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3063 Result);
3064 }
3065
3066 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3067 // load the value at address GV, not the value of GV itself. This means that
3068 // the GlobalAddress must be in the base or index register of the address, not
3069 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3070 // The same applies for external symbols during PIC codegen
3071 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3072 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
3073
3074 return Result;
3075}
3076
3077// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3078static SDOperand
3079LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3080 const MVT::ValueType PtrVT) {
3081 SDOperand InFlag;
3082 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3083 DAG.getNode(X86ISD::GlobalBaseReg,
3084 PtrVT), InFlag);
3085 InFlag = Chain.getValue(1);
3086
3087 // emit leal symbol@TLSGD(,%ebx,1), %eax
3088 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3089 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3090 GA->getValueType(0),
3091 GA->getOffset());
3092 SDOperand Ops[] = { Chain, TGA, InFlag };
3093 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3094 InFlag = Result.getValue(2);
3095 Chain = Result.getValue(1);
3096
3097 // call ___tls_get_addr. This function receives its argument in
3098 // the register EAX.
3099 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3100 InFlag = Chain.getValue(1);
3101
3102 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3103 SDOperand Ops1[] = { Chain,
3104 DAG.getTargetExternalSymbol("___tls_get_addr",
3105 PtrVT),
3106 DAG.getRegister(X86::EAX, PtrVT),
3107 DAG.getRegister(X86::EBX, PtrVT),
3108 InFlag };
3109 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3110 InFlag = Chain.getValue(1);
3111
3112 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3113}
3114
3115// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3116// "local exec" model.
3117static SDOperand
3118LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3119 const MVT::ValueType PtrVT) {
3120 // Get the Thread Pointer
3121 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3122 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3123 // exec)
3124 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3125 GA->getValueType(0),
3126 GA->getOffset());
3127 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3128
3129 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3130 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
3131
3132 // The address of the thread local variable is the add of the thread
3133 // pointer with the offset of the variable.
3134 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3135}
3136
3137SDOperand
3138X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3139 // TODO: implement the "local dynamic" model
3140 // TODO: implement the "initial exec"model for pic executables
3141 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3142 "TLS not implemented for non-ELF and 64-bit targets");
3143 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3144 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3145 // otherwise use the "Local Exec"TLS Model
3146 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3147 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3148 else
3149 return LowerToTLSExecModel(GA, DAG, getPointerTy());
3150}
3151
3152SDOperand
3153X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3154 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3155 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3156 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3157 // With PIC, the address is actually $g + Offset.
3158 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3159 !Subtarget->isPICStyleRIPRel()) {
3160 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3161 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3162 Result);
3163 }
3164
3165 return Result;
3166}
3167
3168SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3169 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3170 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3171 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3172 // With PIC, the address is actually $g + Offset.
3173 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3174 !Subtarget->isPICStyleRIPRel()) {
3175 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3176 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3177 Result);
3178 }
3179
3180 return Result;
3181}
3182
3183SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
3184 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
3185 "Not an i64 shift!");
3186 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
3187 SDOperand ShOpLo = Op.getOperand(0);
3188 SDOperand ShOpHi = Op.getOperand(1);
3189 SDOperand ShAmt = Op.getOperand(2);
3190 SDOperand Tmp1 = isSRA ?
3191 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
3192 DAG.getConstant(0, MVT::i32);
3193
3194 SDOperand Tmp2, Tmp3;
3195 if (Op.getOpcode() == ISD::SHL_PARTS) {
3196 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
3197 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
3198 } else {
3199 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
3200 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
3201 }
3202
3203 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3204 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
3205 DAG.getConstant(32, MVT::i8));
3206 SDOperand COps[]={DAG.getEntryNode(), AndNode, DAG.getConstant(0, MVT::i8)};
3207 SDOperand InFlag = DAG.getNode(X86ISD::CMP, VTs, 2, COps, 3).getValue(1);
3208
3209 SDOperand Hi, Lo;
3210 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3211
3212 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
3213 SmallVector<SDOperand, 4> Ops;
3214 if (Op.getOpcode() == ISD::SHL_PARTS) {
3215 Ops.push_back(Tmp2);
3216 Ops.push_back(Tmp3);
3217 Ops.push_back(CC);
3218 Ops.push_back(InFlag);
3219 Hi = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3220 InFlag = Hi.getValue(1);
3221
3222 Ops.clear();
3223 Ops.push_back(Tmp3);
3224 Ops.push_back(Tmp1);
3225 Ops.push_back(CC);
3226 Ops.push_back(InFlag);
3227 Lo = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3228 } else {
3229 Ops.push_back(Tmp2);
3230 Ops.push_back(Tmp3);
3231 Ops.push_back(CC);
3232 Ops.push_back(InFlag);
3233 Lo = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3234 InFlag = Lo.getValue(1);
3235
3236 Ops.clear();
3237 Ops.push_back(Tmp3);
3238 Ops.push_back(Tmp1);
3239 Ops.push_back(CC);
3240 Ops.push_back(InFlag);
3241 Hi = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3242 }
3243
3244 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
3245 Ops.clear();
3246 Ops.push_back(Lo);
3247 Ops.push_back(Hi);
3248 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
3249}
3250
3251SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
3252 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
3253 Op.getOperand(0).getValueType() >= MVT::i16 &&
3254 "Unknown SINT_TO_FP to lower!");
3255
3256 SDOperand Result;
3257 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
3258 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
3259 MachineFunction &MF = DAG.getMachineFunction();
3260 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
3261 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3262 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
3263 StackSlot, NULL, 0);
3264
3265 // Build the FILD
3266 SDVTList Tys;
3267 if (X86ScalarSSE)
3268 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
3269 else
3270 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
3271 SmallVector<SDOperand, 8> Ops;
3272 Ops.push_back(Chain);
3273 Ops.push_back(StackSlot);
3274 Ops.push_back(DAG.getValueType(SrcVT));
3275 Result = DAG.getNode(X86ScalarSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
3276 Tys, &Ops[0], Ops.size());
3277
3278 if (X86ScalarSSE) {
3279 Chain = Result.getValue(1);
3280 SDOperand InFlag = Result.getValue(2);
3281
3282 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
3283 // shouldn't be necessary except that RFP cannot be live across
3284 // multiple blocks. When stackifier is fixed, they can be uncoupled.
3285 MachineFunction &MF = DAG.getMachineFunction();
3286 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3287 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3288 Tys = DAG.getVTList(MVT::Other);
3289 SmallVector<SDOperand, 8> Ops;
3290 Ops.push_back(Chain);
3291 Ops.push_back(Result);
3292 Ops.push_back(StackSlot);
3293 Ops.push_back(DAG.getValueType(Op.getValueType()));
3294 Ops.push_back(InFlag);
3295 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
3296 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
3297 }
3298
3299 return Result;
3300}
3301
3302SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
3303 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
3304 "Unknown FP_TO_SINT to lower!");
3305 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
3306 // stack slot.
3307 MachineFunction &MF = DAG.getMachineFunction();
3308 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
3309 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3310 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3311
3312 unsigned Opc;
3313 switch (Op.getValueType()) {
3314 default: assert(0 && "Invalid FP_TO_SINT to lower!");
3315 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
3316 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
3317 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
3318 }
3319
3320 SDOperand Chain = DAG.getEntryNode();
3321 SDOperand Value = Op.getOperand(0);
3322 if (X86ScalarSSE) {
3323 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
3324 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
3325 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
3326 SDOperand Ops[] = {
3327 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
3328 };
3329 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
3330 Chain = Value.getValue(1);
3331 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3332 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3333 }
3334
3335 // Build the FP_TO_INT*_IN_MEM
3336 SDOperand Ops[] = { Chain, Value, StackSlot };
3337 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
3338
3339 // Load the result.
3340 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
3341}
3342
3343SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
3344 MVT::ValueType VT = Op.getValueType();
3345 MVT::ValueType EltVT = VT;
3346 if (MVT::isVector(VT))
3347 EltVT = MVT::getVectorElementType(VT);
3348 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
3349 std::vector<Constant*> CV;
3350 if (EltVT == MVT::f64) {
3351 Constant *C = ConstantFP::get(OpNTy, BitsToDouble(~(1ULL << 63)));
3352 CV.push_back(C);
3353 CV.push_back(C);
3354 } else {
3355 Constant *C = ConstantFP::get(OpNTy, BitsToFloat(~(1U << 31)));
3356 CV.push_back(C);
3357 CV.push_back(C);
3358 CV.push_back(C);
3359 CV.push_back(C);
3360 }
3361 Constant *CS = ConstantStruct::get(CV);
3362 SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3363 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
3364 SmallVector<SDOperand, 3> Ops;
3365 Ops.push_back(DAG.getEntryNode());
3366 Ops.push_back(CPIdx);
3367 Ops.push_back(DAG.getSrcValue(NULL));
3368 SDOperand Mask = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3369 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
3370}
3371
3372SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
3373 MVT::ValueType VT = Op.getValueType();
3374 MVT::ValueType EltVT = VT;
Evan Cheng92b8f782007-07-19 23:36:01 +00003375 unsigned EltNum = 1;
3376 if (MVT::isVector(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003377 EltVT = MVT::getVectorElementType(VT);
Evan Cheng92b8f782007-07-19 23:36:01 +00003378 EltNum = MVT::getVectorNumElements(VT);
3379 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003380 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
3381 std::vector<Constant*> CV;
3382 if (EltVT == MVT::f64) {
3383 Constant *C = ConstantFP::get(OpNTy, BitsToDouble(1ULL << 63));
3384 CV.push_back(C);
3385 CV.push_back(C);
3386 } else {
3387 Constant *C = ConstantFP::get(OpNTy, BitsToFloat(1U << 31));
3388 CV.push_back(C);
3389 CV.push_back(C);
3390 CV.push_back(C);
3391 CV.push_back(C);
3392 }
3393 Constant *CS = ConstantStruct::get(CV);
3394 SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
Evan Cheng92b8f782007-07-19 23:36:01 +00003395 if (MVT::isVector(VT)) {
3396 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0);
3397 return DAG.getNode(ISD::BIT_CONVERT, VT,
3398 DAG.getNode(ISD::XOR, MVT::v2i64,
3399 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
3400 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
3401 } else {
3402 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
3403 SmallVector<SDOperand, 3> Ops;
3404 Ops.push_back(DAG.getEntryNode());
3405 Ops.push_back(CPIdx);
3406 Ops.push_back(DAG.getSrcValue(NULL));
3407 SDOperand Mask = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3408 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
3409 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003410}
3411
3412SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
3413 SDOperand Op0 = Op.getOperand(0);
3414 SDOperand Op1 = Op.getOperand(1);
3415 MVT::ValueType VT = Op.getValueType();
3416 MVT::ValueType SrcVT = Op1.getValueType();
3417 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
3418
3419 // If second operand is smaller, extend it first.
3420 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
3421 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
3422 SrcVT = VT;
3423 }
3424
3425 // First get the sign bit of second operand.
3426 std::vector<Constant*> CV;
3427 if (SrcVT == MVT::f64) {
3428 CV.push_back(ConstantFP::get(SrcTy, BitsToDouble(1ULL << 63)));
3429 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3430 } else {
3431 CV.push_back(ConstantFP::get(SrcTy, BitsToFloat(1U << 31)));
3432 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3433 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3434 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3435 }
3436 Constant *CS = ConstantStruct::get(CV);
3437 SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3438 SDVTList Tys = DAG.getVTList(SrcVT, MVT::Other);
3439 SmallVector<SDOperand, 3> Ops;
3440 Ops.push_back(DAG.getEntryNode());
3441 Ops.push_back(CPIdx);
3442 Ops.push_back(DAG.getSrcValue(NULL));
3443 SDOperand Mask1 = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3444 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
3445
3446 // Shift sign bit right or left if the two operands have different types.
3447 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
3448 // Op0 is MVT::f32, Op1 is MVT::f64.
3449 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
3450 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
3451 DAG.getConstant(32, MVT::i32));
3452 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
3453 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
3454 DAG.getConstant(0, getPointerTy()));
3455 }
3456
3457 // Clear first operand sign bit.
3458 CV.clear();
3459 if (VT == MVT::f64) {
3460 CV.push_back(ConstantFP::get(SrcTy, BitsToDouble(~(1ULL << 63))));
3461 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3462 } else {
3463 CV.push_back(ConstantFP::get(SrcTy, BitsToFloat(~(1U << 31))));
3464 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3465 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3466 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3467 }
3468 CS = ConstantStruct::get(CV);
3469 CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3470 Tys = DAG.getVTList(VT, MVT::Other);
3471 Ops.clear();
3472 Ops.push_back(DAG.getEntryNode());
3473 Ops.push_back(CPIdx);
3474 Ops.push_back(DAG.getSrcValue(NULL));
3475 SDOperand Mask2 = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3476 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
3477
3478 // Or the value with the sign bit.
3479 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
3480}
3481
3482SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG,
3483 SDOperand Chain) {
3484 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
3485 SDOperand Cond;
3486 SDOperand Op0 = Op.getOperand(0);
3487 SDOperand Op1 = Op.getOperand(1);
3488 SDOperand CC = Op.getOperand(2);
3489 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3490 const MVT::ValueType *VTs1 = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3491 const MVT::ValueType *VTs2 = DAG.getNodeValueTypes(MVT::i8, MVT::Flag);
3492 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
3493 unsigned X86CC;
3494
3495 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
3496 Op0, Op1, DAG)) {
3497 SDOperand Ops1[] = { Chain, Op0, Op1 };
3498 Cond = DAG.getNode(X86ISD::CMP, VTs1, 2, Ops1, 3).getValue(1);
3499 SDOperand Ops2[] = { DAG.getConstant(X86CC, MVT::i8), Cond };
3500 return DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3501 }
3502
3503 assert(isFP && "Illegal integer SetCC!");
3504
3505 SDOperand COps[] = { Chain, Op0, Op1 };
3506 Cond = DAG.getNode(X86ISD::CMP, VTs1, 2, COps, 3).getValue(1);
3507
3508 switch (SetCCOpcode) {
3509 default: assert(false && "Illegal floating point SetCC!");
3510 case ISD::SETOEQ: { // !PF & ZF
3511 SDOperand Ops1[] = { DAG.getConstant(X86::COND_NP, MVT::i8), Cond };
3512 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops1, 2);
3513 SDOperand Ops2[] = { DAG.getConstant(X86::COND_E, MVT::i8),
3514 Tmp1.getValue(1) };
3515 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3516 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
3517 }
3518 case ISD::SETUNE: { // PF | !ZF
3519 SDOperand Ops1[] = { DAG.getConstant(X86::COND_P, MVT::i8), Cond };
3520 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops1, 2);
3521 SDOperand Ops2[] = { DAG.getConstant(X86::COND_NE, MVT::i8),
3522 Tmp1.getValue(1) };
3523 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3524 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
3525 }
3526 }
3527}
3528
3529SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
3530 bool addTest = true;
3531 SDOperand Chain = DAG.getEntryNode();
3532 SDOperand Cond = Op.getOperand(0);
3533 SDOperand CC;
3534 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3535
3536 if (Cond.getOpcode() == ISD::SETCC)
3537 Cond = LowerSETCC(Cond, DAG, Chain);
3538
3539 if (Cond.getOpcode() == X86ISD::SETCC) {
3540 CC = Cond.getOperand(0);
3541
3542 // If condition flag is set by a X86ISD::CMP, then make a copy of it
3543 // (since flag operand cannot be shared). Use it as the condition setting
3544 // operand in place of the X86ISD::SETCC.
3545 // If the X86ISD::SETCC has more than one use, then perhaps it's better
3546 // to use a test instead of duplicating the X86ISD::CMP (for register
3547 // pressure reason)?
3548 SDOperand Cmp = Cond.getOperand(1);
3549 unsigned Opc = Cmp.getOpcode();
3550 bool IllegalFPCMov = !X86ScalarSSE &&
3551 MVT::isFloatingPoint(Op.getValueType()) &&
3552 !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
3553 if ((Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) &&
3554 !IllegalFPCMov) {
3555 SDOperand Ops[] = { Chain, Cmp.getOperand(1), Cmp.getOperand(2) };
3556 Cond = DAG.getNode(Opc, VTs, 2, Ops, 3);
3557 addTest = false;
3558 }
3559 }
3560
3561 if (addTest) {
3562 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3563 SDOperand Ops[] = { Chain, Cond, DAG.getConstant(0, MVT::i8) };
3564 Cond = DAG.getNode(X86ISD::CMP, VTs, 2, Ops, 3);
3565 }
3566
3567 VTs = DAG.getNodeValueTypes(Op.getValueType(), MVT::Flag);
3568 SmallVector<SDOperand, 4> Ops;
3569 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
3570 // condition is true.
3571 Ops.push_back(Op.getOperand(2));
3572 Ops.push_back(Op.getOperand(1));
3573 Ops.push_back(CC);
3574 Ops.push_back(Cond.getValue(1));
3575 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3576}
3577
3578SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
3579 bool addTest = true;
3580 SDOperand Chain = Op.getOperand(0);
3581 SDOperand Cond = Op.getOperand(1);
3582 SDOperand Dest = Op.getOperand(2);
3583 SDOperand CC;
3584 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3585
3586 if (Cond.getOpcode() == ISD::SETCC)
3587 Cond = LowerSETCC(Cond, DAG, Chain);
3588
3589 if (Cond.getOpcode() == X86ISD::SETCC) {
3590 CC = Cond.getOperand(0);
3591
3592 // If condition flag is set by a X86ISD::CMP, then make a copy of it
3593 // (since flag operand cannot be shared). Use it as the condition setting
3594 // operand in place of the X86ISD::SETCC.
3595 // If the X86ISD::SETCC has more than one use, then perhaps it's better
3596 // to use a test instead of duplicating the X86ISD::CMP (for register
3597 // pressure reason)?
3598 SDOperand Cmp = Cond.getOperand(1);
3599 unsigned Opc = Cmp.getOpcode();
3600 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) {
3601 SDOperand Ops[] = { Chain, Cmp.getOperand(1), Cmp.getOperand(2) };
3602 Cond = DAG.getNode(Opc, VTs, 2, Ops, 3);
3603 addTest = false;
3604 }
3605 }
3606
3607 if (addTest) {
3608 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3609 SDOperand Ops[] = { Chain, Cond, DAG.getConstant(0, MVT::i8) };
3610 Cond = DAG.getNode(X86ISD::CMP, VTs, 2, Ops, 3);
3611 }
3612 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
3613 Cond, Op.getOperand(2), CC, Cond.getValue(1));
3614}
3615
3616SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
3617 unsigned CallingConv= cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3618
3619 if (Subtarget->is64Bit())
3620 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
3621 else
3622 switch (CallingConv) {
3623 default:
3624 assert(0 && "Unsupported calling convention");
3625 case CallingConv::Fast:
3626 // TODO: Implement fastcc
3627 // Falls through
3628 case CallingConv::C:
3629 case CallingConv::X86_StdCall:
3630 return LowerCCCCallTo(Op, DAG, CallingConv);
3631 case CallingConv::X86_FastCall:
3632 return LowerFastCCCallTo(Op, DAG, CallingConv);
3633 }
3634}
3635
3636
3637// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
3638// Calls to _alloca is needed to probe the stack when allocating more than 4k
3639// bytes in one go. Touching the stack at 4K increments is necessary to ensure
3640// that the guard pages used by the OS virtual memory manager are allocated in
3641// correct sequence.
3642SDOperand
3643X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
3644 SelectionDAG &DAG) {
3645 assert(Subtarget->isTargetCygMing() &&
3646 "This should be used only on Cygwin/Mingw targets");
3647
3648 // Get the inputs.
3649 SDOperand Chain = Op.getOperand(0);
3650 SDOperand Size = Op.getOperand(1);
3651 // FIXME: Ensure alignment here
3652
3653 SDOperand Flag;
3654
3655 MVT::ValueType IntPtr = getPointerTy();
3656 MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
3657
3658 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
3659 Flag = Chain.getValue(1);
3660
3661 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3662 SDOperand Ops[] = { Chain,
3663 DAG.getTargetExternalSymbol("_alloca", IntPtr),
3664 DAG.getRegister(X86::EAX, IntPtr),
3665 Flag };
3666 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
3667 Flag = Chain.getValue(1);
3668
3669 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
3670
3671 std::vector<MVT::ValueType> Tys;
3672 Tys.push_back(SPTy);
3673 Tys.push_back(MVT::Other);
3674 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
3675 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
3676}
3677
3678SDOperand
3679X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
3680 MachineFunction &MF = DAG.getMachineFunction();
3681 const Function* Fn = MF.getFunction();
3682 if (Fn->hasExternalLinkage() &&
3683 Subtarget->isTargetCygMing() &&
3684 Fn->getName() == "main")
3685 MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
3686
3687 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3688 if (Subtarget->is64Bit())
3689 return LowerX86_64CCCArguments(Op, DAG);
3690 else
3691 switch(CC) {
3692 default:
3693 assert(0 && "Unsupported calling convention");
3694 case CallingConv::Fast:
3695 // TODO: implement fastcc.
3696
3697 // Falls through
3698 case CallingConv::C:
3699 return LowerCCCArguments(Op, DAG);
3700 case CallingConv::X86_StdCall:
3701 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
3702 return LowerCCCArguments(Op, DAG, true);
3703 case CallingConv::X86_FastCall:
3704 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
3705 return LowerFastCCArguments(Op, DAG);
3706 }
3707}
3708
3709SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
3710 SDOperand InFlag(0, 0);
3711 SDOperand Chain = Op.getOperand(0);
3712 unsigned Align =
3713 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3714 if (Align == 0) Align = 1;
3715
3716 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3717 // If not DWORD aligned, call memset if size is less than the threshold.
3718 // It knows how to align to the right boundary first.
3719 if ((Align & 3) != 0 ||
3720 (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3721 MVT::ValueType IntPtr = getPointerTy();
3722 const Type *IntPtrTy = getTargetData()->getIntPtrType();
3723 TargetLowering::ArgListTy Args;
3724 TargetLowering::ArgListEntry Entry;
3725 Entry.Node = Op.getOperand(1);
3726 Entry.Ty = IntPtrTy;
3727 Args.push_back(Entry);
3728 // Extend the unsigned i8 argument to be an int value for the call.
3729 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
3730 Entry.Ty = IntPtrTy;
3731 Args.push_back(Entry);
3732 Entry.Node = Op.getOperand(3);
3733 Args.push_back(Entry);
3734 std::pair<SDOperand,SDOperand> CallResult =
3735 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
3736 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
3737 return CallResult.second;
3738 }
3739
3740 MVT::ValueType AVT;
3741 SDOperand Count;
3742 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3743 unsigned BytesLeft = 0;
3744 bool TwoRepStos = false;
3745 if (ValC) {
3746 unsigned ValReg;
3747 uint64_t Val = ValC->getValue() & 255;
3748
3749 // If the value is a constant, then we can potentially use larger sets.
3750 switch (Align & 3) {
3751 case 2: // WORD aligned
3752 AVT = MVT::i16;
3753 ValReg = X86::AX;
3754 Val = (Val << 8) | Val;
3755 break;
3756 case 0: // DWORD aligned
3757 AVT = MVT::i32;
3758 ValReg = X86::EAX;
3759 Val = (Val << 8) | Val;
3760 Val = (Val << 16) | Val;
3761 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
3762 AVT = MVT::i64;
3763 ValReg = X86::RAX;
3764 Val = (Val << 32) | Val;
3765 }
3766 break;
3767 default: // Byte aligned
3768 AVT = MVT::i8;
3769 ValReg = X86::AL;
3770 Count = Op.getOperand(3);
3771 break;
3772 }
3773
3774 if (AVT > MVT::i8) {
3775 if (I) {
3776 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
3777 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
3778 BytesLeft = I->getValue() % UBytes;
3779 } else {
3780 assert(AVT >= MVT::i32 &&
3781 "Do not use rep;stos if not at least DWORD aligned");
3782 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
3783 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
3784 TwoRepStos = true;
3785 }
3786 }
3787
3788 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
3789 InFlag);
3790 InFlag = Chain.getValue(1);
3791 } else {
3792 AVT = MVT::i8;
3793 Count = Op.getOperand(3);
3794 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
3795 InFlag = Chain.getValue(1);
3796 }
3797
3798 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
3799 Count, InFlag);
3800 InFlag = Chain.getValue(1);
3801 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
3802 Op.getOperand(1), InFlag);
3803 InFlag = Chain.getValue(1);
3804
3805 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3806 SmallVector<SDOperand, 8> Ops;
3807 Ops.push_back(Chain);
3808 Ops.push_back(DAG.getValueType(AVT));
3809 Ops.push_back(InFlag);
3810 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
3811
3812 if (TwoRepStos) {
3813 InFlag = Chain.getValue(1);
3814 Count = Op.getOperand(3);
3815 MVT::ValueType CVT = Count.getValueType();
3816 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3817 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
3818 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
3819 Left, InFlag);
3820 InFlag = Chain.getValue(1);
3821 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3822 Ops.clear();
3823 Ops.push_back(Chain);
3824 Ops.push_back(DAG.getValueType(MVT::i8));
3825 Ops.push_back(InFlag);
3826 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
3827 } else if (BytesLeft) {
3828 // Issue stores for the last 1 - 7 bytes.
3829 SDOperand Value;
3830 unsigned Val = ValC->getValue() & 255;
3831 unsigned Offset = I->getValue() - BytesLeft;
3832 SDOperand DstAddr = Op.getOperand(1);
3833 MVT::ValueType AddrVT = DstAddr.getValueType();
3834 if (BytesLeft >= 4) {
3835 Val = (Val << 8) | Val;
3836 Val = (Val << 16) | Val;
3837 Value = DAG.getConstant(Val, MVT::i32);
3838 Chain = DAG.getStore(Chain, Value,
3839 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3840 DAG.getConstant(Offset, AddrVT)),
3841 NULL, 0);
3842 BytesLeft -= 4;
3843 Offset += 4;
3844 }
3845 if (BytesLeft >= 2) {
3846 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
3847 Chain = DAG.getStore(Chain, Value,
3848 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3849 DAG.getConstant(Offset, AddrVT)),
3850 NULL, 0);
3851 BytesLeft -= 2;
3852 Offset += 2;
3853 }
3854 if (BytesLeft == 1) {
3855 Value = DAG.getConstant(Val, MVT::i8);
3856 Chain = DAG.getStore(Chain, Value,
3857 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3858 DAG.getConstant(Offset, AddrVT)),
3859 NULL, 0);
3860 }
3861 }
3862
3863 return Chain;
3864}
3865
3866SDOperand X86TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
3867 SDOperand Chain = Op.getOperand(0);
3868 unsigned Align =
3869 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3870 if (Align == 0) Align = 1;
3871
3872 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3873 // If not DWORD aligned, call memcpy if size is less than the threshold.
3874 // It knows how to align to the right boundary first.
3875 if ((Align & 3) != 0 ||
3876 (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3877 MVT::ValueType IntPtr = getPointerTy();
3878 TargetLowering::ArgListTy Args;
3879 TargetLowering::ArgListEntry Entry;
3880 Entry.Ty = getTargetData()->getIntPtrType();
3881 Entry.Node = Op.getOperand(1); Args.push_back(Entry);
3882 Entry.Node = Op.getOperand(2); Args.push_back(Entry);
3883 Entry.Node = Op.getOperand(3); Args.push_back(Entry);
3884 std::pair<SDOperand,SDOperand> CallResult =
3885 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
3886 DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
3887 return CallResult.second;
3888 }
3889
3890 MVT::ValueType AVT;
3891 SDOperand Count;
3892 unsigned BytesLeft = 0;
3893 bool TwoRepMovs = false;
3894 switch (Align & 3) {
3895 case 2: // WORD aligned
3896 AVT = MVT::i16;
3897 break;
3898 case 0: // DWORD aligned
3899 AVT = MVT::i32;
3900 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
3901 AVT = MVT::i64;
3902 break;
3903 default: // Byte aligned
3904 AVT = MVT::i8;
3905 Count = Op.getOperand(3);
3906 break;
3907 }
3908
3909 if (AVT > MVT::i8) {
3910 if (I) {
3911 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
3912 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
3913 BytesLeft = I->getValue() % UBytes;
3914 } else {
3915 assert(AVT >= MVT::i32 &&
3916 "Do not use rep;movs if not at least DWORD aligned");
3917 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
3918 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
3919 TwoRepMovs = true;
3920 }
3921 }
3922
3923 SDOperand InFlag(0, 0);
3924 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
3925 Count, InFlag);
3926 InFlag = Chain.getValue(1);
3927 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
3928 Op.getOperand(1), InFlag);
3929 InFlag = Chain.getValue(1);
3930 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
3931 Op.getOperand(2), InFlag);
3932 InFlag = Chain.getValue(1);
3933
3934 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3935 SmallVector<SDOperand, 8> Ops;
3936 Ops.push_back(Chain);
3937 Ops.push_back(DAG.getValueType(AVT));
3938 Ops.push_back(InFlag);
3939 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
3940
3941 if (TwoRepMovs) {
3942 InFlag = Chain.getValue(1);
3943 Count = Op.getOperand(3);
3944 MVT::ValueType CVT = Count.getValueType();
3945 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3946 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
3947 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
3948 Left, InFlag);
3949 InFlag = Chain.getValue(1);
3950 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3951 Ops.clear();
3952 Ops.push_back(Chain);
3953 Ops.push_back(DAG.getValueType(MVT::i8));
3954 Ops.push_back(InFlag);
3955 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
3956 } else if (BytesLeft) {
3957 // Issue loads and stores for the last 1 - 7 bytes.
3958 unsigned Offset = I->getValue() - BytesLeft;
3959 SDOperand DstAddr = Op.getOperand(1);
3960 MVT::ValueType DstVT = DstAddr.getValueType();
3961 SDOperand SrcAddr = Op.getOperand(2);
3962 MVT::ValueType SrcVT = SrcAddr.getValueType();
3963 SDOperand Value;
3964 if (BytesLeft >= 4) {
3965 Value = DAG.getLoad(MVT::i32, Chain,
3966 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3967 DAG.getConstant(Offset, SrcVT)),
3968 NULL, 0);
3969 Chain = Value.getValue(1);
3970 Chain = DAG.getStore(Chain, Value,
3971 DAG.getNode(ISD::ADD, DstVT, DstAddr,
3972 DAG.getConstant(Offset, DstVT)),
3973 NULL, 0);
3974 BytesLeft -= 4;
3975 Offset += 4;
3976 }
3977 if (BytesLeft >= 2) {
3978 Value = DAG.getLoad(MVT::i16, Chain,
3979 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3980 DAG.getConstant(Offset, SrcVT)),
3981 NULL, 0);
3982 Chain = Value.getValue(1);
3983 Chain = DAG.getStore(Chain, Value,
3984 DAG.getNode(ISD::ADD, DstVT, DstAddr,
3985 DAG.getConstant(Offset, DstVT)),
3986 NULL, 0);
3987 BytesLeft -= 2;
3988 Offset += 2;
3989 }
3990
3991 if (BytesLeft == 1) {
3992 Value = DAG.getLoad(MVT::i8, Chain,
3993 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3994 DAG.getConstant(Offset, SrcVT)),
3995 NULL, 0);
3996 Chain = Value.getValue(1);
3997 Chain = DAG.getStore(Chain, Value,
3998 DAG.getNode(ISD::ADD, DstVT, DstAddr,
3999 DAG.getConstant(Offset, DstVT)),
4000 NULL, 0);
4001 }
4002 }
4003
4004 return Chain;
4005}
4006
4007SDOperand
4008X86TargetLowering::LowerREADCYCLCECOUNTER(SDOperand Op, SelectionDAG &DAG) {
4009 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4010 SDOperand TheOp = Op.getOperand(0);
4011 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheOp, 1);
4012 if (Subtarget->is64Bit()) {
4013 SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4014 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::RDX,
4015 MVT::i64, Copy1.getValue(2));
4016 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, Copy2,
4017 DAG.getConstant(32, MVT::i8));
4018 SDOperand Ops[] = {
4019 DAG.getNode(ISD::OR, MVT::i64, Copy1, Tmp), Copy2.getValue(1)
4020 };
4021
4022 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4023 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2);
4024 }
4025
4026 SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4027 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::EDX,
4028 MVT::i32, Copy1.getValue(2));
4029 SDOperand Ops[] = { Copy1, Copy2, Copy2.getValue(1) };
4030 Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
4031 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 3);
4032}
4033
4034SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4035 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
4036
4037 if (!Subtarget->is64Bit()) {
4038 // vastart just stores the address of the VarArgsFrameIndex slot into the
4039 // memory location argument.
4040 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4041 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
4042 SV->getOffset());
4043 }
4044
4045 // __va_list_tag:
4046 // gp_offset (0 - 6 * 8)
4047 // fp_offset (48 - 48 + 8 * 16)
4048 // overflow_arg_area (point to parameters coming in memory).
4049 // reg_save_area
4050 SmallVector<SDOperand, 8> MemOps;
4051 SDOperand FIN = Op.getOperand(1);
4052 // Store gp_offset
4053 SDOperand Store = DAG.getStore(Op.getOperand(0),
4054 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4055 FIN, SV->getValue(), SV->getOffset());
4056 MemOps.push_back(Store);
4057
4058 // Store fp_offset
4059 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4060 DAG.getConstant(4, getPointerTy()));
4061 Store = DAG.getStore(Op.getOperand(0),
4062 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4063 FIN, SV->getValue(), SV->getOffset());
4064 MemOps.push_back(Store);
4065
4066 // Store ptr to overflow_arg_area
4067 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4068 DAG.getConstant(4, getPointerTy()));
4069 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4070 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
4071 SV->getOffset());
4072 MemOps.push_back(Store);
4073
4074 // Store ptr to reg_save_area.
4075 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4076 DAG.getConstant(8, getPointerTy()));
4077 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4078 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
4079 SV->getOffset());
4080 MemOps.push_back(Store);
4081 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4082}
4083
4084SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4085 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4086 SDOperand Chain = Op.getOperand(0);
4087 SDOperand DstPtr = Op.getOperand(1);
4088 SDOperand SrcPtr = Op.getOperand(2);
4089 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
4090 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
4091
4092 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
4093 SrcSV->getValue(), SrcSV->getOffset());
4094 Chain = SrcPtr.getValue(1);
4095 for (unsigned i = 0; i < 3; ++i) {
4096 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
4097 SrcSV->getValue(), SrcSV->getOffset());
4098 Chain = Val.getValue(1);
4099 Chain = DAG.getStore(Chain, Val, DstPtr,
4100 DstSV->getValue(), DstSV->getOffset());
4101 if (i == 2)
4102 break;
4103 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
4104 DAG.getConstant(8, getPointerTy()));
4105 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
4106 DAG.getConstant(8, getPointerTy()));
4107 }
4108 return Chain;
4109}
4110
4111SDOperand
4112X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4113 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4114 switch (IntNo) {
4115 default: return SDOperand(); // Don't custom lower most intrinsics.
4116 // Comparison intrinsics.
4117 case Intrinsic::x86_sse_comieq_ss:
4118 case Intrinsic::x86_sse_comilt_ss:
4119 case Intrinsic::x86_sse_comile_ss:
4120 case Intrinsic::x86_sse_comigt_ss:
4121 case Intrinsic::x86_sse_comige_ss:
4122 case Intrinsic::x86_sse_comineq_ss:
4123 case Intrinsic::x86_sse_ucomieq_ss:
4124 case Intrinsic::x86_sse_ucomilt_ss:
4125 case Intrinsic::x86_sse_ucomile_ss:
4126 case Intrinsic::x86_sse_ucomigt_ss:
4127 case Intrinsic::x86_sse_ucomige_ss:
4128 case Intrinsic::x86_sse_ucomineq_ss:
4129 case Intrinsic::x86_sse2_comieq_sd:
4130 case Intrinsic::x86_sse2_comilt_sd:
4131 case Intrinsic::x86_sse2_comile_sd:
4132 case Intrinsic::x86_sse2_comigt_sd:
4133 case Intrinsic::x86_sse2_comige_sd:
4134 case Intrinsic::x86_sse2_comineq_sd:
4135 case Intrinsic::x86_sse2_ucomieq_sd:
4136 case Intrinsic::x86_sse2_ucomilt_sd:
4137 case Intrinsic::x86_sse2_ucomile_sd:
4138 case Intrinsic::x86_sse2_ucomigt_sd:
4139 case Intrinsic::x86_sse2_ucomige_sd:
4140 case Intrinsic::x86_sse2_ucomineq_sd: {
4141 unsigned Opc = 0;
4142 ISD::CondCode CC = ISD::SETCC_INVALID;
4143 switch (IntNo) {
4144 default: break;
4145 case Intrinsic::x86_sse_comieq_ss:
4146 case Intrinsic::x86_sse2_comieq_sd:
4147 Opc = X86ISD::COMI;
4148 CC = ISD::SETEQ;
4149 break;
4150 case Intrinsic::x86_sse_comilt_ss:
4151 case Intrinsic::x86_sse2_comilt_sd:
4152 Opc = X86ISD::COMI;
4153 CC = ISD::SETLT;
4154 break;
4155 case Intrinsic::x86_sse_comile_ss:
4156 case Intrinsic::x86_sse2_comile_sd:
4157 Opc = X86ISD::COMI;
4158 CC = ISD::SETLE;
4159 break;
4160 case Intrinsic::x86_sse_comigt_ss:
4161 case Intrinsic::x86_sse2_comigt_sd:
4162 Opc = X86ISD::COMI;
4163 CC = ISD::SETGT;
4164 break;
4165 case Intrinsic::x86_sse_comige_ss:
4166 case Intrinsic::x86_sse2_comige_sd:
4167 Opc = X86ISD::COMI;
4168 CC = ISD::SETGE;
4169 break;
4170 case Intrinsic::x86_sse_comineq_ss:
4171 case Intrinsic::x86_sse2_comineq_sd:
4172 Opc = X86ISD::COMI;
4173 CC = ISD::SETNE;
4174 break;
4175 case Intrinsic::x86_sse_ucomieq_ss:
4176 case Intrinsic::x86_sse2_ucomieq_sd:
4177 Opc = X86ISD::UCOMI;
4178 CC = ISD::SETEQ;
4179 break;
4180 case Intrinsic::x86_sse_ucomilt_ss:
4181 case Intrinsic::x86_sse2_ucomilt_sd:
4182 Opc = X86ISD::UCOMI;
4183 CC = ISD::SETLT;
4184 break;
4185 case Intrinsic::x86_sse_ucomile_ss:
4186 case Intrinsic::x86_sse2_ucomile_sd:
4187 Opc = X86ISD::UCOMI;
4188 CC = ISD::SETLE;
4189 break;
4190 case Intrinsic::x86_sse_ucomigt_ss:
4191 case Intrinsic::x86_sse2_ucomigt_sd:
4192 Opc = X86ISD::UCOMI;
4193 CC = ISD::SETGT;
4194 break;
4195 case Intrinsic::x86_sse_ucomige_ss:
4196 case Intrinsic::x86_sse2_ucomige_sd:
4197 Opc = X86ISD::UCOMI;
4198 CC = ISD::SETGE;
4199 break;
4200 case Intrinsic::x86_sse_ucomineq_ss:
4201 case Intrinsic::x86_sse2_ucomineq_sd:
4202 Opc = X86ISD::UCOMI;
4203 CC = ISD::SETNE;
4204 break;
4205 }
4206
4207 unsigned X86CC;
4208 SDOperand LHS = Op.getOperand(1);
4209 SDOperand RHS = Op.getOperand(2);
4210 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4211
4212 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4213 SDOperand Ops1[] = { DAG.getEntryNode(), LHS, RHS };
4214 SDOperand Cond = DAG.getNode(Opc, VTs, 2, Ops1, 3);
4215 VTs = DAG.getNodeValueTypes(MVT::i8, MVT::Flag);
4216 SDOperand Ops2[] = { DAG.getConstant(X86CC, MVT::i8), Cond };
4217 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, VTs, 2, Ops2, 2);
4218 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
4219 }
4220 }
4221}
4222
4223SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4224 // Depths > 0 not supported yet!
4225 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4226 return SDOperand();
4227
4228 // Just load the return address
4229 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4230 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4231}
4232
4233SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4234 // Depths > 0 not supported yet!
4235 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4236 return SDOperand();
4237
4238 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4239 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
4240 DAG.getConstant(4, getPointerTy()));
4241}
4242
4243SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
4244 SelectionDAG &DAG) {
4245 // Is not yet supported on x86-64
4246 if (Subtarget->is64Bit())
4247 return SDOperand();
4248
4249 return DAG.getConstant(8, getPointerTy());
4250}
4251
4252SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
4253{
4254 assert(!Subtarget->is64Bit() &&
4255 "Lowering of eh_return builtin is not supported yet on x86-64");
4256
4257 MachineFunction &MF = DAG.getMachineFunction();
4258 SDOperand Chain = Op.getOperand(0);
4259 SDOperand Offset = Op.getOperand(1);
4260 SDOperand Handler = Op.getOperand(2);
4261
4262 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
4263 getPointerTy());
4264
4265 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
4266 DAG.getConstant(-4UL, getPointerTy()));
4267 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
4268 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
4269 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
4270 MF.addLiveOut(X86::ECX);
4271
4272 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
4273 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
4274}
4275
4276/// LowerOperation - Provide custom lowering hooks for some operations.
4277///
4278SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4279 switch (Op.getOpcode()) {
4280 default: assert(0 && "Should not custom lower this!");
4281 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
4282 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
4283 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4284 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
4285 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
4286 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
4287 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
4288 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
4289 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
4290 case ISD::SHL_PARTS:
4291 case ISD::SRA_PARTS:
4292 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
4293 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
4294 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
4295 case ISD::FABS: return LowerFABS(Op, DAG);
4296 case ISD::FNEG: return LowerFNEG(Op, DAG);
4297 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
4298 case ISD::SETCC: return LowerSETCC(Op, DAG, DAG.getEntryNode());
4299 case ISD::SELECT: return LowerSELECT(Op, DAG);
4300 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4301 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
4302 case ISD::CALL: return LowerCALL(Op, DAG);
4303 case ISD::RET: return LowerRET(Op, DAG);
4304 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
4305 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
4306 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
4307 case ISD::READCYCLECOUNTER: return LowerREADCYCLCECOUNTER(Op, DAG);
4308 case ISD::VASTART: return LowerVASTART(Op, DAG);
4309 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
4310 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4311 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4312 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
4313 case ISD::FRAME_TO_ARGS_OFFSET:
4314 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
4315 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
4316 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
4317 }
4318 return SDOperand();
4319}
4320
4321const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
4322 switch (Opcode) {
4323 default: return NULL;
4324 case X86ISD::SHLD: return "X86ISD::SHLD";
4325 case X86ISD::SHRD: return "X86ISD::SHRD";
4326 case X86ISD::FAND: return "X86ISD::FAND";
4327 case X86ISD::FOR: return "X86ISD::FOR";
4328 case X86ISD::FXOR: return "X86ISD::FXOR";
4329 case X86ISD::FSRL: return "X86ISD::FSRL";
4330 case X86ISD::FILD: return "X86ISD::FILD";
4331 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
4332 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
4333 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
4334 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
4335 case X86ISD::FLD: return "X86ISD::FLD";
4336 case X86ISD::FST: return "X86ISD::FST";
4337 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
4338 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
4339 case X86ISD::CALL: return "X86ISD::CALL";
4340 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
4341 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
4342 case X86ISD::CMP: return "X86ISD::CMP";
4343 case X86ISD::COMI: return "X86ISD::COMI";
4344 case X86ISD::UCOMI: return "X86ISD::UCOMI";
4345 case X86ISD::SETCC: return "X86ISD::SETCC";
4346 case X86ISD::CMOV: return "X86ISD::CMOV";
4347 case X86ISD::BRCOND: return "X86ISD::BRCOND";
4348 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
4349 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
4350 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
4351 case X86ISD::LOAD_PACK: return "X86ISD::LOAD_PACK";
4352 case X86ISD::LOAD_UA: return "X86ISD::LOAD_UA";
4353 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
4354 case X86ISD::Wrapper: return "X86ISD::Wrapper";
4355 case X86ISD::S2VEC: return "X86ISD::S2VEC";
4356 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
4357 case X86ISD::PINSRW: return "X86ISD::PINSRW";
4358 case X86ISD::FMAX: return "X86ISD::FMAX";
4359 case X86ISD::FMIN: return "X86ISD::FMIN";
4360 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
4361 case X86ISD::FRCP: return "X86ISD::FRCP";
4362 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
4363 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
4364 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
4365 }
4366}
4367
4368// isLegalAddressingMode - Return true if the addressing mode represented
4369// by AM is legal for this target, for a load/store of the specified type.
4370bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
4371 const Type *Ty) const {
4372 // X86 supports extremely general addressing modes.
4373
4374 // X86 allows a sign-extended 32-bit immediate field as a displacement.
4375 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
4376 return false;
4377
4378 if (AM.BaseGV) {
4379 // X86-64 only supports addr of globals in small code model.
4380 if (Subtarget->is64Bit() &&
4381 getTargetMachine().getCodeModel() != CodeModel::Small)
4382 return false;
4383
4384 // We can only fold this if we don't need a load either.
4385 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
4386 return false;
4387 }
4388
4389 switch (AM.Scale) {
4390 case 0:
4391 case 1:
4392 case 2:
4393 case 4:
4394 case 8:
4395 // These scales always work.
4396 break;
4397 case 3:
4398 case 5:
4399 case 9:
4400 // These scales are formed with basereg+scalereg. Only accept if there is
4401 // no basereg yet.
4402 if (AM.HasBaseReg)
4403 return false;
4404 break;
4405 default: // Other stuff never works.
4406 return false;
4407 }
4408
4409 return true;
4410}
4411
4412
4413/// isShuffleMaskLegal - Targets can use this to indicate that they only
4414/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4415/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4416/// are assumed to be legal.
4417bool
4418X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
4419 // Only do shuffles on 128-bit vector types for now.
4420 if (MVT::getSizeInBits(VT) == 64) return false;
4421 return (Mask.Val->getNumOperands() <= 4 ||
4422 isIdentityMask(Mask.Val) ||
4423 isIdentityMask(Mask.Val, true) ||
4424 isSplatMask(Mask.Val) ||
4425 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
4426 X86::isUNPCKLMask(Mask.Val) ||
4427 X86::isUNPCKHMask(Mask.Val) ||
4428 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
4429 X86::isUNPCKH_v_undef_Mask(Mask.Val));
4430}
4431
4432bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
4433 MVT::ValueType EVT,
4434 SelectionDAG &DAG) const {
4435 unsigned NumElts = BVOps.size();
4436 // Only do shuffles on 128-bit vector types for now.
4437 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
4438 if (NumElts == 2) return true;
4439 if (NumElts == 4) {
4440 return (isMOVLMask(&BVOps[0], 4) ||
4441 isCommutedMOVL(&BVOps[0], 4, true) ||
4442 isSHUFPMask(&BVOps[0], 4) ||
4443 isCommutedSHUFP(&BVOps[0], 4));
4444 }
4445 return false;
4446}
4447
4448//===----------------------------------------------------------------------===//
4449// X86 Scheduler Hooks
4450//===----------------------------------------------------------------------===//
4451
4452MachineBasicBlock *
4453X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
4454 MachineBasicBlock *BB) {
4455 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4456 switch (MI->getOpcode()) {
4457 default: assert(false && "Unexpected instr type to insert");
4458 case X86::CMOV_FR32:
4459 case X86::CMOV_FR64:
4460 case X86::CMOV_V4F32:
4461 case X86::CMOV_V2F64:
4462 case X86::CMOV_V2I64: {
4463 // To "insert" a SELECT_CC instruction, we actually have to insert the
4464 // diamond control-flow pattern. The incoming instruction knows the
4465 // destination vreg to set, the condition code register to branch on, the
4466 // true/false values to select between, and a branch opcode to use.
4467 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4468 ilist<MachineBasicBlock>::iterator It = BB;
4469 ++It;
4470
4471 // thisMBB:
4472 // ...
4473 // TrueVal = ...
4474 // cmpTY ccX, r1, r2
4475 // bCC copy1MBB
4476 // fallthrough --> copy0MBB
4477 MachineBasicBlock *thisMBB = BB;
4478 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
4479 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
4480 unsigned Opc =
4481 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
4482 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
4483 MachineFunction *F = BB->getParent();
4484 F->getBasicBlockList().insert(It, copy0MBB);
4485 F->getBasicBlockList().insert(It, sinkMBB);
4486 // Update machine-CFG edges by first adding all successors of the current
4487 // block to the new block which will contain the Phi node for the select.
4488 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
4489 e = BB->succ_end(); i != e; ++i)
4490 sinkMBB->addSuccessor(*i);
4491 // Next, remove all successors of the current block, and add the true
4492 // and fallthrough blocks as its successors.
4493 while(!BB->succ_empty())
4494 BB->removeSuccessor(BB->succ_begin());
4495 BB->addSuccessor(copy0MBB);
4496 BB->addSuccessor(sinkMBB);
4497
4498 // copy0MBB:
4499 // %FalseValue = ...
4500 // # fallthrough to sinkMBB
4501 BB = copy0MBB;
4502
4503 // Update machine-CFG edges
4504 BB->addSuccessor(sinkMBB);
4505
4506 // sinkMBB:
4507 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
4508 // ...
4509 BB = sinkMBB;
4510 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
4511 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
4512 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
4513
4514 delete MI; // The pseudo instruction is gone now.
4515 return BB;
4516 }
4517
4518 case X86::FP32_TO_INT16_IN_MEM:
4519 case X86::FP32_TO_INT32_IN_MEM:
4520 case X86::FP32_TO_INT64_IN_MEM:
4521 case X86::FP64_TO_INT16_IN_MEM:
4522 case X86::FP64_TO_INT32_IN_MEM:
4523 case X86::FP64_TO_INT64_IN_MEM: {
4524 // Change the floating point control register to use "round towards zero"
4525 // mode when truncating to an integer value.
4526 MachineFunction *F = BB->getParent();
4527 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
4528 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
4529
4530 // Load the old value of the high byte of the control word...
4531 unsigned OldCW =
4532 F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
4533 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
4534
4535 // Set the high part to be round to zero...
4536 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
4537 .addImm(0xC7F);
4538
4539 // Reload the modified control word now...
4540 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
4541
4542 // Restore the memory image of control word to original value
4543 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
4544 .addReg(OldCW);
4545
4546 // Get the X86 opcode to use.
4547 unsigned Opc;
4548 switch (MI->getOpcode()) {
4549 default: assert(0 && "illegal opcode!");
4550 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
4551 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
4552 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
4553 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
4554 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
4555 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
4556 }
4557
4558 X86AddressMode AM;
4559 MachineOperand &Op = MI->getOperand(0);
4560 if (Op.isRegister()) {
4561 AM.BaseType = X86AddressMode::RegBase;
4562 AM.Base.Reg = Op.getReg();
4563 } else {
4564 AM.BaseType = X86AddressMode::FrameIndexBase;
4565 AM.Base.FrameIndex = Op.getFrameIndex();
4566 }
4567 Op = MI->getOperand(1);
4568 if (Op.isImmediate())
4569 AM.Scale = Op.getImm();
4570 Op = MI->getOperand(2);
4571 if (Op.isImmediate())
4572 AM.IndexReg = Op.getImm();
4573 Op = MI->getOperand(3);
4574 if (Op.isGlobalAddress()) {
4575 AM.GV = Op.getGlobal();
4576 } else {
4577 AM.Disp = Op.getImm();
4578 }
4579 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
4580 .addReg(MI->getOperand(4).getReg());
4581
4582 // Reload the original control word now.
4583 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
4584
4585 delete MI; // The pseudo instruction is gone now.
4586 return BB;
4587 }
4588 }
4589}
4590
4591//===----------------------------------------------------------------------===//
4592// X86 Optimization Hooks
4593//===----------------------------------------------------------------------===//
4594
4595void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
4596 uint64_t Mask,
4597 uint64_t &KnownZero,
4598 uint64_t &KnownOne,
4599 const SelectionDAG &DAG,
4600 unsigned Depth) const {
4601 unsigned Opc = Op.getOpcode();
4602 assert((Opc >= ISD::BUILTIN_OP_END ||
4603 Opc == ISD::INTRINSIC_WO_CHAIN ||
4604 Opc == ISD::INTRINSIC_W_CHAIN ||
4605 Opc == ISD::INTRINSIC_VOID) &&
4606 "Should use MaskedValueIsZero if you don't know whether Op"
4607 " is a target node!");
4608
4609 KnownZero = KnownOne = 0; // Don't know anything.
4610 switch (Opc) {
4611 default: break;
4612 case X86ISD::SETCC:
4613 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
4614 break;
4615 }
4616}
4617
4618/// getShuffleScalarElt - Returns the scalar element that will make up the ith
4619/// element of the result of the vector shuffle.
4620static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
4621 MVT::ValueType VT = N->getValueType(0);
4622 SDOperand PermMask = N->getOperand(2);
4623 unsigned NumElems = PermMask.getNumOperands();
4624 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
4625 i %= NumElems;
4626 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4627 return (i == 0)
4628 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
4629 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
4630 SDOperand Idx = PermMask.getOperand(i);
4631 if (Idx.getOpcode() == ISD::UNDEF)
4632 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
4633 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
4634 }
4635 return SDOperand();
4636}
4637
4638/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
4639/// node is a GlobalAddress + an offset.
4640static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
4641 unsigned Opc = N->getOpcode();
4642 if (Opc == X86ISD::Wrapper) {
4643 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
4644 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
4645 return true;
4646 }
4647 } else if (Opc == ISD::ADD) {
4648 SDOperand N1 = N->getOperand(0);
4649 SDOperand N2 = N->getOperand(1);
4650 if (isGAPlusOffset(N1.Val, GA, Offset)) {
4651 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
4652 if (V) {
4653 Offset += V->getSignExtended();
4654 return true;
4655 }
4656 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
4657 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
4658 if (V) {
4659 Offset += V->getSignExtended();
4660 return true;
4661 }
4662 }
4663 }
4664 return false;
4665}
4666
4667/// isConsecutiveLoad - Returns true if N is loading from an address of Base
4668/// + Dist * Size.
4669static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
4670 MachineFrameInfo *MFI) {
4671 if (N->getOperand(0).Val != Base->getOperand(0).Val)
4672 return false;
4673
4674 SDOperand Loc = N->getOperand(1);
4675 SDOperand BaseLoc = Base->getOperand(1);
4676 if (Loc.getOpcode() == ISD::FrameIndex) {
4677 if (BaseLoc.getOpcode() != ISD::FrameIndex)
4678 return false;
Dan Gohman53491e92007-07-23 20:24:29 +00004679 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
4680 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004681 int FS = MFI->getObjectSize(FI);
4682 int BFS = MFI->getObjectSize(BFI);
4683 if (FS != BFS || FS != Size) return false;
4684 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
4685 } else {
4686 GlobalValue *GV1 = NULL;
4687 GlobalValue *GV2 = NULL;
4688 int64_t Offset1 = 0;
4689 int64_t Offset2 = 0;
4690 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
4691 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
4692 if (isGA1 && isGA2 && GV1 == GV2)
4693 return Offset1 == (Offset2 + Dist*Size);
4694 }
4695
4696 return false;
4697}
4698
4699static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
4700 const X86Subtarget *Subtarget) {
4701 GlobalValue *GV;
4702 int64_t Offset;
4703 if (isGAPlusOffset(Base, GV, Offset))
4704 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
4705 else {
4706 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
Dan Gohman53491e92007-07-23 20:24:29 +00004707 int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004708 if (BFI < 0)
4709 // Fixed objects do not specify alignment, however the offsets are known.
4710 return ((Subtarget->getStackAlignment() % 16) == 0 &&
4711 (MFI->getObjectOffset(BFI) % 16) == 0);
4712 else
4713 return MFI->getObjectAlignment(BFI) >= 16;
4714 }
4715 return false;
4716}
4717
4718
4719/// PerformShuffleCombine - Combine a vector_shuffle that is equal to
4720/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
4721/// if the load addresses are consecutive, non-overlapping, and in the right
4722/// order.
4723static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
4724 const X86Subtarget *Subtarget) {
4725 MachineFunction &MF = DAG.getMachineFunction();
4726 MachineFrameInfo *MFI = MF.getFrameInfo();
4727 MVT::ValueType VT = N->getValueType(0);
4728 MVT::ValueType EVT = MVT::getVectorElementType(VT);
4729 SDOperand PermMask = N->getOperand(2);
4730 int NumElems = (int)PermMask.getNumOperands();
4731 SDNode *Base = NULL;
4732 for (int i = 0; i < NumElems; ++i) {
4733 SDOperand Idx = PermMask.getOperand(i);
4734 if (Idx.getOpcode() == ISD::UNDEF) {
4735 if (!Base) return SDOperand();
4736 } else {
4737 SDOperand Arg =
4738 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
4739 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
4740 return SDOperand();
4741 if (!Base)
4742 Base = Arg.Val;
4743 else if (!isConsecutiveLoad(Arg.Val, Base,
4744 i, MVT::getSizeInBits(EVT)/8,MFI))
4745 return SDOperand();
4746 }
4747 }
4748
4749 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
4750 if (isAlign16) {
4751 LoadSDNode *LD = cast<LoadSDNode>(Base);
4752 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
4753 LD->getSrcValueOffset());
4754 } else {
4755 // Just use movups, it's shorter.
4756 SDVTList Tys = DAG.getVTList(MVT::v4f32, MVT::Other);
4757 SmallVector<SDOperand, 3> Ops;
4758 Ops.push_back(Base->getOperand(0));
4759 Ops.push_back(Base->getOperand(1));
4760 Ops.push_back(Base->getOperand(2));
4761 return DAG.getNode(ISD::BIT_CONVERT, VT,
4762 DAG.getNode(X86ISD::LOAD_UA, Tys, &Ops[0], Ops.size()));
4763 }
4764}
4765
4766/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
4767static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
4768 const X86Subtarget *Subtarget) {
4769 SDOperand Cond = N->getOperand(0);
4770
4771 // If we have SSE[12] support, try to form min/max nodes.
4772 if (Subtarget->hasSSE2() &&
4773 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
4774 if (Cond.getOpcode() == ISD::SETCC) {
4775 // Get the LHS/RHS of the select.
4776 SDOperand LHS = N->getOperand(1);
4777 SDOperand RHS = N->getOperand(2);
4778 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
4779
4780 unsigned Opcode = 0;
4781 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
4782 switch (CC) {
4783 default: break;
4784 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
4785 case ISD::SETULE:
4786 case ISD::SETLE:
4787 if (!UnsafeFPMath) break;
4788 // FALL THROUGH.
4789 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
4790 case ISD::SETLT:
4791 Opcode = X86ISD::FMIN;
4792 break;
4793
4794 case ISD::SETOGT: // (X > Y) ? X : Y -> max
4795 case ISD::SETUGT:
4796 case ISD::SETGT:
4797 if (!UnsafeFPMath) break;
4798 // FALL THROUGH.
4799 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
4800 case ISD::SETGE:
4801 Opcode = X86ISD::FMAX;
4802 break;
4803 }
4804 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
4805 switch (CC) {
4806 default: break;
4807 case ISD::SETOGT: // (X > Y) ? Y : X -> min
4808 case ISD::SETUGT:
4809 case ISD::SETGT:
4810 if (!UnsafeFPMath) break;
4811 // FALL THROUGH.
4812 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
4813 case ISD::SETGE:
4814 Opcode = X86ISD::FMIN;
4815 break;
4816
4817 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
4818 case ISD::SETULE:
4819 case ISD::SETLE:
4820 if (!UnsafeFPMath) break;
4821 // FALL THROUGH.
4822 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
4823 case ISD::SETLT:
4824 Opcode = X86ISD::FMAX;
4825 break;
4826 }
4827 }
4828
4829 if (Opcode)
4830 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
4831 }
4832
4833 }
4834
4835 return SDOperand();
4836}
4837
4838
4839SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
4840 DAGCombinerInfo &DCI) const {
4841 SelectionDAG &DAG = DCI.DAG;
4842 switch (N->getOpcode()) {
4843 default: break;
4844 case ISD::VECTOR_SHUFFLE:
4845 return PerformShuffleCombine(N, DAG, Subtarget);
4846 case ISD::SELECT:
4847 return PerformSELECTCombine(N, DAG, Subtarget);
4848 }
4849
4850 return SDOperand();
4851}
4852
4853//===----------------------------------------------------------------------===//
4854// X86 Inline Assembly Support
4855//===----------------------------------------------------------------------===//
4856
4857/// getConstraintType - Given a constraint letter, return the type of
4858/// constraint it is for this target.
4859X86TargetLowering::ConstraintType
4860X86TargetLowering::getConstraintType(const std::string &Constraint) const {
4861 if (Constraint.size() == 1) {
4862 switch (Constraint[0]) {
4863 case 'A':
4864 case 'r':
4865 case 'R':
4866 case 'l':
4867 case 'q':
4868 case 'Q':
4869 case 'x':
4870 case 'Y':
4871 return C_RegisterClass;
4872 default:
4873 break;
4874 }
4875 }
4876 return TargetLowering::getConstraintType(Constraint);
4877}
4878
4879/// isOperandValidForConstraint - Return the specified operand (possibly
4880/// modified) if the specified SDOperand is valid for the specified target
4881/// constraint letter, otherwise return null.
4882SDOperand X86TargetLowering::
4883isOperandValidForConstraint(SDOperand Op, char Constraint, SelectionDAG &DAG) {
4884 switch (Constraint) {
4885 default: break;
4886 case 'I':
4887 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4888 if (C->getValue() <= 31)
4889 return DAG.getTargetConstant(C->getValue(), Op.getValueType());
4890 }
4891 return SDOperand(0,0);
4892 case 'N':
4893 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4894 if (C->getValue() <= 255)
4895 return DAG.getTargetConstant(C->getValue(), Op.getValueType());
4896 }
4897 return SDOperand(0,0);
4898 case 'i': {
4899 // Literal immediates are always ok.
4900 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op))
4901 return DAG.getTargetConstant(CST->getValue(), Op.getValueType());
4902
4903 // If we are in non-pic codegen mode, we allow the address of a global (with
4904 // an optional displacement) to be used with 'i'.
4905 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
4906 int64_t Offset = 0;
4907
4908 // Match either (GA) or (GA+C)
4909 if (GA) {
4910 Offset = GA->getOffset();
4911 } else if (Op.getOpcode() == ISD::ADD) {
4912 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4913 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
4914 if (C && GA) {
4915 Offset = GA->getOffset()+C->getValue();
4916 } else {
4917 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4918 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
4919 if (C && GA)
4920 Offset = GA->getOffset()+C->getValue();
4921 else
4922 C = 0, GA = 0;
4923 }
4924 }
4925
4926 if (GA) {
4927 // If addressing this global requires a load (e.g. in PIC mode), we can't
4928 // match.
4929 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
4930 false))
4931 return SDOperand(0, 0);
4932
4933 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4934 Offset);
4935 return Op;
4936 }
4937
4938 // Otherwise, not valid for this mode.
4939 return SDOperand(0, 0);
4940 }
4941 }
4942 return TargetLowering::isOperandValidForConstraint(Op, Constraint, DAG);
4943}
4944
4945std::vector<unsigned> X86TargetLowering::
4946getRegClassForInlineAsmConstraint(const std::string &Constraint,
4947 MVT::ValueType VT) const {
4948 if (Constraint.size() == 1) {
4949 // FIXME: not handling fp-stack yet!
4950 switch (Constraint[0]) { // GCC X86 Constraint Letters
4951 default: break; // Unknown constraint letter
4952 case 'A': // EAX/EDX
4953 if (VT == MVT::i32 || VT == MVT::i64)
4954 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
4955 break;
4956 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
4957 case 'Q': // Q_REGS
4958 if (VT == MVT::i32)
4959 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
4960 else if (VT == MVT::i16)
4961 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
4962 else if (VT == MVT::i8)
4963 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::DL, 0);
4964 break;
4965 }
4966 }
4967
4968 return std::vector<unsigned>();
4969}
4970
4971std::pair<unsigned, const TargetRegisterClass*>
4972X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
4973 MVT::ValueType VT) const {
4974 // First, see if this is a constraint that directly corresponds to an LLVM
4975 // register class.
4976 if (Constraint.size() == 1) {
4977 // GCC Constraint Letters
4978 switch (Constraint[0]) {
4979 default: break;
4980 case 'r': // GENERAL_REGS
4981 case 'R': // LEGACY_REGS
4982 case 'l': // INDEX_REGS
4983 if (VT == MVT::i64 && Subtarget->is64Bit())
4984 return std::make_pair(0U, X86::GR64RegisterClass);
4985 if (VT == MVT::i32)
4986 return std::make_pair(0U, X86::GR32RegisterClass);
4987 else if (VT == MVT::i16)
4988 return std::make_pair(0U, X86::GR16RegisterClass);
4989 else if (VT == MVT::i8)
4990 return std::make_pair(0U, X86::GR8RegisterClass);
4991 break;
4992 case 'y': // MMX_REGS if MMX allowed.
4993 if (!Subtarget->hasMMX()) break;
4994 return std::make_pair(0U, X86::VR64RegisterClass);
4995 break;
4996 case 'Y': // SSE_REGS if SSE2 allowed
4997 if (!Subtarget->hasSSE2()) break;
4998 // FALL THROUGH.
4999 case 'x': // SSE_REGS if SSE1 allowed
5000 if (!Subtarget->hasSSE1()) break;
5001
5002 switch (VT) {
5003 default: break;
5004 // Scalar SSE types.
5005 case MVT::f32:
5006 case MVT::i32:
5007 return std::make_pair(0U, X86::FR32RegisterClass);
5008 case MVT::f64:
5009 case MVT::i64:
5010 return std::make_pair(0U, X86::FR64RegisterClass);
5011 // Vector types.
5012 case MVT::v16i8:
5013 case MVT::v8i16:
5014 case MVT::v4i32:
5015 case MVT::v2i64:
5016 case MVT::v4f32:
5017 case MVT::v2f64:
5018 return std::make_pair(0U, X86::VR128RegisterClass);
5019 }
5020 break;
5021 }
5022 }
5023
5024 // Use the default implementation in TargetLowering to convert the register
5025 // constraint into a member of a register class.
5026 std::pair<unsigned, const TargetRegisterClass*> Res;
5027 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
5028
5029 // Not found as a standard register?
5030 if (Res.second == 0) {
5031 // GCC calls "st(0)" just plain "st".
5032 if (StringsEqualNoCase("{st}", Constraint)) {
5033 Res.first = X86::ST0;
5034 Res.second = X86::RSTRegisterClass;
5035 }
5036
5037 return Res;
5038 }
5039
5040 // Otherwise, check to see if this is a register class of the wrong value
5041 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
5042 // turn into {ax},{dx}.
5043 if (Res.second->hasType(VT))
5044 return Res; // Correct type already, nothing to do.
5045
5046 // All of the single-register GCC register classes map their values onto
5047 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
5048 // really want an 8-bit or 32-bit register, map to the appropriate register
5049 // class and return the appropriate register.
5050 if (Res.second != X86::GR16RegisterClass)
5051 return Res;
5052
5053 if (VT == MVT::i8) {
5054 unsigned DestReg = 0;
5055 switch (Res.first) {
5056 default: break;
5057 case X86::AX: DestReg = X86::AL; break;
5058 case X86::DX: DestReg = X86::DL; break;
5059 case X86::CX: DestReg = X86::CL; break;
5060 case X86::BX: DestReg = X86::BL; break;
5061 }
5062 if (DestReg) {
5063 Res.first = DestReg;
5064 Res.second = Res.second = X86::GR8RegisterClass;
5065 }
5066 } else if (VT == MVT::i32) {
5067 unsigned DestReg = 0;
5068 switch (Res.first) {
5069 default: break;
5070 case X86::AX: DestReg = X86::EAX; break;
5071 case X86::DX: DestReg = X86::EDX; break;
5072 case X86::CX: DestReg = X86::ECX; break;
5073 case X86::BX: DestReg = X86::EBX; break;
5074 case X86::SI: DestReg = X86::ESI; break;
5075 case X86::DI: DestReg = X86::EDI; break;
5076 case X86::BP: DestReg = X86::EBP; break;
5077 case X86::SP: DestReg = X86::ESP; break;
5078 }
5079 if (DestReg) {
5080 Res.first = DestReg;
5081 Res.second = Res.second = X86::GR32RegisterClass;
5082 }
5083 } else if (VT == MVT::i64) {
5084 unsigned DestReg = 0;
5085 switch (Res.first) {
5086 default: break;
5087 case X86::AX: DestReg = X86::RAX; break;
5088 case X86::DX: DestReg = X86::RDX; break;
5089 case X86::CX: DestReg = X86::RCX; break;
5090 case X86::BX: DestReg = X86::RBX; break;
5091 case X86::SI: DestReg = X86::RSI; break;
5092 case X86::DI: DestReg = X86::RDI; break;
5093 case X86::BP: DestReg = X86::RBP; break;
5094 case X86::SP: DestReg = X86::RSP; break;
5095 }
5096 if (DestReg) {
5097 Res.first = DestReg;
5098 Res.second = Res.second = X86::GR64RegisterClass;
5099 }
5100 }
5101
5102 return Res;
5103}