1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/ParameterAttributes.h"
43 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
44 : TargetLowering(TM) {
45 Subtarget = &TM.getSubtarget<X86Subtarget>();
46 X86ScalarSSEf64 = Subtarget->hasSSE2();
47 X86ScalarSSEf32 = Subtarget->hasSSE1();
48 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
51 RegInfo = TM.getRegisterInfo();
53 // Set up the TargetLowering object.
55 // X86 is weird, it always uses i8 for shift amounts and setcc results.
56 setShiftAmountType(MVT::i8);
57 setSetCCResultType(MVT::i8);
58 setSetCCResultContents(ZeroOrOneSetCCResult);
59 setSchedulingPreference(SchedulingForRegPressure);
60 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
61 setStackPointerRegisterToSaveRestore(X86StackPtr);
63 if (Subtarget->isTargetDarwin()) {
64 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
65 setUseUnderscoreSetJmp(false);
66 setUseUnderscoreLongJmp(false);
67 } else if (Subtarget->isTargetMingw()) {
68 // MS runtime is weird: it exports _setjmp, but longjmp!
69 setUseUnderscoreSetJmp(true);
70 setUseUnderscoreLongJmp(false);
72 setUseUnderscoreSetJmp(true);
73 setUseUnderscoreLongJmp(true);
76 // Set up the register classes.
77 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
78 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
79 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
80 if (Subtarget->is64Bit())
81 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
83 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
85 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
87 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
88 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
89 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
91 if (Subtarget->is64Bit()) {
92 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
93 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
96 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
97 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
99 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
102 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
104 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
105 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
106 // SSE has no i16 to fp conversion, only i32
107 if (X86ScalarSSEf32) {
108 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
109 // f32 and f64 cases are Legal, f80 case is not
110 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
112 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
113 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
116 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
117 // are Legal, f80 is custom lowered.
118 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
119 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
121 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
123 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
124 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
126 if (X86ScalarSSEf32) {
127 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
128 // f32 and f64 cases are Legal, f80 case is not
129 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
131 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
132 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
135 // Handle FP_TO_UINT by promoting the destination to a larger signed
137 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
138 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
139 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
141 if (Subtarget->is64Bit()) {
142 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
143 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
145 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
146 // Expand FP_TO_UINT into a select.
147 // FIXME: We would like to use a Custom expander here eventually to do
148 // the optimal thing for SSE vs. the default expansion in the legalizer.
149 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
151 // With SSE3 we can use fisttpll to convert to a signed i64.
152 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
155 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
156 if (!X86ScalarSSEf64) {
157 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
158 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
161 // Scalar integer multiply, multiply-high, divide, and remainder are
162 // lowered to use operations that produce two results, to match the
163 // available instructions. This exposes the two-result form to trivial
164 // CSE, which is able to combine x/y and x%y into a single instruction,
165 // for example. The single-result multiply instructions are introduced
166 // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
168 setOperationAction(ISD::MUL , MVT::i8 , Expand);
169 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
170 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
171 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
172 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
173 setOperationAction(ISD::SREM , MVT::i8 , Expand);
174 setOperationAction(ISD::UREM , MVT::i8 , Expand);
175 setOperationAction(ISD::MUL , MVT::i16 , Expand);
176 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
177 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
178 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
179 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
180 setOperationAction(ISD::SREM , MVT::i16 , Expand);
181 setOperationAction(ISD::UREM , MVT::i16 , Expand);
182 setOperationAction(ISD::MUL , MVT::i32 , Expand);
183 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
184 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
185 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
186 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
187 setOperationAction(ISD::SREM , MVT::i32 , Expand);
188 setOperationAction(ISD::UREM , MVT::i32 , Expand);
189 setOperationAction(ISD::MUL , MVT::i64 , Expand);
190 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
191 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
192 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
193 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
194 setOperationAction(ISD::SREM , MVT::i64 , Expand);
195 setOperationAction(ISD::UREM , MVT::i64 , Expand);
197 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
198 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
199 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
200 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
201 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
202 if (Subtarget->is64Bit())
203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
206 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
207 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
208 setOperationAction(ISD::FREM , MVT::f64 , Expand);
209 setOperationAction(ISD::FLT_ROUNDS , MVT::i32 , Custom);
211 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
212 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
213 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
214 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
215 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
216 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
217 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
218 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
219 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
220 if (Subtarget->is64Bit()) {
221 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
222 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
223 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
226 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
227 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
229 // These should be promoted to a larger select which is supported.
230 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
231 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
232 // X86 wants to expand cmov itself.
233 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
234 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
235 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
236 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
237 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
238 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
239 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
240 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
241 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
242 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
243 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
244 if (Subtarget->is64Bit()) {
245 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
246 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
248 // X86 ret instruction may pop stack.
249 setOperationAction(ISD::RET , MVT::Other, Custom);
250 if (!Subtarget->is64Bit())
251 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
254 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
255 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
256 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
257 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
258 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
259 if (Subtarget->is64Bit()) {
260 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
261 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
262 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
263 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
265 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
266 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
267 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
268 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
269 // X86 wants to expand memset / memcpy itself.
270 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
271 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
273 // Use the default ISD::LOCATION expansion.
274 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
275 // FIXME - use subtarget debug flags
276 if (!Subtarget->isTargetDarwin() &&
277 !Subtarget->isTargetELF() &&
278 !Subtarget->isTargetCygMing())
279 setOperationAction(ISD::LABEL, MVT::Other, Expand);
281 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
282 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
283 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
284 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
285 if (Subtarget->is64Bit()) {
287 setExceptionPointerRegister(X86::RAX);
288 setExceptionSelectorRegister(X86::RDX);
290 setExceptionPointerRegister(X86::EAX);
291 setExceptionSelectorRegister(X86::EDX);
293 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
295 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
297 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
298 setOperationAction(ISD::VASTART , MVT::Other, Custom);
299 setOperationAction(ISD::VAARG , MVT::Other, Expand);
300 setOperationAction(ISD::VAEND , MVT::Other, Expand);
301 if (Subtarget->is64Bit())
302 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
304 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
306 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
307 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
308 if (Subtarget->is64Bit())
309 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
310 if (Subtarget->isTargetCygMing())
311 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
313 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
315 if (X86ScalarSSEf64) {
316 // f32 and f64 use SSE.
317 // Set up the FP register classes.
318 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
319 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
321 // Use ANDPD to simulate FABS.
322 setOperationAction(ISD::FABS , MVT::f64, Custom);
323 setOperationAction(ISD::FABS , MVT::f32, Custom);
325 // Use XORP to simulate FNEG.
326 setOperationAction(ISD::FNEG , MVT::f64, Custom);
327 setOperationAction(ISD::FNEG , MVT::f32, Custom);
329 // Use ANDPD and ORPD to simulate FCOPYSIGN.
330 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
331 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
333 // We don't support sin/cos/fmod
334 setOperationAction(ISD::FSIN , MVT::f64, Expand);
335 setOperationAction(ISD::FCOS , MVT::f64, Expand);
336 setOperationAction(ISD::FREM , MVT::f64, Expand);
337 setOperationAction(ISD::FSIN , MVT::f32, Expand);
338 setOperationAction(ISD::FCOS , MVT::f32, Expand);
339 setOperationAction(ISD::FREM , MVT::f32, Expand);
341 // Expand FP immediates into loads from the stack, except for the special
343 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
344 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
345 addLegalFPImmediate(APFloat(+0.0)); // xorpd
346 addLegalFPImmediate(APFloat(+0.0f)); // xorps
348 // Conversions to long double (in X87) go through memory.
349 setConvertAction(MVT::f32, MVT::f80, Expand);
350 setConvertAction(MVT::f64, MVT::f80, Expand);
352 // Conversions from long double (in X87) go through memory.
353 setConvertAction(MVT::f80, MVT::f32, Expand);
354 setConvertAction(MVT::f80, MVT::f64, Expand);
355 } else if (X86ScalarSSEf32) {
356 // Use SSE for f32, x87 for f64.
357 // Set up the FP register classes.
358 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
359 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
361 // Use ANDPS to simulate FABS.
362 setOperationAction(ISD::FABS , MVT::f32, Custom);
364 // Use XORP to simulate FNEG.
365 setOperationAction(ISD::FNEG , MVT::f32, Custom);
367 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
369 // Use ANDPS and ORPS to simulate FCOPYSIGN.
370 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
371 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
373 // We don't support sin/cos/fmod
374 setOperationAction(ISD::FSIN , MVT::f32, Expand);
375 setOperationAction(ISD::FCOS , MVT::f32, Expand);
376 setOperationAction(ISD::FREM , MVT::f32, Expand);
378 // Expand FP immediates into loads from the stack, except for the special
380 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
381 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
382 addLegalFPImmediate(APFloat(+0.0f)); // xorps
383 addLegalFPImmediate(APFloat(+0.0)); // FLD0
384 addLegalFPImmediate(APFloat(+1.0)); // FLD1
385 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
386 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
388 // SSE->x87 conversions go through memory.
389 setConvertAction(MVT::f32, MVT::f64, Expand);
390 setConvertAction(MVT::f32, MVT::f80, Expand);
392 // x87->SSE truncations need to go through memory.
393 setConvertAction(MVT::f80, MVT::f32, Expand);
394 setConvertAction(MVT::f64, MVT::f32, Expand);
395 // And x87->x87 truncations also.
396 setConvertAction(MVT::f80, MVT::f64, Expand);
399 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
400 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
403 // f32 and f64 in x87.
404 // Set up the FP register classes.
405 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
406 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
408 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
409 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
410 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
411 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
413 // Floating truncations need to go through memory.
414 setConvertAction(MVT::f80, MVT::f32, Expand);
415 setConvertAction(MVT::f64, MVT::f32, Expand);
416 setConvertAction(MVT::f80, MVT::f64, Expand);
419 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
420 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
423 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
424 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
425 addLegalFPImmediate(APFloat(+0.0)); // FLD0
426 addLegalFPImmediate(APFloat(+1.0)); // FLD1
427 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
428 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
429 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
430 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
431 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
432 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
435 // Long double always uses X87.
436 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
437 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
438 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
439 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
441 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
442 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
445 // Always use a library call for pow.
446 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
447 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
448 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
450 // First set operation action for all vector types to expand. Then we
451 // will selectively turn on ones that can be effectively codegen'd.
452 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
453 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
454 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
455 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
456 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
457 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
458 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
459 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
460 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
461 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
462 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
463 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
464 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
465 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
466 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
467 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
468 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
469 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
470 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
471 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
472 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
473 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
474 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
475 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
476 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
477 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
478 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
479 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
480 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
481 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
482 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
483 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
484 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
485 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
486 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
487 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
488 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
489 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
490 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
493 if (Subtarget->hasMMX()) {
494 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
495 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
496 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
497 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
499 // FIXME: add MMX packed arithmetics
501 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
502 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
503 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
504 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
506 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
507 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
508 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
509 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
511 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
512 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
514 setOperationAction(ISD::AND, MVT::v8i8, Promote);
515 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
516 setOperationAction(ISD::AND, MVT::v4i16, Promote);
517 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
518 setOperationAction(ISD::AND, MVT::v2i32, Promote);
519 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
520 setOperationAction(ISD::AND, MVT::v1i64, Legal);
522 setOperationAction(ISD::OR, MVT::v8i8, Promote);
523 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
524 setOperationAction(ISD::OR, MVT::v4i16, Promote);
525 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
526 setOperationAction(ISD::OR, MVT::v2i32, Promote);
527 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
528 setOperationAction(ISD::OR, MVT::v1i64, Legal);
530 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
531 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
532 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
533 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
534 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
535 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
536 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
538 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
539 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
540 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
541 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
542 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
543 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
544 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
546 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
547 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
548 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
549 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
551 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
552 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
553 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
554 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
556 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
557 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
558 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
559 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
562 if (Subtarget->hasSSE1()) {
563 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
565 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
566 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
567 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
568 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
569 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
570 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
571 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
572 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
573 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
574 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
575 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
578 if (Subtarget->hasSSE2()) {
579 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
580 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
581 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
582 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
583 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
585 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
586 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
587 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
588 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
589 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
590 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
591 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
592 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
593 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
594 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
595 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
596 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
597 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
598 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
599 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
601 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
602 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
603 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
604 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
605 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
606 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
608 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
609 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
610 // Do not attempt to custom lower non-power-of-2 vectors
611 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
613 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
614 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
615 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
617 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
618 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
619 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
620 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
621 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
622 if (Subtarget->is64Bit())
623 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
625 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
626 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
627 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
628 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
629 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
630 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
631 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
632 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
633 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
634 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
635 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
636 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
639 // Custom lower v2i64 and v2f64 selects.
640 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
641 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
642 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
643 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
646 // We want to custom lower some of our intrinsics.
647 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
649 // We have target-specific dag combine patterns for the following nodes:
650 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
651 setTargetDAGCombine(ISD::SELECT);
653 computeRegisterProperties();
655 // FIXME: These should be based on subtarget info. Plus, the values should
656 // be smaller when we are in optimizing for size mode.
657 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
658 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
659 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
660 allowUnalignedMemoryAccesses = true; // x86 supports it!
664 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
666 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
667 SelectionDAG &DAG) const {
668 if (usesGlobalOffsetTable())
669 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
670 if (!Subtarget->isPICStyleRIPRel())
671 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
675 //===----------------------------------------------------------------------===//
676 // Return Value Calling Convention Implementation
677 //===----------------------------------------------------------------------===//
679 #include "X86GenCallingConv.inc"
681 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
682 /// exists skip possible ISD:TokenFactor.
683 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
684 if (Chain.getOpcode()==X86ISD::TAILCALL) {
686 } else if (Chain.getOpcode()==ISD::TokenFactor) {
687 if (Chain.getNumOperands() &&
688 Chain.getOperand(0).getOpcode()==X86ISD::TAILCALL)
689 return Chain.getOperand(0);
694 /// LowerRET - Lower an ISD::RET node.
695 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
696 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
698 SmallVector<CCValAssign, 16> RVLocs;
699 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
700 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
701 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
702 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
704 // If this is the first return lowered for this function, add the regs to the
705 // liveout set for the function.
706 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
707 for (unsigned i = 0; i != RVLocs.size(); ++i)
708 if (RVLocs[i].isRegLoc())
709 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
711 SDOperand Chain = Op.getOperand(0);
713 // Handle tail call return.
714 Chain = GetPossiblePreceedingTailCall(Chain);
715 if (Chain.getOpcode() == X86ISD::TAILCALL) {
716 SDOperand TailCall = Chain;
717 SDOperand TargetAddress = TailCall.getOperand(1);
718 SDOperand StackAdjustment = TailCall.getOperand(2);
719 assert ( ((TargetAddress.getOpcode() == ISD::Register &&
720 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
721 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
722 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
723 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
724 "Expecting an global address, external symbol, or register");
725 assert( StackAdjustment.getOpcode() == ISD::Constant &&
726 "Expecting a const value");
728 SmallVector<SDOperand,8> Operands;
729 Operands.push_back(Chain.getOperand(0));
730 Operands.push_back(TargetAddress);
731 Operands.push_back(StackAdjustment);
732 // Copy registers used by the call. Last operand is a flag so it is not
734 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
735 Operands.push_back(Chain.getOperand(i));
737 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
744 // Copy the result values into the output registers.
745 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
746 RVLocs[0].getLocReg() != X86::ST0) {
747 for (unsigned i = 0; i != RVLocs.size(); ++i) {
748 CCValAssign &VA = RVLocs[i];
749 assert(VA.isRegLoc() && "Can only return in registers!");
750 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
752 Flag = Chain.getValue(1);
755 // We need to handle a destination of ST0 specially, because it isn't really
757 SDOperand Value = Op.getOperand(1);
759 // If this is an FP return with ScalarSSE, we need to move the value from
760 // an XMM register onto the fp-stack.
761 if ((X86ScalarSSEf32 && RVLocs[0].getValVT()==MVT::f32) ||
762 (X86ScalarSSEf64 && RVLocs[0].getValVT()==MVT::f64)) {
765 // If this is a load into a scalarsse value, don't store the loaded value
766 // back to the stack, only to reload it: just replace the scalar-sse load.
767 if (ISD::isNON_EXTLoad(Value.Val) &&
768 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
769 Chain = Value.getOperand(0);
770 MemLoc = Value.getOperand(1);
772 // Spill the value to memory and reload it into top of stack.
773 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
774 MachineFunction &MF = DAG.getMachineFunction();
775 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
776 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
777 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
779 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
780 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
781 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
782 Chain = Value.getValue(1);
785 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
786 SDOperand Ops[] = { Chain, Value };
787 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
788 Flag = Chain.getValue(1);
791 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
793 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
795 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
799 /// LowerCallResult - Lower the result values of an ISD::CALL into the
800 /// appropriate copies out of appropriate physical registers. This assumes that
801 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
802 /// being lowered. The returns a SDNode with the same number of values as the
804 SDNode *X86TargetLowering::
805 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
806 unsigned CallingConv, SelectionDAG &DAG) {
808 // Assign locations to each value returned by this call.
809 SmallVector<CCValAssign, 16> RVLocs;
810 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
811 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
812 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
814 SmallVector<SDOperand, 8> ResultVals;
816 // Copy all of the result registers out of their specified physreg.
817 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
818 for (unsigned i = 0; i != RVLocs.size(); ++i) {
819 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
820 RVLocs[i].getValVT(), InFlag).getValue(1);
821 InFlag = Chain.getValue(2);
822 ResultVals.push_back(Chain.getValue(0));
825 // Copies from the FP stack are special, as ST0 isn't a valid register
826 // before the fp stackifier runs.
828 // Copy ST0 into an RFP register with FP_GET_RESULT.
829 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
830 SDOperand GROps[] = { Chain, InFlag };
831 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
832 Chain = RetVal.getValue(1);
833 InFlag = RetVal.getValue(2);
835 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
837 if ((X86ScalarSSEf32 && RVLocs[0].getValVT() == MVT::f32) ||
838 (X86ScalarSSEf64 && RVLocs[0].getValVT() == MVT::f64)) {
840 const Value *SrcVal = 0;
841 int SrcValOffset = 0;
842 MVT::ValueType RetStoreVT = RVLocs[0].getValVT();
844 // Determine where to store the value. If the call result is directly
845 // used by a store, see if we can store directly into the location. In
846 // this case, we'll end up producing a fst + movss[load] + movss[store] to
847 // the same location, and the two movss's will be nuked as dead. This
848 // optimizes common things like "*D = atof(..)" to not need an
849 // intermediate stack slot.
850 if (SDOperand(TheCall, 0).hasOneUse() &&
851 SDOperand(TheCall, 1).hasOneUse()) {
852 // In addition to direct uses, we also support a FP_ROUND that uses the
853 // value, if it is directly stored somewhere.
854 SDNode *User = *TheCall->use_begin();
855 if (User->getOpcode() == ISD::FP_ROUND && User->hasOneUse())
856 User = *User->use_begin();
858 // Ok, we have one use of the value and one use of the chain. See if
859 // they are the same node: a store.
860 if (StoreSDNode *N = dyn_cast<StoreSDNode>(User)) {
861 // Verify that the value being stored is either the call or a
862 // truncation of the call.
863 SDNode *StoreVal = N->getValue().Val;
864 if (StoreVal == TheCall)
866 else if (StoreVal->getOpcode() == ISD::FP_ROUND &&
867 StoreVal->hasOneUse() &&
868 StoreVal->getOperand(0).Val == TheCall)
873 if (N && N->getChain().Val == TheCall &&
874 !N->isVolatile() && !N->isTruncatingStore() &&
875 N->getAddressingMode() == ISD::UNINDEXED) {
876 StoreLoc = N->getBasePtr();
877 SrcVal = N->getSrcValue();
878 SrcValOffset = N->getSrcValueOffset();
879 RetStoreVT = N->getValue().getValueType();
884 // If we weren't able to optimize the result, just create a temporary
886 if (StoreLoc.Val == 0) {
887 MachineFunction &MF = DAG.getMachineFunction();
888 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
889 StoreLoc = DAG.getFrameIndex(SSFI, getPointerTy());
892 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
893 // shouldn't be necessary except that RFP cannot be live across
894 // multiple blocks (which could happen if a select gets lowered into
895 // multiple blocks and scheduled in between them). When stackifier is
896 // fixed, they can be uncoupled.
898 Chain, RetVal, StoreLoc, DAG.getValueType(RetStoreVT), InFlag
900 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
901 RetVal = DAG.getLoad(RetStoreVT, Chain,
902 StoreLoc, SrcVal, SrcValOffset);
903 Chain = RetVal.getValue(1);
905 // If we optimized a truncate, then extend the result back to its desired
907 if (RVLocs[0].getValVT() != RetStoreVT)
908 RetVal = DAG.getNode(ISD::FP_EXTEND, RVLocs[0].getValVT(), RetVal);
910 ResultVals.push_back(RetVal);
913 // Merge everything together with a MERGE_VALUES node.
914 ResultVals.push_back(Chain);
915 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
916 &ResultVals[0], ResultVals.size()).Val;
920 //===----------------------------------------------------------------------===//
921 // C & StdCall & Fast Calling Convention implementation
922 //===----------------------------------------------------------------------===//
923 // StdCall calling convention seems to be standard for many Windows' API
924 // routines and around. It differs from C calling convention just a little:
925 // callee should clean up the stack, not caller. Symbols should be also
926 // decorated in some fancy way :) It doesn't support any vector arguments.
927 // For info on fast calling convention see Fast Calling Convention (tail call)
928 // implementation LowerX86_32FastCCCallTo.
930 /// AddLiveIn - This helper function adds the specified physical register to the
931 /// MachineFunction as a live in value. It also creates a corresponding virtual
933 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
934 const TargetRegisterClass *RC) {
935 assert(RC->contains(PReg) && "Not the correct regclass!");
936 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
937 MF.getRegInfo().addLiveIn(PReg, VReg);
941 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
942 const CCValAssign &VA,
943 MachineFrameInfo *MFI,
944 SDOperand Root, unsigned i) {
945 // Create the nodes corresponding to a load from this parameter slot.
946 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
947 VA.getLocMemOffset());
948 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
950 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
952 if (Flags & ISD::ParamFlags::ByVal)
955 return DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0);
958 SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
960 MachineFunction &MF = DAG.getMachineFunction();
961 MachineFrameInfo *MFI = MF.getFrameInfo();
962 SDOperand Root = Op.getOperand(0);
963 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
964 unsigned CC = MF.getFunction()->getCallingConv();
966 assert(!(isVarArg && CC == CallingConv::Fast) &&
967 "Var args not supported with calling convention fastcc");
969 // Assign locations to all of the incoming arguments.
970 SmallVector<CCValAssign, 16> ArgLocs;
971 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
972 // Check for possible tail call calling convention.
973 if (CC == CallingConv::Fast && PerformTailCallOpt)
974 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_TailCall);
976 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
978 SmallVector<SDOperand, 8> ArgValues;
979 unsigned LastVal = ~0U;
980 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
981 CCValAssign &VA = ArgLocs[i];
982 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
984 assert(VA.getValNo() != LastVal &&
985 "Don't support value assigned to multiple locs yet");
986 LastVal = VA.getValNo();
989 MVT::ValueType RegVT = VA.getLocVT();
990 TargetRegisterClass *RC;
991 if (RegVT == MVT::i32)
992 RC = X86::GR32RegisterClass;
994 assert(MVT::isVector(RegVT));
995 RC = X86::VR128RegisterClass;
998 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
999 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1001 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1002 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1004 if (VA.getLocInfo() == CCValAssign::SExt)
1005 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1006 DAG.getValueType(VA.getValVT()));
1007 else if (VA.getLocInfo() == CCValAssign::ZExt)
1008 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1009 DAG.getValueType(VA.getValVT()));
1011 if (VA.getLocInfo() != CCValAssign::Full)
1012 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1014 ArgValues.push_back(ArgValue);
1016 assert(VA.isMemLoc());
1017 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1021 unsigned StackSize = CCInfo.getNextStackOffset();
1022 // align stack specially for tail calls
1023 if (CC == CallingConv::Fast)
1024 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1026 // If the function takes variable number of arguments, make a frame index for
1027 // the start of the first vararg value... for expansion of llvm.va_start.
1029 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1032 ArgValues.push_back(Root);
1034 // Tail call convention (fastcc) needs callee pop.
1035 if (isStdCall && !isVarArg &&
1036 (CC==CallingConv::Fast && PerformTailCallOpt || CC!=CallingConv::Fast)) {
1037 BytesToPopOnReturn = StackSize; // Callee pops everything..
1038 BytesCallerReserves = 0;
1040 BytesToPopOnReturn = 0; // Callee pops nothing.
1042 // If this is an sret function, the return should pop the hidden pointer.
1043 unsigned NumArgs = Op.Val->getNumValues() - 1;
1045 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
1046 ISD::ParamFlags::StructReturn))
1047 BytesToPopOnReturn = 4;
1049 BytesCallerReserves = StackSize;
1052 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
1054 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1055 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1057 // Return the new list of results.
1058 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1059 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1063 X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
1065 SDOperand Chain = Op.getOperand(0);
1066 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1067 SDOperand Callee = Op.getOperand(4);
1069 assert(!(isVarArg && CC == CallingConv::Fast) &&
1070 "Var args not supported with calling convention fastcc");
1072 // Analyze operands of the call, assigning locations to each operand.
1073 SmallVector<CCValAssign, 16> ArgLocs;
1074 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1075 if (CC==CallingConv::Fast && PerformTailCallOpt)
1076 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1078 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
1080 // Get a count of how many bytes are to be pushed on the stack.
1081 unsigned NumBytes = CCInfo.getNextStackOffset();
1082 if (CC == CallingConv::Fast)
1083 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1085 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1087 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1088 SmallVector<SDOperand, 8> MemOpChains;
1092 // Walk the register/memloc assignments, inserting copies/loads.
1093 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1094 CCValAssign &VA = ArgLocs[i];
1095 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1097 // Promote the value if needed.
1098 switch (VA.getLocInfo()) {
1099 default: assert(0 && "Unknown loc info!");
1100 case CCValAssign::Full: break;
1101 case CCValAssign::SExt:
1102 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1104 case CCValAssign::ZExt:
1105 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1107 case CCValAssign::AExt:
1108 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1112 if (VA.isRegLoc()) {
1113 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1115 assert(VA.isMemLoc());
1116 if (StackPtr.Val == 0)
1117 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1119 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1124 // If the first argument is an sret pointer, remember it.
1125 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1126 bool isSRet = NumOps &&
1127 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
1128 ISD::ParamFlags::StructReturn);
1130 if (!MemOpChains.empty())
1131 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1132 &MemOpChains[0], MemOpChains.size());
1134 // Build a sequence of copy-to-reg nodes chained together with token chain
1135 // and flag operands which copy the outgoing args into registers.
1137 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1138 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1140 InFlag = Chain.getValue(1);
1143 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1145 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1146 Subtarget->isPICStyleGOT()) {
1147 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1148 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1150 InFlag = Chain.getValue(1);
1153 // If the callee is a GlobalAddress node (quite common, every direct call is)
1154 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1155 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1156 // We should use extra load for direct calls to dllimported functions in
1158 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1159 getTargetMachine(), true))
1160 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1161 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1162 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1165 // Returns a chain & a flag for retval copy to use.
1166 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1167 SmallVector<SDOperand, 8> Ops;
1168 Ops.push_back(Chain);
1169 Ops.push_back(Callee);
1171 // Add argument registers to the end of the list so that they are known live
1173 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1174 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1175 RegsToPass[i].second.getValueType()));
1177 // Add an implicit use GOT pointer in EBX.
1178 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1179 Subtarget->isPICStyleGOT())
1180 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1183 Ops.push_back(InFlag);
1185 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1186 InFlag = Chain.getValue(1);
1188 // Create the CALLSEQ_END node.
1189 unsigned NumBytesForCalleeToPush = 0;
1190 if (!isVarArg && (CC == CallingConv::X86_StdCall
1191 || CC == CallingConv::Fast && PerformTailCallOpt)) {
1192 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1193 } else if (isSRet) {
1194 // If this is is a call to a struct-return function, the callee
1195 // pops the hidden struct pointer, so we have to push it back.
1196 // This is common for Darwin/X86, Linux & Mingw32 targets.
1197 NumBytesForCalleeToPush = 4;
1199 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1202 // Returns a flag for retval copy to use.
1203 Chain = DAG.getCALLSEQ_END(Chain,
1204 DAG.getConstant(NumBytes, getPointerTy()),
1205 DAG.getConstant(NumBytesForCalleeToPush,
1208 InFlag = Chain.getValue(1);
1210 // Handle result values, copying them out of physregs into vregs that we
1212 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1216 //===----------------------------------------------------------------------===//
1217 // FastCall Calling Convention implementation
1218 //===----------------------------------------------------------------------===//
1220 // The X86 'fastcall' calling convention passes up to two integer arguments in
1221 // registers (an appropriate portion of ECX/EDX), passes arguments in C order,
1222 // and requires that the callee pop its arguments off the stack (allowing proper
1223 // tail calls), and has the same return value conventions as C calling convs.
1225 // This calling convention always arranges for the callee pop value to be 8n+4
1226 // bytes, which is needed for tail recursion elimination and stack alignment
1230 X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
1231 MachineFunction &MF = DAG.getMachineFunction();
1232 MachineFrameInfo *MFI = MF.getFrameInfo();
1233 SDOperand Root = Op.getOperand(0);
1234 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1235 unsigned CC = MF.getFunction()->getCallingConv();
1237 assert(!(isVarArg && CC == CallingConv::Fast) &&
1238 "Var args not supported with calling convention fastcc");
1240 // Assign locations to all of the incoming arguments.
1241 SmallVector<CCValAssign, 16> ArgLocs;
1242 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1243 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
1245 SmallVector<SDOperand, 8> ArgValues;
1246 unsigned LastVal = ~0U;
1247 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1248 CCValAssign &VA = ArgLocs[i];
1249 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1251 assert(VA.getValNo() != LastVal &&
1252 "Don't support value assigned to multiple locs yet");
1253 LastVal = VA.getValNo();
1255 if (VA.isRegLoc()) {
1256 MVT::ValueType RegVT = VA.getLocVT();
1257 TargetRegisterClass *RC;
1258 if (RegVT == MVT::i32)
1259 RC = X86::GR32RegisterClass;
1261 assert(MVT::isVector(RegVT));
1262 RC = X86::VR128RegisterClass;
1265 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1266 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1268 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1269 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1271 if (VA.getLocInfo() == CCValAssign::SExt)
1272 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1273 DAG.getValueType(VA.getValVT()));
1274 else if (VA.getLocInfo() == CCValAssign::ZExt)
1275 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1276 DAG.getValueType(VA.getValVT()));
1278 if (VA.getLocInfo() != CCValAssign::Full)
1279 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1281 ArgValues.push_back(ArgValue);
1283 assert(VA.isMemLoc());
1284 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1288 unsigned StackSize = CCInfo.getNextStackOffset();
1290 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1291 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1292 // arguments and the arguments after the retaddr has been pushed are
1294 if ((StackSize & 7) == 0)
1298 ArgValues.push_back(Root);
1300 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
1301 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1302 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
1303 BytesCallerReserves = 0;
1305 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1306 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1308 // Return the new list of results.
1309 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1310 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1314 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1315 const SDOperand &StackPtr,
1316 const CCValAssign &VA,
1319 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1320 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1321 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1322 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1323 if (Flags & ISD::ParamFlags::ByVal) {
1324 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1325 ISD::ParamFlags::ByValAlignOffs);
1327 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1328 ISD::ParamFlags::ByValSizeOffs;
1330 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1331 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1332 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1334 return DAG.getMemcpy(Chain, PtrOff, Arg, SizeNode, AlignNode,
1337 return DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1342 X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1344 SDOperand Chain = Op.getOperand(0);
1345 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1346 SDOperand Callee = Op.getOperand(4);
1348 assert(!cast<ConstantSDNode>(Op.getOperand(3))->getValue() &&
1349 "Tail calls should not reach here.");
1351 // Analyze operands of the call, assigning locations to each operand.
1352 SmallVector<CCValAssign, 16> ArgLocs;
1353 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1354 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1356 // Get a count of how many bytes are to be pushed on the stack.
1357 unsigned NumBytes = CCInfo.getNextStackOffset();
1358 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1359 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1360 // arguments and the arguments after the retaddr has been pushed are
1362 if ((NumBytes & 7) == 0)
1366 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1368 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1369 SmallVector<SDOperand, 8> MemOpChains;
1373 // Walk the register/memloc assignments, inserting copies/loads.
1374 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1375 CCValAssign &VA = ArgLocs[i];
1376 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1378 // Promote the value if needed.
1379 switch (VA.getLocInfo()) {
1380 default: assert(0 && "Unknown loc info!");
1381 case CCValAssign::Full: break;
1382 case CCValAssign::SExt:
1383 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1385 case CCValAssign::ZExt:
1386 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1388 case CCValAssign::AExt:
1389 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1393 if (VA.isRegLoc()) {
1394 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1396 assert(VA.isMemLoc());
1397 if (StackPtr.Val == 0)
1398 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1400 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1405 if (!MemOpChains.empty())
1406 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1407 &MemOpChains[0], MemOpChains.size());
1409 // Build a sequence of copy-to-reg nodes chained together with token chain
1410 // and flag operands which copy the outgoing args into registers.
1412 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1413 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1415 InFlag = Chain.getValue(1);
1418 // If the callee is a GlobalAddress node (quite common, every direct call is)
1419 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1420 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1421 // We should use extra load for direct calls to dllimported functions in
1423 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1424 getTargetMachine(), true))
1425 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1426 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1427 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1430 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1432 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1433 Subtarget->isPICStyleGOT()) {
1434 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1435 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1437 InFlag = Chain.getValue(1);
1440 // Returns a chain & a flag for retval copy to use.
1441 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1442 SmallVector<SDOperand, 8> Ops;
1443 Ops.push_back(Chain);
1444 Ops.push_back(Callee);
1446 // Add argument registers to the end of the list so that they are known live
1448 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1449 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1450 RegsToPass[i].second.getValueType()));
1452 // Add an implicit use GOT pointer in EBX.
1453 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1454 Subtarget->isPICStyleGOT())
1455 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1458 Ops.push_back(InFlag);
1460 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1461 InFlag = Chain.getValue(1);
1463 // Create the CALLSEQ_END node.
1464 unsigned NumBytesForCalleeToPush = NumBytes;
1466 // Returns a flag for retval copy to use.
1467 Chain = DAG.getCALLSEQ_END(Chain,
1468 DAG.getConstant(NumBytes, getPointerTy()),
1469 DAG.getConstant(NumBytesForCalleeToPush,
1472 InFlag = Chain.getValue(1);
1474 // Handle result values, copying them out of physregs into vregs that we
1476 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1479 //===----------------------------------------------------------------------===//
1480 // Fast Calling Convention (tail call) implementation
1481 //===----------------------------------------------------------------------===//
1483 // Like std call, callee cleans arguments, convention except that ECX is
1484 // reserved for storing the tail called function address. Only 2 registers are
1485 // free for argument passing (inreg). Tail call optimization is performed
1487 // * tailcallopt is enabled
1488 // * caller/callee are fastcc
1489 // * elf/pic is disabled OR
1490 // * elf/pic enabled + callee is in module + callee has
1491 // visibility protected or hidden
1492 // To keep the stack aligned according to platform abi the function
1493 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1494 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1495 // If a tail called function callee has more arguments than the caller the
1496 // caller needs to make sure that there is room to move the RETADDR to. This is
1497 // achieved by reserving an area the size of the argument delta right after the
1498 // original REtADDR, but before the saved framepointer or the spilled registers
1499 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1511 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1512 /// for a 16 byte align requirement.
1513 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1514 SelectionDAG& DAG) {
1515 if (PerformTailCallOpt) {
1516 MachineFunction &MF = DAG.getMachineFunction();
1517 const TargetMachine &TM = MF.getTarget();
1518 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1519 unsigned StackAlignment = TFI.getStackAlignment();
1520 uint64_t AlignMask = StackAlignment - 1;
1521 int64_t Offset = StackSize;
1522 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1523 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1524 // Number smaller than 12 so just add the difference.
1525 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1527 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1528 Offset = ((~AlignMask) & Offset) + StackAlignment +
1529 (StackAlignment-SlotSize);
1536 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1537 /// following the call is a return. A function is eligible if caller/callee
1538 /// calling conventions match, currently only fastcc supports tail calls, and
1539 /// the function CALL is immediatly followed by a RET.
1540 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1542 SelectionDAG& DAG) const {
1543 if (!PerformTailCallOpt)
1546 // Check whether CALL node immediatly preceeds the RET node and whether the
1547 // return uses the result of the node or is a void return.
1548 unsigned NumOps = Ret.getNumOperands();
1550 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1551 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1553 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1554 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1555 MachineFunction &MF = DAG.getMachineFunction();
1556 unsigned CallerCC = MF.getFunction()->getCallingConv();
1557 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1558 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1559 SDOperand Callee = Call.getOperand(4);
1560 // On elf/pic %ebx needs to be livein.
1561 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1562 !Subtarget->isPICStyleGOT())
1565 // Can only do local tail calls with PIC.
1566 GlobalValue * GV = 0;
1567 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1569 (GV = G->getGlobal()) &&
1570 (GV->hasHiddenVisibility() || GV->hasProtectedVisibility()))
1579 X86TargetLowering::LowerX86_TailCallTo(SDOperand Op, SelectionDAG &DAG,
1581 SDOperand Chain = Op.getOperand(0);
1582 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1583 SDOperand Callee = Op.getOperand(4);
1584 bool is64Bit = Subtarget->is64Bit();
1586 assert(cast<ConstantSDNode>(Op.getOperand(3))->getValue() &&PerformTailCallOpt
1587 && "Should only emit tail calls.");
1589 // Analyze operands of the call, assigning locations to each operand.
1590 SmallVector<CCValAssign, 16> ArgLocs;
1591 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1593 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1595 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1597 // Lower arguments at fp - stackoffset + fpdiff.
1598 MachineFunction &MF = DAG.getMachineFunction();
1600 unsigned NumBytesToBePushed =
1601 GetAlignedArgumentStackSize(CCInfo.getNextStackOffset(), DAG);
1603 unsigned NumBytesCallerPushed =
1604 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1605 int FPDiff = NumBytesCallerPushed - NumBytesToBePushed;
1607 // Set the delta of movement of the returnaddr stackslot.
1608 // But only set if delta is greater than previous delta.
1609 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1610 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1613 getCALLSEQ_START(Chain, DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1615 // Adjust the Return address stack slot.
1616 SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
1618 MVT::ValueType VT = is64Bit ? MVT::i64 : MVT::i32;
1619 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1620 // Load the "old" Return address.
1622 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1623 // Calculate the new stack slot for the return address.
1624 int SlotSize = is64Bit ? 8 : 4;
1625 int NewReturnAddrFI =
1626 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1627 NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1628 Chain = SDOperand(RetAddrFrIdx.Val, 1);
1631 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1632 SmallVector<SDOperand, 8> MemOpChains;
1633 SmallVector<SDOperand, 8> MemOpChains2;
1634 SDOperand FramePtr, StackPtr;
1639 // Walk the register/memloc assignments, inserting copies/loads. Lower
1640 // arguments first to the stack slot where they would normally - in case of a
1641 // normal function call - be.
1642 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1643 CCValAssign &VA = ArgLocs[i];
1644 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1646 // Promote the value if needed.
1647 switch (VA.getLocInfo()) {
1648 default: assert(0 && "Unknown loc info!");
1649 case CCValAssign::Full: break;
1650 case CCValAssign::SExt:
1651 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1653 case CCValAssign::ZExt:
1654 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1656 case CCValAssign::AExt:
1657 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1661 if (VA.isRegLoc()) {
1662 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1664 assert(VA.isMemLoc());
1665 if (StackPtr.Val == 0)
1666 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1668 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1673 if (!MemOpChains.empty())
1674 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1675 &MemOpChains[0], MemOpChains.size());
1677 // Build a sequence of copy-to-reg nodes chained together with token chain
1678 // and flag operands which copy the outgoing args into registers.
1680 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1681 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1683 InFlag = Chain.getValue(1);
1685 InFlag = SDOperand();
1687 // Copy from stack slots to stack slot of a tail called function. This needs
1688 // to be done because if we would lower the arguments directly to their real
1689 // stack slot we might end up overwriting each other.
1690 // TODO: To make this more efficient (sometimes saving a store/load) we could
1691 // analyse the arguments and emit this store/load/store sequence only for
1692 // arguments which would be overwritten otherwise.
1693 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1694 CCValAssign &VA = ArgLocs[i];
1695 if (!VA.isRegLoc()) {
1696 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1697 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1699 // Get source stack slot.
1700 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1701 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1702 // Create frame index.
1703 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1704 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1705 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1706 FIN = DAG.getFrameIndex(FI, MVT::i32);
1707 if (Flags & ISD::ParamFlags::ByVal) {
1708 // Copy relative to framepointer.
1709 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1710 ISD::ParamFlags::ByValAlignOffs);
1712 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1713 ISD::ParamFlags::ByValSizeOffs;
1715 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1716 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1717 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i1);
1719 MemOpChains2.push_back(DAG.getMemcpy(Chain, FIN, PtrOff, SizeNode,
1720 AlignNode,AlwaysInline));
1722 SDOperand LoadedArg = DAG.getLoad(VA.getValVT(), Chain, PtrOff, NULL,0);
1723 // Store relative to framepointer.
1724 MemOpChains2.push_back(DAG.getStore(Chain, LoadedArg, FIN, NULL, 0));
1729 if (!MemOpChains2.empty())
1730 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1731 &MemOpChains2[0], MemOpChains.size());
1733 // Store the return address to the appropriate stack slot.
1735 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1737 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1739 // Does not work with tail call since ebx is not restored correctly by
1740 // tailcaller. TODO: at least for x86 - verify for x86-64
1742 // If the callee is a GlobalAddress node (quite common, every direct call is)
1743 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1744 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1745 // We should use extra load for direct calls to dllimported functions in
1747 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1748 getTargetMachine(), true))
1749 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1750 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1751 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1753 assert(Callee.getOpcode() == ISD::LOAD &&
1754 "Function destination must be loaded into virtual register");
1755 unsigned Opc = is64Bit ? X86::R9 : X86::ECX;
1757 Chain = DAG.getCopyToReg(Chain,
1758 DAG.getRegister(Opc, getPointerTy()) ,
1760 Callee = DAG.getRegister(Opc, getPointerTy());
1761 // Add register as live out.
1762 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1765 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1766 SmallVector<SDOperand, 8> Ops;
1768 Ops.push_back(Chain);
1769 Ops.push_back(DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1770 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1772 Ops.push_back(InFlag);
1773 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1774 InFlag = Chain.getValue(1);
1776 // Returns a chain & a flag for retval copy to use.
1777 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1779 Ops.push_back(Chain);
1780 Ops.push_back(Callee);
1781 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1782 // Add argument registers to the end of the list so that they are known live
1784 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1785 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1786 RegsToPass[i].second.getValueType()));
1788 Ops.push_back(InFlag);
1789 assert(InFlag.Val &&
1790 "Flag must be set. Depend on flag being set in LowerRET");
1791 Chain = DAG.getNode(X86ISD::TAILCALL,
1792 Op.Val->getVTList(), &Ops[0], Ops.size());
1794 return SDOperand(Chain.Val, Op.ResNo);
1797 //===----------------------------------------------------------------------===//
1798 // X86-64 C Calling Convention implementation
1799 //===----------------------------------------------------------------------===//
1802 X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1803 MachineFunction &MF = DAG.getMachineFunction();
1804 MachineFrameInfo *MFI = MF.getFrameInfo();
1805 SDOperand Root = Op.getOperand(0);
1806 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1807 unsigned CC = MF.getFunction()->getCallingConv();
1809 assert(!(isVarArg && CC == CallingConv::Fast) &&
1810 "Var args not supported with calling convention fastcc");
1812 static const unsigned GPR64ArgRegs[] = {
1813 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1815 static const unsigned XMMArgRegs[] = {
1816 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1817 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1820 // Assign locations to all of the incoming arguments.
1821 SmallVector<CCValAssign, 16> ArgLocs;
1822 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1823 // Check for possible tail call calling convention.
1824 if (CC == CallingConv::Fast && PerformTailCallOpt)
1825 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_TailCall);
1827 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
1829 SmallVector<SDOperand, 8> ArgValues;
1830 unsigned LastVal = ~0U;
1831 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1832 CCValAssign &VA = ArgLocs[i];
1833 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1835 assert(VA.getValNo() != LastVal &&
1836 "Don't support value assigned to multiple locs yet");
1837 LastVal = VA.getValNo();
1839 if (VA.isRegLoc()) {
1840 MVT::ValueType RegVT = VA.getLocVT();
1841 TargetRegisterClass *RC;
1842 if (RegVT == MVT::i32)
1843 RC = X86::GR32RegisterClass;
1844 else if (RegVT == MVT::i64)
1845 RC = X86::GR64RegisterClass;
1846 else if (RegVT == MVT::f32)
1847 RC = X86::FR32RegisterClass;
1848 else if (RegVT == MVT::f64)
1849 RC = X86::FR64RegisterClass;
1851 assert(MVT::isVector(RegVT));
1852 if (MVT::getSizeInBits(RegVT) == 64) {
1853 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1856 RC = X86::VR128RegisterClass;
1859 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1860 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1862 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1863 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1865 if (VA.getLocInfo() == CCValAssign::SExt)
1866 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1867 DAG.getValueType(VA.getValVT()));
1868 else if (VA.getLocInfo() == CCValAssign::ZExt)
1869 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1870 DAG.getValueType(VA.getValVT()));
1872 if (VA.getLocInfo() != CCValAssign::Full)
1873 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1875 // Handle MMX values passed in GPRs.
1876 if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1877 MVT::getSizeInBits(RegVT) == 64)
1878 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1880 ArgValues.push_back(ArgValue);
1882 assert(VA.isMemLoc());
1883 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1887 unsigned StackSize = CCInfo.getNextStackOffset();
1888 // align stack specially for tail calls
1889 if (CC == CallingConv::Fast)
1890 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1892 // If the function takes variable number of arguments, make a frame index for
1893 // the start of the first vararg value... for expansion of llvm.va_start.
1895 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1896 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1898 // For X86-64, if there are vararg parameters that are passed via
1899 // registers, then we must store them to their spots on the stack so they
1900 // may be loaded by deferencing the result of va_next.
1901 VarArgsGPOffset = NumIntRegs * 8;
1902 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1903 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1904 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1906 // Store the integer parameter registers.
1907 SmallVector<SDOperand, 8> MemOps;
1908 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1909 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1910 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1911 for (; NumIntRegs != 6; ++NumIntRegs) {
1912 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1913 X86::GR64RegisterClass);
1914 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1915 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1916 MemOps.push_back(Store);
1917 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1918 DAG.getConstant(8, getPointerTy()));
1921 // Now store the XMM (fp + vector) parameter registers.
1922 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1923 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1924 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1925 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1926 X86::VR128RegisterClass);
1927 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1928 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1929 MemOps.push_back(Store);
1930 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1931 DAG.getConstant(16, getPointerTy()));
1933 if (!MemOps.empty())
1934 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1935 &MemOps[0], MemOps.size());
1938 ArgValues.push_back(Root);
1940 // Tail call convention (fastcc) needs callee pop.
1941 if (CC == CallingConv::Fast && PerformTailCallOpt) {
1942 BytesToPopOnReturn = StackSize; // Callee pops everything.
1943 BytesCallerReserves = 0;
1945 BytesToPopOnReturn = 0; // Callee pops nothing.
1946 BytesCallerReserves = StackSize;
1948 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1949 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1951 // Return the new list of results.
1952 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1953 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1957 X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1959 SDOperand Chain = Op.getOperand(0);
1960 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1961 SDOperand Callee = Op.getOperand(4);
1963 assert(!(isVarArg && CC == CallingConv::Fast) &&
1964 "Var args not supported with calling convention fastcc");
1966 // Analyze operands of the call, assigning locations to each operand.
1967 SmallVector<CCValAssign, 16> ArgLocs;
1968 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1969 if (CC==CallingConv::Fast && PerformTailCallOpt)
1970 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1972 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
1974 // Get a count of how many bytes are to be pushed on the stack.
1975 unsigned NumBytes = CCInfo.getNextStackOffset();
1976 if (CC == CallingConv::Fast)
1977 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1979 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1981 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1982 SmallVector<SDOperand, 8> MemOpChains;
1986 // Walk the register/memloc assignments, inserting copies/loads.
1987 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1988 CCValAssign &VA = ArgLocs[i];
1989 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1991 // Promote the value if needed.
1992 switch (VA.getLocInfo()) {
1993 default: assert(0 && "Unknown loc info!");
1994 case CCValAssign::Full: break;
1995 case CCValAssign::SExt:
1996 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1998 case CCValAssign::ZExt:
1999 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
2001 case CCValAssign::AExt:
2002 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
2006 if (VA.isRegLoc()) {
2007 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2009 assert(VA.isMemLoc());
2010 if (StackPtr.Val == 0)
2011 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
2013 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
2018 if (!MemOpChains.empty())
2019 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2020 &MemOpChains[0], MemOpChains.size());
2022 // Build a sequence of copy-to-reg nodes chained together with token chain
2023 // and flag operands which copy the outgoing args into registers.
2025 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2026 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
2028 InFlag = Chain.getValue(1);
2032 // From AMD64 ABI document:
2033 // For calls that may call functions that use varargs or stdargs
2034 // (prototype-less calls or calls to functions containing ellipsis (...) in
2035 // the declaration) %al is used as hidden argument to specify the number
2036 // of SSE registers used. The contents of %al do not need to match exactly
2037 // the number of registers, but must be an ubound on the number of SSE
2038 // registers used and is in the range 0 - 8 inclusive.
2040 // Count the number of XMM registers allocated.
2041 static const unsigned XMMArgRegs[] = {
2042 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2043 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2045 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2047 Chain = DAG.getCopyToReg(Chain, X86::AL,
2048 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2049 InFlag = Chain.getValue(1);
2052 // If the callee is a GlobalAddress node (quite common, every direct call is)
2053 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
2054 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2055 // We should use extra load for direct calls to dllimported functions in
2057 if (getTargetMachine().getCodeModel() != CodeModel::Large
2058 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
2059 getTargetMachine(), true))
2060 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
2061 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2062 if (getTargetMachine().getCodeModel() != CodeModel::Large)
2063 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
2066 // Returns a chain & a flag for retval copy to use.
2067 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2068 SmallVector<SDOperand, 8> Ops;
2069 Ops.push_back(Chain);
2070 Ops.push_back(Callee);
2072 // Add argument registers to the end of the list so that they are known live
2074 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2075 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2076 RegsToPass[i].second.getValueType()));
2079 Ops.push_back(InFlag);
2081 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
2082 InFlag = Chain.getValue(1);
2084 // Create the CALLSEQ_END node.
2085 unsigned NumBytesForCalleeToPush = 0;
2086 if (CC == CallingConv::Fast && PerformTailCallOpt) {
2087 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2089 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2092 // Returns a flag for retval copy to use.
2093 Chain = DAG.getCALLSEQ_END(Chain,
2094 DAG.getConstant(NumBytes, getPointerTy()),
2095 DAG.getConstant(NumBytesForCalleeToPush,
2098 InFlag = Chain.getValue(1);
2100 // Handle result values, copying them out of physregs into vregs that we
2102 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
2106 //===----------------------------------------------------------------------===//
2107 // Other Lowering Hooks
2108 //===----------------------------------------------------------------------===//
2111 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2112 MachineFunction &MF = DAG.getMachineFunction();
2113 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2114 int ReturnAddrIndex = FuncInfo->getRAIndex();
2116 if (ReturnAddrIndex == 0) {
2117 // Set up a frame object for the return address.
2118 if (Subtarget->is64Bit())
2119 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
2121 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
2123 FuncInfo->setRAIndex(ReturnAddrIndex);
2126 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2131 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
2132 /// specific condition code. It returns a false if it cannot do a direct
2133 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
2135 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2136 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
2137 SelectionDAG &DAG) {
2138 X86CC = X86::COND_INVALID;
2140 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2141 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2142 // X > -1 -> X == 0, jump !sign.
2143 RHS = DAG.getConstant(0, RHS.getValueType());
2144 X86CC = X86::COND_NS;
2146 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2147 // X < 0 -> X == 0, jump on sign.
2148 X86CC = X86::COND_S;
2150 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
2152 RHS = DAG.getConstant(0, RHS.getValueType());
2153 X86CC = X86::COND_LE;
2158 switch (SetCCOpcode) {
2160 case ISD::SETEQ: X86CC = X86::COND_E; break;
2161 case ISD::SETGT: X86CC = X86::COND_G; break;
2162 case ISD::SETGE: X86CC = X86::COND_GE; break;
2163 case ISD::SETLT: X86CC = X86::COND_L; break;
2164 case ISD::SETLE: X86CC = X86::COND_LE; break;
2165 case ISD::SETNE: X86CC = X86::COND_NE; break;
2166 case ISD::SETULT: X86CC = X86::COND_B; break;
2167 case ISD::SETUGT: X86CC = X86::COND_A; break;
2168 case ISD::SETULE: X86CC = X86::COND_BE; break;
2169 case ISD::SETUGE: X86CC = X86::COND_AE; break;
2172 // On a floating point condition, the flags are set as follows:
2174 // 0 | 0 | 0 | X > Y
2175 // 0 | 0 | 1 | X < Y
2176 // 1 | 0 | 0 | X == Y
2177 // 1 | 1 | 1 | unordered
2179 switch (SetCCOpcode) {
2182 case ISD::SETEQ: X86CC = X86::COND_E; break;
2183 case ISD::SETOLT: Flip = true; // Fallthrough
2185 case ISD::SETGT: X86CC = X86::COND_A; break;
2186 case ISD::SETOLE: Flip = true; // Fallthrough
2188 case ISD::SETGE: X86CC = X86::COND_AE; break;
2189 case ISD::SETUGT: Flip = true; // Fallthrough
2191 case ISD::SETLT: X86CC = X86::COND_B; break;
2192 case ISD::SETUGE: Flip = true; // Fallthrough
2194 case ISD::SETLE: X86CC = X86::COND_BE; break;
2196 case ISD::SETNE: X86CC = X86::COND_NE; break;
2197 case ISD::SETUO: X86CC = X86::COND_P; break;
2198 case ISD::SETO: X86CC = X86::COND_NP; break;
2201 std::swap(LHS, RHS);
2204 return X86CC != X86::COND_INVALID;
2207 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2208 /// code. Current x86 isa includes the following FP cmov instructions:
2209 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2210 static bool hasFPCMov(unsigned X86CC) {
2226 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2227 /// true if Op is undef or if its value falls within the specified range (L, H].
2228 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2229 if (Op.getOpcode() == ISD::UNDEF)
2232 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2233 return (Val >= Low && Val < Hi);
2236 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2237 /// true if Op is undef or if its value equal to the specified value.
2238 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2239 if (Op.getOpcode() == ISD::UNDEF)
2241 return cast<ConstantSDNode>(Op)->getValue() == Val;
2244 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2245 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2246 bool X86::isPSHUFDMask(SDNode *N) {
2247 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2249 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2252 // Check if the value doesn't reference the second vector.
2253 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2254 SDOperand Arg = N->getOperand(i);
2255 if (Arg.getOpcode() == ISD::UNDEF) continue;
2256 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2257 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2264 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2265 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2266 bool X86::isPSHUFHWMask(SDNode *N) {
2267 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2269 if (N->getNumOperands() != 8)
2272 // Lower quadword copied in order.
2273 for (unsigned i = 0; i != 4; ++i) {
2274 SDOperand Arg = N->getOperand(i);
2275 if (Arg.getOpcode() == ISD::UNDEF) continue;
2276 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2277 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2281 // Upper quadword shuffled.
2282 for (unsigned i = 4; i != 8; ++i) {
2283 SDOperand Arg = N->getOperand(i);
2284 if (Arg.getOpcode() == ISD::UNDEF) continue;
2285 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2286 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2287 if (Val < 4 || Val > 7)
2294 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2295 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2296 bool X86::isPSHUFLWMask(SDNode *N) {
2297 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2299 if (N->getNumOperands() != 8)
2302 // Upper quadword copied in order.
2303 for (unsigned i = 4; i != 8; ++i)
2304 if (!isUndefOrEqual(N->getOperand(i), i))
2307 // Lower quadword shuffled.
2308 for (unsigned i = 0; i != 4; ++i)
2309 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2315 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2316 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2317 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2318 if (NumElems != 2 && NumElems != 4) return false;
2320 unsigned Half = NumElems / 2;
2321 for (unsigned i = 0; i < Half; ++i)
2322 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2324 for (unsigned i = Half; i < NumElems; ++i)
2325 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2331 bool X86::isSHUFPMask(SDNode *N) {
2332 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2333 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2336 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2337 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2338 /// half elements to come from vector 1 (which would equal the dest.) and
2339 /// the upper half to come from vector 2.
2340 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2341 if (NumOps != 2 && NumOps != 4) return false;
2343 unsigned Half = NumOps / 2;
2344 for (unsigned i = 0; i < Half; ++i)
2345 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2347 for (unsigned i = Half; i < NumOps; ++i)
2348 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2353 static bool isCommutedSHUFP(SDNode *N) {
2354 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2355 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2358 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2359 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2360 bool X86::isMOVHLPSMask(SDNode *N) {
2361 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2363 if (N->getNumOperands() != 4)
2366 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2367 return isUndefOrEqual(N->getOperand(0), 6) &&
2368 isUndefOrEqual(N->getOperand(1), 7) &&
2369 isUndefOrEqual(N->getOperand(2), 2) &&
2370 isUndefOrEqual(N->getOperand(3), 3);
2373 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2374 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2376 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2377 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2379 if (N->getNumOperands() != 4)
2382 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2383 return isUndefOrEqual(N->getOperand(0), 2) &&
2384 isUndefOrEqual(N->getOperand(1), 3) &&
2385 isUndefOrEqual(N->getOperand(2), 2) &&
2386 isUndefOrEqual(N->getOperand(3), 3);
2389 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2390 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2391 bool X86::isMOVLPMask(SDNode *N) {
2392 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2394 unsigned NumElems = N->getNumOperands();
2395 if (NumElems != 2 && NumElems != 4)
2398 for (unsigned i = 0; i < NumElems/2; ++i)
2399 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2402 for (unsigned i = NumElems/2; i < NumElems; ++i)
2403 if (!isUndefOrEqual(N->getOperand(i), i))
2409 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2410 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2412 bool X86::isMOVHPMask(SDNode *N) {
2413 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2415 unsigned NumElems = N->getNumOperands();
2416 if (NumElems != 2 && NumElems != 4)
2419 for (unsigned i = 0; i < NumElems/2; ++i)
2420 if (!isUndefOrEqual(N->getOperand(i), i))
2423 for (unsigned i = 0; i < NumElems/2; ++i) {
2424 SDOperand Arg = N->getOperand(i + NumElems/2);
2425 if (!isUndefOrEqual(Arg, i + NumElems))
2432 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2433 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2434 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2435 bool V2IsSplat = false) {
2436 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2439 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2440 SDOperand BitI = Elts[i];
2441 SDOperand BitI1 = Elts[i+1];
2442 if (!isUndefOrEqual(BitI, j))
2445 if (isUndefOrEqual(BitI1, NumElts))
2448 if (!isUndefOrEqual(BitI1, j + NumElts))
2456 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2457 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2458 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2461 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2462 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2463 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2464 bool V2IsSplat = false) {
2465 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2468 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2469 SDOperand BitI = Elts[i];
2470 SDOperand BitI1 = Elts[i+1];
2471 if (!isUndefOrEqual(BitI, j + NumElts/2))
2474 if (isUndefOrEqual(BitI1, NumElts))
2477 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2485 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2486 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2487 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2490 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2491 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2493 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2494 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2496 unsigned NumElems = N->getNumOperands();
2497 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2500 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2501 SDOperand BitI = N->getOperand(i);
2502 SDOperand BitI1 = N->getOperand(i+1);
2504 if (!isUndefOrEqual(BitI, j))
2506 if (!isUndefOrEqual(BitI1, j))
2513 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2514 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2516 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2517 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2519 unsigned NumElems = N->getNumOperands();
2520 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2523 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2524 SDOperand BitI = N->getOperand(i);
2525 SDOperand BitI1 = N->getOperand(i + 1);
2527 if (!isUndefOrEqual(BitI, j))
2529 if (!isUndefOrEqual(BitI1, j))
2536 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2537 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2538 /// MOVSD, and MOVD, i.e. setting the lowest element.
2539 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2540 if (NumElts != 2 && NumElts != 4)
2543 if (!isUndefOrEqual(Elts[0], NumElts))
2546 for (unsigned i = 1; i < NumElts; ++i) {
2547 if (!isUndefOrEqual(Elts[i], i))
2554 bool X86::isMOVLMask(SDNode *N) {
2555 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2556 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2559 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2560 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2561 /// element of vector 2 and the other elements to come from vector 1 in order.
2562 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2563 bool V2IsSplat = false,
2564 bool V2IsUndef = false) {
2565 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2568 if (!isUndefOrEqual(Ops[0], 0))
2571 for (unsigned i = 1; i < NumOps; ++i) {
2572 SDOperand Arg = Ops[i];
2573 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2574 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2575 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2582 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2583 bool V2IsUndef = false) {
2584 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2585 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2586 V2IsSplat, V2IsUndef);
2589 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2590 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2591 bool X86::isMOVSHDUPMask(SDNode *N) {
2592 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2594 if (N->getNumOperands() != 4)
2597 // Expect 1, 1, 3, 3
2598 for (unsigned i = 0; i < 2; ++i) {
2599 SDOperand Arg = N->getOperand(i);
2600 if (Arg.getOpcode() == ISD::UNDEF) continue;
2601 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2602 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2603 if (Val != 1) return false;
2607 for (unsigned i = 2; i < 4; ++i) {
2608 SDOperand Arg = N->getOperand(i);
2609 if (Arg.getOpcode() == ISD::UNDEF) continue;
2610 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2611 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2612 if (Val != 3) return false;
2616 // Don't use movshdup if it can be done with a shufps.
2620 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2621 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2622 bool X86::isMOVSLDUPMask(SDNode *N) {
2623 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2625 if (N->getNumOperands() != 4)
2628 // Expect 0, 0, 2, 2
2629 for (unsigned i = 0; i < 2; ++i) {
2630 SDOperand Arg = N->getOperand(i);
2631 if (Arg.getOpcode() == ISD::UNDEF) continue;
2632 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2633 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2634 if (Val != 0) return false;
2638 for (unsigned i = 2; i < 4; ++i) {
2639 SDOperand Arg = N->getOperand(i);
2640 if (Arg.getOpcode() == ISD::UNDEF) continue;
2641 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2642 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2643 if (Val != 2) return false;
2647 // Don't use movshdup if it can be done with a shufps.
2651 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2652 /// specifies a identity operation on the LHS or RHS.
2653 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2654 unsigned NumElems = N->getNumOperands();
2655 for (unsigned i = 0; i < NumElems; ++i)
2656 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2661 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2662 /// a splat of a single element.
2663 static bool isSplatMask(SDNode *N) {
2664 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2666 // This is a splat operation if each element of the permute is the same, and
2667 // if the value doesn't reference the second vector.
2668 unsigned NumElems = N->getNumOperands();
2669 SDOperand ElementBase;
2671 for (; i != NumElems; ++i) {
2672 SDOperand Elt = N->getOperand(i);
2673 if (isa<ConstantSDNode>(Elt)) {
2679 if (!ElementBase.Val)
2682 for (; i != NumElems; ++i) {
2683 SDOperand Arg = N->getOperand(i);
2684 if (Arg.getOpcode() == ISD::UNDEF) continue;
2685 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2686 if (Arg != ElementBase) return false;
2689 // Make sure it is a splat of the first vector operand.
2690 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2693 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2694 /// a splat of a single element and it's a 2 or 4 element mask.
2695 bool X86::isSplatMask(SDNode *N) {
2696 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2698 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2699 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2701 return ::isSplatMask(N);
2704 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2705 /// specifies a splat of zero element.
2706 bool X86::isSplatLoMask(SDNode *N) {
2707 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2709 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2710 if (!isUndefOrEqual(N->getOperand(i), 0))
2715 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2716 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2718 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2719 unsigned NumOperands = N->getNumOperands();
2720 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2722 for (unsigned i = 0; i < NumOperands; ++i) {
2724 SDOperand Arg = N->getOperand(NumOperands-i-1);
2725 if (Arg.getOpcode() != ISD::UNDEF)
2726 Val = cast<ConstantSDNode>(Arg)->getValue();
2727 if (Val >= NumOperands) Val -= NumOperands;
2729 if (i != NumOperands - 1)
2736 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2737 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2739 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2741 // 8 nodes, but we only care about the last 4.
2742 for (unsigned i = 7; i >= 4; --i) {
2744 SDOperand Arg = N->getOperand(i);
2745 if (Arg.getOpcode() != ISD::UNDEF)
2746 Val = cast<ConstantSDNode>(Arg)->getValue();
2755 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2756 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2758 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2760 // 8 nodes, but we only care about the first 4.
2761 for (int i = 3; i >= 0; --i) {
2763 SDOperand Arg = N->getOperand(i);
2764 if (Arg.getOpcode() != ISD::UNDEF)
2765 Val = cast<ConstantSDNode>(Arg)->getValue();
2774 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2775 /// specifies a 8 element shuffle that can be broken into a pair of
2776 /// PSHUFHW and PSHUFLW.
2777 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2778 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2780 if (N->getNumOperands() != 8)
2783 // Lower quadword shuffled.
2784 for (unsigned i = 0; i != 4; ++i) {
2785 SDOperand Arg = N->getOperand(i);
2786 if (Arg.getOpcode() == ISD::UNDEF) continue;
2787 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2788 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2793 // Upper quadword shuffled.
2794 for (unsigned i = 4; i != 8; ++i) {
2795 SDOperand Arg = N->getOperand(i);
2796 if (Arg.getOpcode() == ISD::UNDEF) continue;
2797 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2798 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2799 if (Val < 4 || Val > 7)
2806 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2807 /// values in ther permute mask.
2808 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2809 SDOperand &V2, SDOperand &Mask,
2810 SelectionDAG &DAG) {
2811 MVT::ValueType VT = Op.getValueType();
2812 MVT::ValueType MaskVT = Mask.getValueType();
2813 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2814 unsigned NumElems = Mask.getNumOperands();
2815 SmallVector<SDOperand, 8> MaskVec;
2817 for (unsigned i = 0; i != NumElems; ++i) {
2818 SDOperand Arg = Mask.getOperand(i);
2819 if (Arg.getOpcode() == ISD::UNDEF) {
2820 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2823 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2824 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2826 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2828 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2832 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2833 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2836 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2837 /// the two vector operands have swapped position.
2839 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2840 MVT::ValueType MaskVT = Mask.getValueType();
2841 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2842 unsigned NumElems = Mask.getNumOperands();
2843 SmallVector<SDOperand, 8> MaskVec;
2844 for (unsigned i = 0; i != NumElems; ++i) {
2845 SDOperand Arg = Mask.getOperand(i);
2846 if (Arg.getOpcode() == ISD::UNDEF) {
2847 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2850 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2851 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2853 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2855 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2857 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2861 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2862 /// match movhlps. The lower half elements should come from upper half of
2863 /// V1 (and in order), and the upper half elements should come from the upper
2864 /// half of V2 (and in order).
2865 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2866 unsigned NumElems = Mask->getNumOperands();
2869 for (unsigned i = 0, e = 2; i != e; ++i)
2870 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2872 for (unsigned i = 2; i != 4; ++i)
2873 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2878 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2879 /// is promoted to a vector.
2880 static inline bool isScalarLoadToVector(SDNode *N) {
2881 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2882 N = N->getOperand(0).Val;
2883 return ISD::isNON_EXTLoad(N);
2888 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2889 /// match movlp{s|d}. The lower half elements should come from lower half of
2890 /// V1 (and in order), and the upper half elements should come from the upper
2891 /// half of V2 (and in order). And since V1 will become the source of the
2892 /// MOVLP, it must be either a vector load or a scalar load to vector.
2893 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2894 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2896 // Is V2 is a vector load, don't do this transformation. We will try to use
2897 // load folding shufps op.
2898 if (ISD::isNON_EXTLoad(V2))
2901 unsigned NumElems = Mask->getNumOperands();
2902 if (NumElems != 2 && NumElems != 4)
2904 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2905 if (!isUndefOrEqual(Mask->getOperand(i), i))
2907 for (unsigned i = NumElems/2; i != NumElems; ++i)
2908 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2913 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2915 static bool isSplatVector(SDNode *N) {
2916 if (N->getOpcode() != ISD::BUILD_VECTOR)
2919 SDOperand SplatValue = N->getOperand(0);
2920 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2921 if (N->getOperand(i) != SplatValue)
2926 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2928 static bool isUndefShuffle(SDNode *N) {
2929 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2932 SDOperand V1 = N->getOperand(0);
2933 SDOperand V2 = N->getOperand(1);
2934 SDOperand Mask = N->getOperand(2);
2935 unsigned NumElems = Mask.getNumOperands();
2936 for (unsigned i = 0; i != NumElems; ++i) {
2937 SDOperand Arg = Mask.getOperand(i);
2938 if (Arg.getOpcode() != ISD::UNDEF) {
2939 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2940 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2942 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2949 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2951 static inline bool isZeroNode(SDOperand Elt) {
2952 return ((isa<ConstantSDNode>(Elt) &&
2953 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2954 (isa<ConstantFPSDNode>(Elt) &&
2955 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2958 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2959 /// to an zero vector.
2960 static bool isZeroShuffle(SDNode *N) {
2961 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2964 SDOperand V1 = N->getOperand(0);
2965 SDOperand V2 = N->getOperand(1);
2966 SDOperand Mask = N->getOperand(2);
2967 unsigned NumElems = Mask.getNumOperands();
2968 for (unsigned i = 0; i != NumElems; ++i) {
2969 SDOperand Arg = Mask.getOperand(i);
2970 if (Arg.getOpcode() == ISD::UNDEF)
2973 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2974 if (Idx < NumElems) {
2975 unsigned Opc = V1.Val->getOpcode();
2976 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2978 if (Opc != ISD::BUILD_VECTOR ||
2979 !isZeroNode(V1.Val->getOperand(Idx)))
2981 } else if (Idx >= NumElems) {
2982 unsigned Opc = V2.Val->getOpcode();
2983 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2985 if (Opc != ISD::BUILD_VECTOR ||
2986 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2993 /// getZeroVector - Returns a vector of specified type with all zero elements.
2995 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2996 assert(MVT::isVector(VT) && "Expected a vector type");
2998 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2999 // type. This ensures they get CSE'd.
3000 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
3002 if (MVT::getSizeInBits(VT) == 64) // MMX
3003 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
3005 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
3006 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
3009 /// getOnesVector - Returns a vector of specified type with all bits set.
3011 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
3012 assert(MVT::isVector(VT) && "Expected a vector type");
3014 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3015 // type. This ensures they get CSE'd.
3016 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
3018 if (MVT::getSizeInBits(VT) == 64) // MMX
3019 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
3021 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
3022 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
3026 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3027 /// that point to V2 points to its first element.
3028 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
3029 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
3031 bool Changed = false;
3032 SmallVector<SDOperand, 8> MaskVec;
3033 unsigned NumElems = Mask.getNumOperands();
3034 for (unsigned i = 0; i != NumElems; ++i) {
3035 SDOperand Arg = Mask.getOperand(i);
3036 if (Arg.getOpcode() != ISD::UNDEF) {
3037 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
3038 if (Val > NumElems) {
3039 Arg = DAG.getConstant(NumElems, Arg.getValueType());
3043 MaskVec.push_back(Arg);
3047 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
3048 &MaskVec[0], MaskVec.size());
3052 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3053 /// operation of specified width.
3054 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
3055 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3056 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3058 SmallVector<SDOperand, 8> MaskVec;
3059 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
3060 for (unsigned i = 1; i != NumElems; ++i)
3061 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3062 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3065 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
3066 /// of specified width.
3067 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
3068 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3069 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3070 SmallVector<SDOperand, 8> MaskVec;
3071 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3072 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3073 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
3075 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3078 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3079 /// of specified width.
3080 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
3081 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3082 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3083 unsigned Half = NumElems/2;
3084 SmallVector<SDOperand, 8> MaskVec;
3085 for (unsigned i = 0; i != Half; ++i) {
3086 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3087 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3089 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3092 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
3094 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
3095 SDOperand V1 = Op.getOperand(0);
3096 SDOperand Mask = Op.getOperand(2);
3097 MVT::ValueType VT = Op.getValueType();
3098 unsigned NumElems = Mask.getNumOperands();
3099 Mask = getUnpacklMask(NumElems, DAG);
3100 while (NumElems != 4) {
3101 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
3104 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
3106 Mask = getZeroVector(MVT::v4i32, DAG);
3107 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
3108 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
3109 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3112 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3113 /// vector of zero or undef vector. This produces a shuffle where the low
3114 /// element of V2 is swizzled into the zero/undef vector, landing at element
3115 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3116 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
3117 unsigned NumElems, unsigned Idx,
3118 bool isZero, SelectionDAG &DAG) {
3119 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
3120 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3121 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3122 SmallVector<SDOperand, 16> MaskVec;
3123 for (unsigned i = 0; i != NumElems; ++i)
3124 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3125 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3127 MaskVec.push_back(DAG.getConstant(i, EVT));
3128 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3129 &MaskVec[0], MaskVec.size());
3130 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3133 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3135 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
3136 unsigned NumNonZero, unsigned NumZero,
3137 SelectionDAG &DAG, TargetLowering &TLI) {
3143 for (unsigned i = 0; i < 16; ++i) {
3144 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3145 if (ThisIsNonZero && First) {
3147 V = getZeroVector(MVT::v8i16, DAG);
3149 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3154 SDOperand ThisElt(0, 0), LastElt(0, 0);
3155 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3156 if (LastIsNonZero) {
3157 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3159 if (ThisIsNonZero) {
3160 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3161 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3162 ThisElt, DAG.getConstant(8, MVT::i8));
3164 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3169 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3170 DAG.getConstant(i/2, TLI.getPointerTy()));
3174 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3177 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3179 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3180 unsigned NumNonZero, unsigned NumZero,
3181 SelectionDAG &DAG, TargetLowering &TLI) {
3187 for (unsigned i = 0; i < 8; ++i) {
3188 bool isNonZero = (NonZeros & (1 << i)) != 0;
3192 V = getZeroVector(MVT::v8i16, DAG);
3194 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3197 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3198 DAG.getConstant(i, TLI.getPointerTy()));
3206 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3207 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3208 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3209 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3210 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3211 // eliminated on x86-32 hosts.
3212 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3215 if (ISD::isBuildVectorAllOnes(Op.Val))
3216 return getOnesVector(Op.getValueType(), DAG);
3217 return getZeroVector(Op.getValueType(), DAG);
3220 MVT::ValueType VT = Op.getValueType();
3221 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3222 unsigned EVTBits = MVT::getSizeInBits(EVT);
3224 unsigned NumElems = Op.getNumOperands();
3225 unsigned NumZero = 0;
3226 unsigned NumNonZero = 0;
3227 unsigned NonZeros = 0;
3228 bool HasNonImms = false;
3229 SmallSet<SDOperand, 8> Values;
3230 for (unsigned i = 0; i < NumElems; ++i) {
3231 SDOperand Elt = Op.getOperand(i);
3232 if (Elt.getOpcode() == ISD::UNDEF)
3235 if (Elt.getOpcode() != ISD::Constant &&
3236 Elt.getOpcode() != ISD::ConstantFP)
3238 if (isZeroNode(Elt))
3241 NonZeros |= (1 << i);
3246 if (NumNonZero == 0) {
3247 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3248 return DAG.getNode(ISD::UNDEF, VT);
3251 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3252 if (Values.size() == 1)
3255 // Special case for single non-zero element.
3256 if (NumNonZero == 1 && NumElems <= 4) {
3257 unsigned Idx = CountTrailingZeros_32(NonZeros);
3258 SDOperand Item = Op.getOperand(Idx);
3259 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3261 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3262 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
3264 else if (!HasNonImms) // Otherwise, it's better to do a constpool load.
3267 if (EVTBits == 32) {
3268 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3269 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
3271 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3272 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3273 SmallVector<SDOperand, 8> MaskVec;
3274 for (unsigned i = 0; i < NumElems; i++)
3275 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3276 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3277 &MaskVec[0], MaskVec.size());
3278 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3279 DAG.getNode(ISD::UNDEF, VT), Mask);
3283 // A vector full of immediates; various special cases are already
3284 // handled, so this is best done with a single constant-pool load.
3288 // Let legalizer expand 2-wide build_vectors.
3292 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3293 if (EVTBits == 8 && NumElems == 16) {
3294 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3296 if (V.Val) return V;
3299 if (EVTBits == 16 && NumElems == 8) {
3300 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3302 if (V.Val) return V;
3305 // If element VT is == 32 bits, turn it into a number of shuffles.
3306 SmallVector<SDOperand, 8> V;
3308 if (NumElems == 4 && NumZero > 0) {
3309 for (unsigned i = 0; i < 4; ++i) {
3310 bool isZero = !(NonZeros & (1 << i));
3312 V[i] = getZeroVector(VT, DAG);
3314 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3317 for (unsigned i = 0; i < 2; ++i) {
3318 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3321 V[i] = V[i*2]; // Must be a zero vector.
3324 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3325 getMOVLMask(NumElems, DAG));
3328 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3329 getMOVLMask(NumElems, DAG));
3332 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3333 getUnpacklMask(NumElems, DAG));
3338 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3339 // clears the upper bits.
3340 // FIXME: we can do the same for v4f32 case when we know both parts of
3341 // the lower half come from scalar_to_vector (loadf32). We should do
3342 // that in post legalizer dag combiner with target specific hooks.
3343 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3345 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3346 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3347 SmallVector<SDOperand, 8> MaskVec;
3348 bool Reverse = (NonZeros & 0x3) == 2;
3349 for (unsigned i = 0; i < 2; ++i)
3351 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3353 MaskVec.push_back(DAG.getConstant(i, EVT));
3354 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3355 for (unsigned i = 0; i < 2; ++i)
3357 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3359 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3360 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3361 &MaskVec[0], MaskVec.size());
3362 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3365 if (Values.size() > 2) {
3366 // Expand into a number of unpckl*.
3368 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3369 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3370 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3371 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3372 for (unsigned i = 0; i < NumElems; ++i)
3373 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3375 while (NumElems != 0) {
3376 for (unsigned i = 0; i < NumElems; ++i)
3377 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3388 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3389 SDOperand PermMask, SelectionDAG &DAG,
3390 TargetLowering &TLI) {
3392 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3393 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3394 MVT::ValueType PtrVT = TLI.getPointerTy();
3395 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3396 PermMask.Val->op_end());
3398 // First record which half of which vector the low elements come from.
3399 SmallVector<unsigned, 4> LowQuad(4);
3400 for (unsigned i = 0; i < 4; ++i) {
3401 SDOperand Elt = MaskElts[i];
3402 if (Elt.getOpcode() == ISD::UNDEF)
3404 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3405 int QuadIdx = EltIdx / 4;
3408 int BestLowQuad = -1;
3409 unsigned MaxQuad = 1;
3410 for (unsigned i = 0; i < 4; ++i) {
3411 if (LowQuad[i] > MaxQuad) {
3413 MaxQuad = LowQuad[i];
3417 // Record which half of which vector the high elements come from.
3418 SmallVector<unsigned, 4> HighQuad(4);
3419 for (unsigned i = 4; i < 8; ++i) {
3420 SDOperand Elt = MaskElts[i];
3421 if (Elt.getOpcode() == ISD::UNDEF)
3423 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3424 int QuadIdx = EltIdx / 4;
3425 ++HighQuad[QuadIdx];
3427 int BestHighQuad = -1;
3429 for (unsigned i = 0; i < 4; ++i) {
3430 if (HighQuad[i] > MaxQuad) {
3432 MaxQuad = HighQuad[i];
3436 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3437 if (BestLowQuad != -1 || BestHighQuad != -1) {
3438 // First sort the 4 chunks in order using shufpd.
3439 SmallVector<SDOperand, 8> MaskVec;
3440 if (BestLowQuad != -1)
3441 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3443 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3444 if (BestHighQuad != -1)
3445 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3447 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3448 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3449 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3450 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3451 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3452 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3454 // Now sort high and low parts separately.
3455 BitVector InOrder(8);
3456 if (BestLowQuad != -1) {
3457 // Sort lower half in order using PSHUFLW.
3459 bool AnyOutOrder = false;
3460 for (unsigned i = 0; i != 4; ++i) {
3461 SDOperand Elt = MaskElts[i];
3462 if (Elt.getOpcode() == ISD::UNDEF) {
3463 MaskVec.push_back(Elt);
3466 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3469 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3470 // If this element is in the right place after this shuffle, then
3472 if ((int)(EltIdx / 4) == BestLowQuad)
3477 for (unsigned i = 4; i != 8; ++i)
3478 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3479 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3480 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3484 if (BestHighQuad != -1) {
3485 // Sort high half in order using PSHUFHW if possible.
3487 for (unsigned i = 0; i != 4; ++i)
3488 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3489 bool AnyOutOrder = false;
3490 for (unsigned i = 4; i != 8; ++i) {
3491 SDOperand Elt = MaskElts[i];
3492 if (Elt.getOpcode() == ISD::UNDEF) {
3493 MaskVec.push_back(Elt);
3496 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3499 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3500 // If this element is in the right place after this shuffle, then
3502 if ((int)(EltIdx / 4) == BestHighQuad)
3507 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3508 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3512 // The other elements are put in the right place using pextrw and pinsrw.
3513 for (unsigned i = 0; i != 8; ++i) {
3516 SDOperand Elt = MaskElts[i];
3517 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3520 SDOperand ExtOp = (EltIdx < 8)
3521 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3522 DAG.getConstant(EltIdx, PtrVT))
3523 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3524 DAG.getConstant(EltIdx - 8, PtrVT));
3525 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3526 DAG.getConstant(i, PtrVT));
3531 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3532 ///as few as possible.
3533 // First, let's find out how many elements are already in the right order.
3534 unsigned V1InOrder = 0;
3535 unsigned V1FromV1 = 0;
3536 unsigned V2InOrder = 0;
3537 unsigned V2FromV2 = 0;
3538 SmallVector<SDOperand, 8> V1Elts;
3539 SmallVector<SDOperand, 8> V2Elts;
3540 for (unsigned i = 0; i < 8; ++i) {
3541 SDOperand Elt = MaskElts[i];
3542 if (Elt.getOpcode() == ISD::UNDEF) {
3543 V1Elts.push_back(Elt);
3544 V2Elts.push_back(Elt);
3549 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3551 V1Elts.push_back(Elt);
3552 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3554 } else if (EltIdx == i+8) {
3555 V1Elts.push_back(Elt);
3556 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3558 } else if (EltIdx < 8) {
3559 V1Elts.push_back(Elt);
3562 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3567 if (V2InOrder > V1InOrder) {
3568 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3570 std::swap(V1Elts, V2Elts);
3571 std::swap(V1FromV1, V2FromV2);
3574 if ((V1FromV1 + V1InOrder) != 8) {
3575 // Some elements are from V2.
3577 // If there are elements that are from V1 but out of place,
3578 // then first sort them in place
3579 SmallVector<SDOperand, 8> MaskVec;
3580 for (unsigned i = 0; i < 8; ++i) {
3581 SDOperand Elt = V1Elts[i];
3582 if (Elt.getOpcode() == ISD::UNDEF) {
3583 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3586 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3588 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3590 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3592 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3593 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3597 for (unsigned i = 0; i < 8; ++i) {
3598 SDOperand Elt = V1Elts[i];
3599 if (Elt.getOpcode() == ISD::UNDEF)
3601 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3604 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3605 DAG.getConstant(EltIdx - 8, PtrVT));
3606 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3607 DAG.getConstant(i, PtrVT));
3611 // All elements are from V1.
3613 for (unsigned i = 0; i < 8; ++i) {
3614 SDOperand Elt = V1Elts[i];
3615 if (Elt.getOpcode() == ISD::UNDEF)
3617 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3618 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3619 DAG.getConstant(EltIdx, PtrVT));
3620 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3621 DAG.getConstant(i, PtrVT));
3627 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3628 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3629 /// done when every pair / quad of shuffle mask elements point to elements in
3630 /// the right sequence. e.g.
3631 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3633 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3635 SDOperand PermMask, SelectionDAG &DAG,
3636 TargetLowering &TLI) {
3637 unsigned NumElems = PermMask.getNumOperands();
3638 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3639 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3640 MVT::ValueType NewVT = MaskVT;
3642 case MVT::v4f32: NewVT = MVT::v2f64; break;
3643 case MVT::v4i32: NewVT = MVT::v2i64; break;
3644 case MVT::v8i16: NewVT = MVT::v4i32; break;
3645 case MVT::v16i8: NewVT = MVT::v4i32; break;
3646 default: assert(false && "Unexpected!");
3650 if (MVT::isInteger(VT))
3654 unsigned Scale = NumElems / NewWidth;
3655 SmallVector<SDOperand, 8> MaskVec;
3656 for (unsigned i = 0; i < NumElems; i += Scale) {
3657 unsigned StartIdx = ~0U;
3658 for (unsigned j = 0; j < Scale; ++j) {
3659 SDOperand Elt = PermMask.getOperand(i+j);
3660 if (Elt.getOpcode() == ISD::UNDEF)
3662 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3663 if (StartIdx == ~0U)
3664 StartIdx = EltIdx - (EltIdx % Scale);
3665 if (EltIdx != StartIdx + j)
3668 if (StartIdx == ~0U)
3669 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3671 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3674 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3675 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3676 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3677 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3678 &MaskVec[0], MaskVec.size()));
3682 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3683 SDOperand V1 = Op.getOperand(0);
3684 SDOperand V2 = Op.getOperand(1);
3685 SDOperand PermMask = Op.getOperand(2);
3686 MVT::ValueType VT = Op.getValueType();
3687 unsigned NumElems = PermMask.getNumOperands();
3688 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3689 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3690 bool V1IsSplat = false;
3691 bool V2IsSplat = false;
3693 if (isUndefShuffle(Op.Val))
3694 return DAG.getNode(ISD::UNDEF, VT);
3696 if (isZeroShuffle(Op.Val))
3697 return getZeroVector(VT, DAG);
3699 if (isIdentityMask(PermMask.Val))
3701 else if (isIdentityMask(PermMask.Val, true))
3704 if (isSplatMask(PermMask.Val)) {
3705 if (NumElems <= 4) return Op;
3706 // Promote it to a v4i32 splat.
3707 return PromoteSplat(Op, DAG);
3710 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3712 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3713 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3715 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3716 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3717 // FIXME: Figure out a cleaner way to do this.
3718 // Try to make use of movq to zero out the top part.
3719 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3720 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3722 SDOperand NewV1 = NewOp.getOperand(0);
3723 SDOperand NewV2 = NewOp.getOperand(1);
3724 SDOperand NewMask = NewOp.getOperand(2);
3725 if (isCommutedMOVL(NewMask.Val, true, false)) {
3726 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3727 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3728 NewV1, NewV2, getMOVLMask(2, DAG));
3729 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3732 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3733 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3734 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3735 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3739 if (X86::isMOVLMask(PermMask.Val))
3740 return (V1IsUndef) ? V2 : Op;
3742 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3743 X86::isMOVSLDUPMask(PermMask.Val) ||
3744 X86::isMOVHLPSMask(PermMask.Val) ||
3745 X86::isMOVHPMask(PermMask.Val) ||
3746 X86::isMOVLPMask(PermMask.Val))
3749 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3750 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3751 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3753 bool Commuted = false;
3754 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3755 // 1,1,1,1 -> v8i16 though.
3756 V1IsSplat = isSplatVector(V1.Val);
3757 V2IsSplat = isSplatVector(V2.Val);
3759 // Canonicalize the splat or undef, if present, to be on the RHS.
3760 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3761 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3762 std::swap(V1IsSplat, V2IsSplat);
3763 std::swap(V1IsUndef, V2IsUndef);
3767 // FIXME: Figure out a cleaner way to do this.
3768 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3769 if (V2IsUndef) return V1;
3770 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3772 // V2 is a splat, so the mask may be malformed. That is, it may point
3773 // to any V2 element. The instruction selectior won't like this. Get
3774 // a corrected mask and commute to form a proper MOVS{S|D}.
3775 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3776 if (NewMask.Val != PermMask.Val)
3777 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3782 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3783 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3784 X86::isUNPCKLMask(PermMask.Val) ||
3785 X86::isUNPCKHMask(PermMask.Val))
3789 // Normalize mask so all entries that point to V2 points to its first
3790 // element then try to match unpck{h|l} again. If match, return a
3791 // new vector_shuffle with the corrected mask.
3792 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3793 if (NewMask.Val != PermMask.Val) {
3794 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3795 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3796 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3797 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3798 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3799 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3804 // Normalize the node to match x86 shuffle ops if needed
3805 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3806 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3809 // Commute is back and try unpck* again.
3810 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3811 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3812 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3813 X86::isUNPCKLMask(PermMask.Val) ||
3814 X86::isUNPCKHMask(PermMask.Val))
3818 // If VT is integer, try PSHUF* first, then SHUFP*.
3819 if (MVT::isInteger(VT)) {
3820 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3821 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3822 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3823 X86::isPSHUFDMask(PermMask.Val)) ||
3824 X86::isPSHUFHWMask(PermMask.Val) ||
3825 X86::isPSHUFLWMask(PermMask.Val)) {
3826 if (V2.getOpcode() != ISD::UNDEF)
3827 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3828 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3832 if (X86::isSHUFPMask(PermMask.Val) &&
3833 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3836 // Floating point cases in the other order.
3837 if (X86::isSHUFPMask(PermMask.Val))
3839 if (X86::isPSHUFDMask(PermMask.Val) ||
3840 X86::isPSHUFHWMask(PermMask.Val) ||
3841 X86::isPSHUFLWMask(PermMask.Val)) {
3842 if (V2.getOpcode() != ISD::UNDEF)
3843 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3844 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3849 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3850 if (VT == MVT::v8i16) {
3851 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3856 // Handle all 4 wide cases with a number of shuffles.
3857 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3858 // Don't do this for MMX.
3859 MVT::ValueType MaskVT = PermMask.getValueType();
3860 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3861 SmallVector<std::pair<int, int>, 8> Locs;
3862 Locs.reserve(NumElems);
3863 SmallVector<SDOperand, 8> Mask1(NumElems,
3864 DAG.getNode(ISD::UNDEF, MaskEVT));
3865 SmallVector<SDOperand, 8> Mask2(NumElems,
3866 DAG.getNode(ISD::UNDEF, MaskEVT));
3869 // If no more than two elements come from either vector. This can be
3870 // implemented with two shuffles. First shuffle gather the elements.
3871 // The second shuffle, which takes the first shuffle as both of its
3872 // vector operands, put the elements into the right order.
3873 for (unsigned i = 0; i != NumElems; ++i) {
3874 SDOperand Elt = PermMask.getOperand(i);
3875 if (Elt.getOpcode() == ISD::UNDEF) {
3876 Locs[i] = std::make_pair(-1, -1);
3878 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3879 if (Val < NumElems) {
3880 Locs[i] = std::make_pair(0, NumLo);
3884 Locs[i] = std::make_pair(1, NumHi);
3885 if (2+NumHi < NumElems)
3886 Mask1[2+NumHi] = Elt;
3891 if (NumLo <= 2 && NumHi <= 2) {
3892 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3893 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3894 &Mask1[0], Mask1.size()));
3895 for (unsigned i = 0; i != NumElems; ++i) {
3896 if (Locs[i].first == -1)
3899 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3900 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3901 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3905 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3906 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3907 &Mask2[0], Mask2.size()));
3910 // Break it into (shuffle shuffle_hi, shuffle_lo).
3912 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3913 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3914 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3915 unsigned MaskIdx = 0;
3917 unsigned HiIdx = NumElems/2;
3918 for (unsigned i = 0; i != NumElems; ++i) {
3919 if (i == NumElems/2) {
3925 SDOperand Elt = PermMask.getOperand(i);
3926 if (Elt.getOpcode() == ISD::UNDEF) {
3927 Locs[i] = std::make_pair(-1, -1);
3928 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3929 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3930 (*MaskPtr)[LoIdx] = Elt;
3933 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3934 (*MaskPtr)[HiIdx] = Elt;
3939 SDOperand LoShuffle =
3940 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3941 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3942 &LoMask[0], LoMask.size()));
3943 SDOperand HiShuffle =
3944 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3945 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3946 &HiMask[0], HiMask.size()));
3947 SmallVector<SDOperand, 8> MaskOps;
3948 for (unsigned i = 0; i != NumElems; ++i) {
3949 if (Locs[i].first == -1) {
3950 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3952 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3953 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3956 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3957 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3958 &MaskOps[0], MaskOps.size()));
3965 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3966 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3969 MVT::ValueType VT = Op.getValueType();
3970 // TODO: handle v16i8.
3971 if (MVT::getSizeInBits(VT) == 16) {
3972 SDOperand Vec = Op.getOperand(0);
3973 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3975 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3976 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3977 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3979 // Transform it so it match pextrw which produces a 32-bit result.
3980 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3981 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3982 Op.getOperand(0), Op.getOperand(1));
3983 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3984 DAG.getValueType(VT));
3985 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3986 } else if (MVT::getSizeInBits(VT) == 32) {
3987 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3990 // SHUFPS the element to the lowest double word, then movss.
3991 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3992 SmallVector<SDOperand, 8> IdxVec;
3994 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3996 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3998 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
4000 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
4001 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4002 &IdxVec[0], IdxVec.size());
4003 SDOperand Vec = Op.getOperand(0);
4004 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4005 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4006 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4007 DAG.getConstant(0, getPointerTy()));
4008 } else if (MVT::getSizeInBits(VT) == 64) {
4009 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4013 // UNPCKHPD the element to the lowest double word, then movsd.
4014 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4015 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4016 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
4017 SmallVector<SDOperand, 8> IdxVec;
4018 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
4020 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
4021 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4022 &IdxVec[0], IdxVec.size());
4023 SDOperand Vec = Op.getOperand(0);
4024 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4025 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4026 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4027 DAG.getConstant(0, getPointerTy()));
4034 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
4035 MVT::ValueType VT = Op.getValueType();
4036 MVT::ValueType EVT = MVT::getVectorElementType(VT);
4040 SDOperand N0 = Op.getOperand(0);
4041 SDOperand N1 = Op.getOperand(1);
4042 SDOperand N2 = Op.getOperand(2);
4044 if (MVT::getSizeInBits(EVT) == 16) {
4045 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4046 // as its second argument.
4047 if (N1.getValueType() != MVT::i32)
4048 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4049 if (N2.getValueType() != MVT::i32)
4050 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
4051 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4054 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
4055 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
4056 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
4057 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
4058 SmallVector<SDOperand, 4> MaskVec;
4059 for (unsigned i = 0; i < 4; ++i)
4060 MaskVec.push_back(DAG.getConstant((i == Idx) ? i+4 : i, MaskEVT));
4061 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
4062 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4063 &MaskVec[0], MaskVec.size()));
4067 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
4068 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4069 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
4072 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4073 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4074 // one of the above mentioned nodes. It has to be wrapped because otherwise
4075 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4076 // be used to form addressing mode. These wrapped nodes will be selected
4079 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
4080 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4081 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
4083 CP->getAlignment());
4084 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4085 // With PIC, the address is actually $g + Offset.
4086 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4087 !Subtarget->isPICStyleRIPRel()) {
4088 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4089 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4097 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4098 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4099 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4100 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4101 // With PIC, the address is actually $g + Offset.
4102 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4103 !Subtarget->isPICStyleRIPRel()) {
4104 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4105 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4109 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4110 // load the value at address GV, not the value of GV itself. This means that
4111 // the GlobalAddress must be in the base or index register of the address, not
4112 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4113 // The same applies for external symbols during PIC codegen
4114 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4115 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
4120 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
4122 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4123 const MVT::ValueType PtrVT) {
4125 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4126 DAG.getNode(X86ISD::GlobalBaseReg,
4128 InFlag = Chain.getValue(1);
4130 // emit leal symbol@TLSGD(,%ebx,1), %eax
4131 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4132 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4133 GA->getValueType(0),
4135 SDOperand Ops[] = { Chain, TGA, InFlag };
4136 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4137 InFlag = Result.getValue(2);
4138 Chain = Result.getValue(1);
4140 // call ___tls_get_addr. This function receives its argument in
4141 // the register EAX.
4142 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4143 InFlag = Chain.getValue(1);
4145 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4146 SDOperand Ops1[] = { Chain,
4147 DAG.getTargetExternalSymbol("___tls_get_addr",
4149 DAG.getRegister(X86::EAX, PtrVT),
4150 DAG.getRegister(X86::EBX, PtrVT),
4152 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4153 InFlag = Chain.getValue(1);
4155 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4158 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4159 // "local exec" model.
4161 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4162 const MVT::ValueType PtrVT) {
4163 // Get the Thread Pointer
4164 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4165 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4167 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4168 GA->getValueType(0),
4170 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4172 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4173 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
4175 // The address of the thread local variable is the add of the thread
4176 // pointer with the offset of the variable.
4177 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4181 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4182 // TODO: implement the "local dynamic" model
4183 // TODO: implement the "initial exec"model for pic executables
4184 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4185 "TLS not implemented for non-ELF and 64-bit targets");
4186 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4187 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4188 // otherwise use the "Local Exec"TLS Model
4189 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4190 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4192 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4196 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4197 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4198 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4199 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4200 // With PIC, the address is actually $g + Offset.
4201 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4202 !Subtarget->isPICStyleRIPRel()) {
4203 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4204 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4211 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4212 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4213 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4214 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4215 // With PIC, the address is actually $g + Offset.
4216 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4217 !Subtarget->isPICStyleRIPRel()) {
4218 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4219 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4226 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4227 /// take a 2 x i32 value to shift plus a shift amount.
4228 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4229 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
4230 "Not an i64 shift!");
4231 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4232 SDOperand ShOpLo = Op.getOperand(0);
4233 SDOperand ShOpHi = Op.getOperand(1);
4234 SDOperand ShAmt = Op.getOperand(2);
4235 SDOperand Tmp1 = isSRA ?
4236 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
4237 DAG.getConstant(0, MVT::i32);
4239 SDOperand Tmp2, Tmp3;
4240 if (Op.getOpcode() == ISD::SHL_PARTS) {
4241 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
4242 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
4244 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
4245 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
4248 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4249 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4250 DAG.getConstant(32, MVT::i8));
4251 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
4252 AndNode, DAG.getConstant(0, MVT::i8));
4255 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4256 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
4257 SmallVector<SDOperand, 4> Ops;
4258 if (Op.getOpcode() == ISD::SHL_PARTS) {
4259 Ops.push_back(Tmp2);
4260 Ops.push_back(Tmp3);
4262 Ops.push_back(Cond);
4263 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4266 Ops.push_back(Tmp3);
4267 Ops.push_back(Tmp1);
4269 Ops.push_back(Cond);
4270 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4272 Ops.push_back(Tmp2);
4273 Ops.push_back(Tmp3);
4275 Ops.push_back(Cond);
4276 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4279 Ops.push_back(Tmp3);
4280 Ops.push_back(Tmp1);
4282 Ops.push_back(Cond);
4283 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4286 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
4290 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4293 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4294 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
4295 Op.getOperand(0).getValueType() >= MVT::i16 &&
4296 "Unknown SINT_TO_FP to lower!");
4299 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4300 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4301 MachineFunction &MF = DAG.getMachineFunction();
4302 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4303 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4304 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4305 StackSlot, NULL, 0);
4307 // These are really Legal; caller falls through into that case.
4308 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f32 && X86ScalarSSEf32)
4310 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f64 && X86ScalarSSEf64)
4312 if (SrcVT==MVT::i64 && Op.getValueType() != MVT::f80 &&
4313 Subtarget->is64Bit())
4318 bool useSSE = (X86ScalarSSEf32 && Op.getValueType() == MVT::f32) ||
4319 (X86ScalarSSEf64 && Op.getValueType() == MVT::f64);
4321 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4323 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4324 SmallVector<SDOperand, 8> Ops;
4325 Ops.push_back(Chain);
4326 Ops.push_back(StackSlot);
4327 Ops.push_back(DAG.getValueType(SrcVT));
4328 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
4329 Tys, &Ops[0], Ops.size());
4332 Chain = Result.getValue(1);
4333 SDOperand InFlag = Result.getValue(2);
4335 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4336 // shouldn't be necessary except that RFP cannot be live across
4337 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4338 MachineFunction &MF = DAG.getMachineFunction();
4339 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4340 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4341 Tys = DAG.getVTList(MVT::Other);
4342 SmallVector<SDOperand, 8> Ops;
4343 Ops.push_back(Chain);
4344 Ops.push_back(Result);
4345 Ops.push_back(StackSlot);
4346 Ops.push_back(DAG.getValueType(Op.getValueType()));
4347 Ops.push_back(InFlag);
4348 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4349 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
4355 std::pair<SDOperand,SDOperand> X86TargetLowering::
4356 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4357 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4358 "Unknown FP_TO_SINT to lower!");
4360 // These are really Legal.
4361 if (Op.getValueType() == MVT::i32 &&
4362 X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32)
4363 return std::make_pair(SDOperand(), SDOperand());
4364 if (Op.getValueType() == MVT::i32 &&
4365 X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)
4366 return std::make_pair(SDOperand(), SDOperand());
4367 if (Subtarget->is64Bit() &&
4368 Op.getValueType() == MVT::i64 &&
4369 Op.getOperand(0).getValueType() != MVT::f80)
4370 return std::make_pair(SDOperand(), SDOperand());
4372 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4374 MachineFunction &MF = DAG.getMachineFunction();
4375 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4376 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4377 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4379 switch (Op.getValueType()) {
4380 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4381 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4382 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4383 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4386 SDOperand Chain = DAG.getEntryNode();
4387 SDOperand Value = Op.getOperand(0);
4388 if ((X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32) ||
4389 (X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)) {
4390 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4391 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
4392 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4394 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4396 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4397 Chain = Value.getValue(1);
4398 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4399 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4402 // Build the FP_TO_INT*_IN_MEM
4403 SDOperand Ops[] = { Chain, Value, StackSlot };
4404 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4406 return std::make_pair(FIST, StackSlot);
4409 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4410 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4411 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4412 if (FIST.Val == 0) return SDOperand();
4415 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4418 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4419 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4420 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4421 if (FIST.Val == 0) return 0;
4423 // Return an i64 load from the stack slot.
4424 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4426 // Use a MERGE_VALUES node to drop the chain result value.
4427 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4430 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4431 MVT::ValueType VT = Op.getValueType();
4432 MVT::ValueType EltVT = VT;
4433 if (MVT::isVector(VT))
4434 EltVT = MVT::getVectorElementType(VT);
4435 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4436 std::vector<Constant*> CV;
4437 if (EltVT == MVT::f64) {
4438 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4442 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4448 Constant *C = ConstantVector::get(CV);
4449 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4450 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4452 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4455 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4456 MVT::ValueType VT = Op.getValueType();
4457 MVT::ValueType EltVT = VT;
4458 unsigned EltNum = 1;
4459 if (MVT::isVector(VT)) {
4460 EltVT = MVT::getVectorElementType(VT);
4461 EltNum = MVT::getVectorNumElements(VT);
4463 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4464 std::vector<Constant*> CV;
4465 if (EltVT == MVT::f64) {
4466 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4470 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4476 Constant *C = ConstantVector::get(CV);
4477 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4478 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4480 if (MVT::isVector(VT)) {
4481 return DAG.getNode(ISD::BIT_CONVERT, VT,
4482 DAG.getNode(ISD::XOR, MVT::v2i64,
4483 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4484 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4486 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4490 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4491 SDOperand Op0 = Op.getOperand(0);
4492 SDOperand Op1 = Op.getOperand(1);
4493 MVT::ValueType VT = Op.getValueType();
4494 MVT::ValueType SrcVT = Op1.getValueType();
4495 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4497 // If second operand is smaller, extend it first.
4498 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4499 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4501 SrcTy = MVT::getTypeForValueType(SrcVT);
4503 // And if it is bigger, shrink it first.
4504 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4505 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1);
4507 SrcTy = MVT::getTypeForValueType(SrcVT);
4510 // At this point the operands and the result should have the same
4511 // type, and that won't be f80 since that is not custom lowered.
4513 // First get the sign bit of second operand.
4514 std::vector<Constant*> CV;
4515 if (SrcVT == MVT::f64) {
4516 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4517 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4519 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4520 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4521 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4522 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4524 Constant *C = ConstantVector::get(CV);
4525 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4526 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx, NULL, 0,
4528 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4530 // Shift sign bit right or left if the two operands have different types.
4531 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4532 // Op0 is MVT::f32, Op1 is MVT::f64.
4533 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4534 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4535 DAG.getConstant(32, MVT::i32));
4536 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4537 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4538 DAG.getConstant(0, getPointerTy()));
4541 // Clear first operand sign bit.
4543 if (VT == MVT::f64) {
4544 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4545 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4547 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4548 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4549 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4550 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4552 C = ConstantVector::get(CV);
4553 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4554 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4556 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4558 // Or the value with the sign bit.
4559 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4562 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4563 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4565 SDOperand Op0 = Op.getOperand(0);
4566 SDOperand Op1 = Op.getOperand(1);
4567 SDOperand CC = Op.getOperand(2);
4568 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4569 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4572 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4574 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4575 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4576 DAG.getConstant(X86CC, MVT::i8), Cond);
4579 assert(isFP && "Illegal integer SetCC!");
4581 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4582 switch (SetCCOpcode) {
4583 default: assert(false && "Illegal floating point SetCC!");
4584 case ISD::SETOEQ: { // !PF & ZF
4585 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4586 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4587 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4588 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4589 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4591 case ISD::SETUNE: { // PF | !ZF
4592 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4593 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4594 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4595 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4596 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4602 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4603 bool addTest = true;
4604 SDOperand Cond = Op.getOperand(0);
4607 if (Cond.getOpcode() == ISD::SETCC)
4608 Cond = LowerSETCC(Cond, DAG);
4610 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4611 // setting operand in place of the X86ISD::SETCC.
4612 if (Cond.getOpcode() == X86ISD::SETCC) {
4613 CC = Cond.getOperand(0);
4615 SDOperand Cmp = Cond.getOperand(1);
4616 unsigned Opc = Cmp.getOpcode();
4617 MVT::ValueType VT = Op.getValueType();
4618 bool IllegalFPCMov = false;
4619 if (VT == MVT::f32 && !X86ScalarSSEf32)
4620 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4621 else if (VT == MVT::f64 && !X86ScalarSSEf64)
4622 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4623 else if (VT == MVT::f80)
4624 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4625 if ((Opc == X86ISD::CMP ||
4626 Opc == X86ISD::COMI ||
4627 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4634 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4635 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4638 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4640 SmallVector<SDOperand, 4> Ops;
4641 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4642 // condition is true.
4643 Ops.push_back(Op.getOperand(2));
4644 Ops.push_back(Op.getOperand(1));
4646 Ops.push_back(Cond);
4647 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4650 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4651 bool addTest = true;
4652 SDOperand Chain = Op.getOperand(0);
4653 SDOperand Cond = Op.getOperand(1);
4654 SDOperand Dest = Op.getOperand(2);
4657 if (Cond.getOpcode() == ISD::SETCC)
4658 Cond = LowerSETCC(Cond, DAG);
4660 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4661 // setting operand in place of the X86ISD::SETCC.
4662 if (Cond.getOpcode() == X86ISD::SETCC) {
4663 CC = Cond.getOperand(0);
4665 SDOperand Cmp = Cond.getOperand(1);
4666 unsigned Opc = Cmp.getOpcode();
4667 if (Opc == X86ISD::CMP ||
4668 Opc == X86ISD::COMI ||
4669 Opc == X86ISD::UCOMI) {
4676 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4677 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4679 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4680 Chain, Op.getOperand(2), CC, Cond);
4683 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
4684 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4685 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
4687 if (Subtarget->is64Bit())
4688 if(CallingConv==CallingConv::Fast && isTailCall && PerformTailCallOpt)
4689 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4691 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
4693 switch (CallingConv) {
4695 assert(0 && "Unsupported calling convention");
4696 case CallingConv::Fast:
4697 if (isTailCall && PerformTailCallOpt)
4698 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4700 return LowerCCCCallTo(Op,DAG, CallingConv);
4701 case CallingConv::C:
4702 case CallingConv::X86_StdCall:
4703 return LowerCCCCallTo(Op, DAG, CallingConv);
4704 case CallingConv::X86_FastCall:
4705 return LowerFastCCCallTo(Op, DAG, CallingConv);
4710 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4711 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4712 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4713 // that the guard pages used by the OS virtual memory manager are allocated in
4714 // correct sequence.
4716 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4717 SelectionDAG &DAG) {
4718 assert(Subtarget->isTargetCygMing() &&
4719 "This should be used only on Cygwin/Mingw targets");
4722 SDOperand Chain = Op.getOperand(0);
4723 SDOperand Size = Op.getOperand(1);
4724 // FIXME: Ensure alignment here
4728 MVT::ValueType IntPtr = getPointerTy();
4729 MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
4731 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4732 Flag = Chain.getValue(1);
4734 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4735 SDOperand Ops[] = { Chain,
4736 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4737 DAG.getRegister(X86::EAX, IntPtr),
4739 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4740 Flag = Chain.getValue(1);
4742 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4744 std::vector<MVT::ValueType> Tys;
4745 Tys.push_back(SPTy);
4746 Tys.push_back(MVT::Other);
4747 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4748 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4752 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
4753 MachineFunction &MF = DAG.getMachineFunction();
4754 const Function* Fn = MF.getFunction();
4755 if (Fn->hasExternalLinkage() &&
4756 Subtarget->isTargetCygMing() &&
4757 Fn->getName() == "main")
4758 MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
4760 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4761 if (Subtarget->is64Bit())
4762 return LowerX86_64CCCArguments(Op, DAG);
4766 assert(0 && "Unsupported calling convention");
4767 case CallingConv::Fast:
4768 return LowerCCCArguments(Op, DAG, true);
4769 case CallingConv::C:
4770 return LowerCCCArguments(Op, DAG);
4771 case CallingConv::X86_StdCall:
4772 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
4773 return LowerCCCArguments(Op, DAG, true);
4774 case CallingConv::X86_FastCall:
4775 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
4776 return LowerFastCCArguments(Op, DAG);
4780 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4781 SDOperand InFlag(0, 0);
4782 SDOperand Chain = Op.getOperand(0);
4784 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4785 if (Align == 0) Align = 1;
4787 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4788 // If not DWORD aligned or size is more than the threshold, call memset.
4789 // The libc version is likely to be faster for these cases. It can use the
4790 // address value and run time information about the CPU.
4791 if ((Align & 3) != 0 ||
4792 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4793 MVT::ValueType IntPtr = getPointerTy();
4794 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4795 TargetLowering::ArgListTy Args;
4796 TargetLowering::ArgListEntry Entry;
4797 Entry.Node = Op.getOperand(1);
4798 Entry.Ty = IntPtrTy;
4799 Args.push_back(Entry);
4800 // Extend the unsigned i8 argument to be an int value for the call.
4801 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4802 Entry.Ty = IntPtrTy;
4803 Args.push_back(Entry);
4804 Entry.Node = Op.getOperand(3);
4805 Args.push_back(Entry);
4806 std::pair<SDOperand,SDOperand> CallResult =
4807 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4808 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4809 return CallResult.second;
4814 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4815 unsigned BytesLeft = 0;
4816 bool TwoRepStos = false;
4819 uint64_t Val = ValC->getValue() & 255;
4821 // If the value is a constant, then we can potentially use larger sets.
4822 switch (Align & 3) {
4823 case 2: // WORD aligned
4826 Val = (Val << 8) | Val;
4828 case 0: // DWORD aligned
4831 Val = (Val << 8) | Val;
4832 Val = (Val << 16) | Val;
4833 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4836 Val = (Val << 32) | Val;
4839 default: // Byte aligned
4842 Count = Op.getOperand(3);
4846 if (AVT > MVT::i8) {
4848 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4849 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
4850 BytesLeft = I->getValue() % UBytes;
4852 assert(AVT >= MVT::i32 &&
4853 "Do not use rep;stos if not at least DWORD aligned");
4854 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4855 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4860 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4862 InFlag = Chain.getValue(1);
4865 Count = Op.getOperand(3);
4866 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4867 InFlag = Chain.getValue(1);
4870 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4872 InFlag = Chain.getValue(1);
4873 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4874 Op.getOperand(1), InFlag);
4875 InFlag = Chain.getValue(1);
4877 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4878 SmallVector<SDOperand, 8> Ops;
4879 Ops.push_back(Chain);
4880 Ops.push_back(DAG.getValueType(AVT));
4881 Ops.push_back(InFlag);
4882 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4885 InFlag = Chain.getValue(1);
4886 Count = Op.getOperand(3);
4887 MVT::ValueType CVT = Count.getValueType();
4888 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4889 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4890 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4892 InFlag = Chain.getValue(1);
4893 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4895 Ops.push_back(Chain);
4896 Ops.push_back(DAG.getValueType(MVT::i8));
4897 Ops.push_back(InFlag);
4898 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4899 } else if (BytesLeft) {
4900 // Issue stores for the last 1 - 7 bytes.
4902 unsigned Val = ValC->getValue() & 255;
4903 unsigned Offset = I->getValue() - BytesLeft;
4904 SDOperand DstAddr = Op.getOperand(1);
4905 MVT::ValueType AddrVT = DstAddr.getValueType();
4906 if (BytesLeft >= 4) {
4907 Val = (Val << 8) | Val;
4908 Val = (Val << 16) | Val;
4909 Value = DAG.getConstant(Val, MVT::i32);
4910 Chain = DAG.getStore(Chain, Value,
4911 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4912 DAG.getConstant(Offset, AddrVT)),
4917 if (BytesLeft >= 2) {
4918 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4919 Chain = DAG.getStore(Chain, Value,
4920 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4921 DAG.getConstant(Offset, AddrVT)),
4926 if (BytesLeft == 1) {
4927 Value = DAG.getConstant(Val, MVT::i8);
4928 Chain = DAG.getStore(Chain, Value,
4929 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4930 DAG.getConstant(Offset, AddrVT)),
4938 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4943 SelectionDAG &DAG) {
4945 unsigned BytesLeft = 0;
4946 switch (Align & 3) {
4947 case 2: // WORD aligned
4950 case 0: // DWORD aligned
4952 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4955 default: // Byte aligned
4960 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4961 SDOperand Count = DAG.getConstant(Size / UBytes, getPointerTy());
4962 BytesLeft = Size % UBytes;
4964 SDOperand InFlag(0, 0);
4965 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4967 InFlag = Chain.getValue(1);
4968 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4970 InFlag = Chain.getValue(1);
4971 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4973 InFlag = Chain.getValue(1);
4975 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4976 SmallVector<SDOperand, 8> Ops;
4977 Ops.push_back(Chain);
4978 Ops.push_back(DAG.getValueType(AVT));
4979 Ops.push_back(InFlag);
4980 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4983 // Issue loads and stores for the last 1 - 7 bytes.
4984 unsigned Offset = Size - BytesLeft;
4985 SDOperand DstAddr = Dest;
4986 MVT::ValueType DstVT = DstAddr.getValueType();
4987 SDOperand SrcAddr = Source;
4988 MVT::ValueType SrcVT = SrcAddr.getValueType();
4990 if (BytesLeft >= 4) {
4991 Value = DAG.getLoad(MVT::i32, Chain,
4992 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4993 DAG.getConstant(Offset, SrcVT)),
4995 Chain = Value.getValue(1);
4996 Chain = DAG.getStore(Chain, Value,
4997 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4998 DAG.getConstant(Offset, DstVT)),
5003 if (BytesLeft >= 2) {
5004 Value = DAG.getLoad(MVT::i16, Chain,
5005 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
5006 DAG.getConstant(Offset, SrcVT)),
5008 Chain = Value.getValue(1);
5009 Chain = DAG.getStore(Chain, Value,
5010 DAG.getNode(ISD::ADD, DstVT, DstAddr,
5011 DAG.getConstant(Offset, DstVT)),
5017 if (BytesLeft == 1) {
5018 Value = DAG.getLoad(MVT::i8, Chain,
5019 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
5020 DAG.getConstant(Offset, SrcVT)),
5022 Chain = Value.getValue(1);
5023 Chain = DAG.getStore(Chain, Value,
5024 DAG.getNode(ISD::ADD, DstVT, DstAddr,
5025 DAG.getConstant(Offset, DstVT)),
5033 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
5034 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
5035 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5036 SDOperand TheChain = N->getOperand(0);
5037 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
5038 if (Subtarget->is64Bit()) {
5039 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
5040 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
5041 MVT::i64, rax.getValue(2));
5042 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
5043 DAG.getConstant(32, MVT::i8));
5045 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
5048 Tys = DAG.getVTList(MVT::i64, MVT::Other);
5049 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
5052 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
5053 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
5054 MVT::i32, eax.getValue(2));
5055 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
5056 SDOperand Ops[] = { eax, edx };
5057 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
5059 // Use a MERGE_VALUES to return the value and chain.
5060 Ops[1] = edx.getValue(1);
5061 Tys = DAG.getVTList(MVT::i64, MVT::Other);
5062 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
5065 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
5066 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
5068 if (!Subtarget->is64Bit()) {
5069 // vastart just stores the address of the VarArgsFrameIndex slot into the
5070 // memory location argument.
5071 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5072 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
5077 // gp_offset (0 - 6 * 8)
5078 // fp_offset (48 - 48 + 8 * 16)
5079 // overflow_arg_area (point to parameters coming in memory).
5081 SmallVector<SDOperand, 8> MemOps;
5082 SDOperand FIN = Op.getOperand(1);
5084 SDOperand Store = DAG.getStore(Op.getOperand(0),
5085 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5086 FIN, SV->getValue(), SV->getOffset());
5087 MemOps.push_back(Store);
5090 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5091 DAG.getConstant(4, getPointerTy()));
5092 Store = DAG.getStore(Op.getOperand(0),
5093 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5094 FIN, SV->getValue(), SV->getOffset());
5095 MemOps.push_back(Store);
5097 // Store ptr to overflow_arg_area
5098 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5099 DAG.getConstant(4, getPointerTy()));
5100 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5101 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
5103 MemOps.push_back(Store);
5105 // Store ptr to reg_save_area.
5106 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5107 DAG.getConstant(8, getPointerTy()));
5108 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5109 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
5111 MemOps.push_back(Store);
5112 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5115 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
5116 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5117 SDOperand Chain = Op.getOperand(0);
5118 SDOperand DstPtr = Op.getOperand(1);
5119 SDOperand SrcPtr = Op.getOperand(2);
5120 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
5121 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
5123 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
5124 SrcSV->getValue(), SrcSV->getOffset());
5125 Chain = SrcPtr.getValue(1);
5126 for (unsigned i = 0; i < 3; ++i) {
5127 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
5128 SrcSV->getValue(), SrcSV->getOffset());
5129 Chain = Val.getValue(1);
5130 Chain = DAG.getStore(Chain, Val, DstPtr,
5131 DstSV->getValue(), DstSV->getOffset());
5134 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
5135 DAG.getConstant(8, getPointerTy()));
5136 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
5137 DAG.getConstant(8, getPointerTy()));
5143 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5144 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5146 default: return SDOperand(); // Don't custom lower most intrinsics.
5147 // Comparison intrinsics.
5148 case Intrinsic::x86_sse_comieq_ss:
5149 case Intrinsic::x86_sse_comilt_ss:
5150 case Intrinsic::x86_sse_comile_ss:
5151 case Intrinsic::x86_sse_comigt_ss:
5152 case Intrinsic::x86_sse_comige_ss:
5153 case Intrinsic::x86_sse_comineq_ss:
5154 case Intrinsic::x86_sse_ucomieq_ss:
5155 case Intrinsic::x86_sse_ucomilt_ss:
5156 case Intrinsic::x86_sse_ucomile_ss:
5157 case Intrinsic::x86_sse_ucomigt_ss:
5158 case Intrinsic::x86_sse_ucomige_ss:
5159 case Intrinsic::x86_sse_ucomineq_ss:
5160 case Intrinsic::x86_sse2_comieq_sd:
5161 case Intrinsic::x86_sse2_comilt_sd:
5162 case Intrinsic::x86_sse2_comile_sd:
5163 case Intrinsic::x86_sse2_comigt_sd:
5164 case Intrinsic::x86_sse2_comige_sd:
5165 case Intrinsic::x86_sse2_comineq_sd:
5166 case Intrinsic::x86_sse2_ucomieq_sd:
5167 case Intrinsic::x86_sse2_ucomilt_sd:
5168 case Intrinsic::x86_sse2_ucomile_sd:
5169 case Intrinsic::x86_sse2_ucomigt_sd:
5170 case Intrinsic::x86_sse2_ucomige_sd:
5171 case Intrinsic::x86_sse2_ucomineq_sd: {
5173 ISD::CondCode CC = ISD::SETCC_INVALID;
5176 case Intrinsic::x86_sse_comieq_ss:
5177 case Intrinsic::x86_sse2_comieq_sd:
5181 case Intrinsic::x86_sse_comilt_ss:
5182 case Intrinsic::x86_sse2_comilt_sd:
5186 case Intrinsic::x86_sse_comile_ss:
5187 case Intrinsic::x86_sse2_comile_sd:
5191 case Intrinsic::x86_sse_comigt_ss:
5192 case Intrinsic::x86_sse2_comigt_sd:
5196 case Intrinsic::x86_sse_comige_ss:
5197 case Intrinsic::x86_sse2_comige_sd:
5201 case Intrinsic::x86_sse_comineq_ss:
5202 case Intrinsic::x86_sse2_comineq_sd:
5206 case Intrinsic::x86_sse_ucomieq_ss:
5207 case Intrinsic::x86_sse2_ucomieq_sd:
5208 Opc = X86ISD::UCOMI;
5211 case Intrinsic::x86_sse_ucomilt_ss:
5212 case Intrinsic::x86_sse2_ucomilt_sd:
5213 Opc = X86ISD::UCOMI;
5216 case Intrinsic::x86_sse_ucomile_ss:
5217 case Intrinsic::x86_sse2_ucomile_sd:
5218 Opc = X86ISD::UCOMI;
5221 case Intrinsic::x86_sse_ucomigt_ss:
5222 case Intrinsic::x86_sse2_ucomigt_sd:
5223 Opc = X86ISD::UCOMI;
5226 case Intrinsic::x86_sse_ucomige_ss:
5227 case Intrinsic::x86_sse2_ucomige_sd:
5228 Opc = X86ISD::UCOMI;
5231 case Intrinsic::x86_sse_ucomineq_ss:
5232 case Intrinsic::x86_sse2_ucomineq_sd:
5233 Opc = X86ISD::UCOMI;
5239 SDOperand LHS = Op.getOperand(1);
5240 SDOperand RHS = Op.getOperand(2);
5241 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5243 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5244 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5245 DAG.getConstant(X86CC, MVT::i8), Cond);
5246 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5251 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5252 // Depths > 0 not supported yet!
5253 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5256 // Just load the return address
5257 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5258 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5261 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5262 // Depths > 0 not supported yet!
5263 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5266 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5267 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5268 DAG.getConstant(4, getPointerTy()));
5271 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5272 SelectionDAG &DAG) {
5273 // Is not yet supported on x86-64
5274 if (Subtarget->is64Bit())
5277 return DAG.getConstant(8, getPointerTy());
5280 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5282 assert(!Subtarget->is64Bit() &&
5283 "Lowering of eh_return builtin is not supported yet on x86-64");
5285 MachineFunction &MF = DAG.getMachineFunction();
5286 SDOperand Chain = Op.getOperand(0);
5287 SDOperand Offset = Op.getOperand(1);
5288 SDOperand Handler = Op.getOperand(2);
5290 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5293 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5294 DAG.getConstant(-4UL, getPointerTy()));
5295 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5296 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5297 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5298 MF.getRegInfo().addLiveOut(X86::ECX);
5300 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5301 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5304 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5305 SelectionDAG &DAG) {
5306 SDOperand Root = Op.getOperand(0);
5307 SDOperand Trmp = Op.getOperand(1); // trampoline
5308 SDOperand FPtr = Op.getOperand(2); // nested function
5309 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5311 SrcValueSDNode *TrmpSV = cast<SrcValueSDNode>(Op.getOperand(4));
5313 if (Subtarget->is64Bit()) {
5314 return SDOperand(); // not yet supported
5316 Function *Func = (Function *)
5317 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5318 unsigned CC = Func->getCallingConv();
5323 assert(0 && "Unsupported calling convention");
5324 case CallingConv::C:
5325 case CallingConv::X86_StdCall: {
5326 // Pass 'nest' parameter in ECX.
5327 // Must be kept in sync with X86CallingConv.td
5330 // Check that ECX wasn't needed by an 'inreg' parameter.
5331 const FunctionType *FTy = Func->getFunctionType();
5332 const ParamAttrsList *Attrs = Func->getParamAttrs();
5334 if (Attrs && !Func->isVarArg()) {
5335 unsigned InRegCount = 0;
5338 for (FunctionType::param_iterator I = FTy->param_begin(),
5339 E = FTy->param_end(); I != E; ++I, ++Idx)
5340 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5341 // FIXME: should only count parameters that are lowered to integers.
5342 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5344 if (InRegCount > 2) {
5345 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5351 case CallingConv::X86_FastCall:
5352 // Pass 'nest' parameter in EAX.
5353 // Must be kept in sync with X86CallingConv.td
5358 const X86InstrInfo *TII =
5359 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5361 SDOperand OutChains[4];
5362 SDOperand Addr, Disp;
5364 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5365 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5367 unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5368 unsigned char N86Reg = ((X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5369 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5370 Trmp, TrmpSV->getValue(), TrmpSV->getOffset());
5372 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5373 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpSV->getValue(),
5374 TrmpSV->getOffset() + 1, false, 1);
5376 unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5377 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5378 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5379 TrmpSV->getValue() + 5, TrmpSV->getOffset());
5381 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5382 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpSV->getValue(),
5383 TrmpSV->getOffset() + 6, false, 1);
5386 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5387 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5391 SDOperand X86TargetLowering::LowerFLT_ROUNDS(SDOperand Op, SelectionDAG &DAG) {
5393 The rounding mode is in bits 11:10 of FPSR, and has the following
5400 FLT_ROUNDS, on the other hand, expects the following:
5407 To perform the conversion, we do:
5408 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5411 MachineFunction &MF = DAG.getMachineFunction();
5412 const TargetMachine &TM = MF.getTarget();
5413 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5414 unsigned StackAlignment = TFI.getStackAlignment();
5415 MVT::ValueType VT = Op.getValueType();
5417 // Save FP Control Word to stack slot
5418 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5419 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5421 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5422 DAG.getEntryNode(), StackSlot);
5424 // Load FP Control Word from stack slot
5425 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5427 // Transform as necessary
5429 DAG.getNode(ISD::SRL, MVT::i16,
5430 DAG.getNode(ISD::AND, MVT::i16,
5431 CWD, DAG.getConstant(0x800, MVT::i16)),
5432 DAG.getConstant(11, MVT::i8));
5434 DAG.getNode(ISD::SRL, MVT::i16,
5435 DAG.getNode(ISD::AND, MVT::i16,
5436 CWD, DAG.getConstant(0x400, MVT::i16)),
5437 DAG.getConstant(9, MVT::i8));
5440 DAG.getNode(ISD::AND, MVT::i16,
5441 DAG.getNode(ISD::ADD, MVT::i16,
5442 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5443 DAG.getConstant(1, MVT::i16)),
5444 DAG.getConstant(3, MVT::i16));
5447 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5448 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5451 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5452 MVT::ValueType VT = Op.getValueType();
5453 MVT::ValueType OpVT = VT;
5454 unsigned NumBits = MVT::getSizeInBits(VT);
5456 Op = Op.getOperand(0);
5457 if (VT == MVT::i8) {
5458 // Zero extend to i32 since there is not an i8 bsr.
5460 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5463 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5464 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5465 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5467 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5468 SmallVector<SDOperand, 4> Ops;
5470 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5471 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5472 Ops.push_back(Op.getValue(1));
5473 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5475 // Finally xor with NumBits-1.
5476 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5479 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5483 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5484 MVT::ValueType VT = Op.getValueType();
5485 MVT::ValueType OpVT = VT;
5486 unsigned NumBits = MVT::getSizeInBits(VT);
5488 Op = Op.getOperand(0);
5489 if (VT == MVT::i8) {
5491 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5494 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5495 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5496 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5498 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5499 SmallVector<SDOperand, 4> Ops;
5501 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5502 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5503 Ops.push_back(Op.getValue(1));
5504 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5507 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5511 /// LowerOperation - Provide custom lowering hooks for some operations.
5513 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5514 switch (Op.getOpcode()) {
5515 default: assert(0 && "Should not custom lower this!");
5516 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5517 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5518 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5519 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5520 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5521 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5522 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5523 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5524 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5525 case ISD::SHL_PARTS:
5526 case ISD::SRA_PARTS:
5527 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5528 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5529 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5530 case ISD::FABS: return LowerFABS(Op, DAG);
5531 case ISD::FNEG: return LowerFNEG(Op, DAG);
5532 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5533 case ISD::SETCC: return LowerSETCC(Op, DAG);
5534 case ISD::SELECT: return LowerSELECT(Op, DAG);
5535 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5536 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5537 case ISD::CALL: return LowerCALL(Op, DAG);
5538 case ISD::RET: return LowerRET(Op, DAG);
5539 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5540 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5541 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
5542 case ISD::VASTART: return LowerVASTART(Op, DAG);
5543 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5544 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5545 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5546 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5547 case ISD::FRAME_TO_ARGS_OFFSET:
5548 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5549 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5550 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5551 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5552 case ISD::FLT_ROUNDS: return LowerFLT_ROUNDS(Op, DAG);
5553 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5554 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5556 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5557 case ISD::READCYCLECOUNTER:
5558 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5562 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5563 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5564 switch (N->getOpcode()) {
5565 default: assert(0 && "Should not custom lower this!");
5566 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5567 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5571 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5573 default: return NULL;
5574 case X86ISD::BSF: return "X86ISD::BSF";
5575 case X86ISD::BSR: return "X86ISD::BSR";
5576 case X86ISD::SHLD: return "X86ISD::SHLD";
5577 case X86ISD::SHRD: return "X86ISD::SHRD";
5578 case X86ISD::FAND: return "X86ISD::FAND";
5579 case X86ISD::FOR: return "X86ISD::FOR";
5580 case X86ISD::FXOR: return "X86ISD::FXOR";
5581 case X86ISD::FSRL: return "X86ISD::FSRL";
5582 case X86ISD::FILD: return "X86ISD::FILD";
5583 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5584 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5585 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5586 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5587 case X86ISD::FLD: return "X86ISD::FLD";
5588 case X86ISD::FST: return "X86ISD::FST";
5589 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5590 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5591 case X86ISD::CALL: return "X86ISD::CALL";
5592 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5593 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5594 case X86ISD::CMP: return "X86ISD::CMP";
5595 case X86ISD::COMI: return "X86ISD::COMI";
5596 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5597 case X86ISD::SETCC: return "X86ISD::SETCC";
5598 case X86ISD::CMOV: return "X86ISD::CMOV";
5599 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5600 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5601 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5602 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5603 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5604 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5605 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5606 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5607 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5608 case X86ISD::FMAX: return "X86ISD::FMAX";
5609 case X86ISD::FMIN: return "X86ISD::FMIN";
5610 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5611 case X86ISD::FRCP: return "X86ISD::FRCP";
5612 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5613 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5614 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5615 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5616 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5620 // isLegalAddressingMode - Return true if the addressing mode represented
5621 // by AM is legal for this target, for a load/store of the specified type.
5622 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5623 const Type *Ty) const {
5624 // X86 supports extremely general addressing modes.
5626 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5627 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5631 // We can only fold this if we don't need an extra load.
5632 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5635 // X86-64 only supports addr of globals in small code model.
5636 if (Subtarget->is64Bit()) {
5637 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5639 // If lower 4G is not available, then we must use rip-relative addressing.
5640 if (AM.BaseOffs || AM.Scale > 1)
5651 // These scales always work.
5656 // These scales are formed with basereg+scalereg. Only accept if there is
5661 default: // Other stuff never works.
5669 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5670 if (!Ty1->isInteger() || !Ty2->isInteger())
5672 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5673 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5674 if (NumBits1 <= NumBits2)
5676 return Subtarget->is64Bit() || NumBits1 < 64;
5679 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5680 MVT::ValueType VT2) const {
5681 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5683 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5684 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5685 if (NumBits1 <= NumBits2)
5687 return Subtarget->is64Bit() || NumBits1 < 64;
5690 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5691 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5692 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5693 /// are assumed to be legal.
5695 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5696 // Only do shuffles on 128-bit vector types for now.
5697 if (MVT::getSizeInBits(VT) == 64) return false;
5698 return (Mask.Val->getNumOperands() <= 4 ||
5699 isIdentityMask(Mask.Val) ||
5700 isIdentityMask(Mask.Val, true) ||
5701 isSplatMask(Mask.Val) ||
5702 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5703 X86::isUNPCKLMask(Mask.Val) ||
5704 X86::isUNPCKHMask(Mask.Val) ||
5705 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5706 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5709 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5711 SelectionDAG &DAG) const {
5712 unsigned NumElts = BVOps.size();
5713 // Only do shuffles on 128-bit vector types for now.
5714 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5715 if (NumElts == 2) return true;
5717 return (isMOVLMask(&BVOps[0], 4) ||
5718 isCommutedMOVL(&BVOps[0], 4, true) ||
5719 isSHUFPMask(&BVOps[0], 4) ||
5720 isCommutedSHUFP(&BVOps[0], 4));
5725 //===----------------------------------------------------------------------===//
5726 // X86 Scheduler Hooks
5727 //===----------------------------------------------------------------------===//
5730 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
5731 MachineBasicBlock *BB) {
5732 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5733 switch (MI->getOpcode()) {
5734 default: assert(false && "Unexpected instr type to insert");
5735 case X86::CMOV_FR32:
5736 case X86::CMOV_FR64:
5737 case X86::CMOV_V4F32:
5738 case X86::CMOV_V2F64:
5739 case X86::CMOV_V2I64: {
5740 // To "insert" a SELECT_CC instruction, we actually have to insert the
5741 // diamond control-flow pattern. The incoming instruction knows the
5742 // destination vreg to set, the condition code register to branch on, the
5743 // true/false values to select between, and a branch opcode to use.
5744 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5745 ilist<MachineBasicBlock>::iterator It = BB;
5751 // cmpTY ccX, r1, r2
5753 // fallthrough --> copy0MBB
5754 MachineBasicBlock *thisMBB = BB;
5755 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5756 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5758 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5759 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5760 MachineFunction *F = BB->getParent();
5761 F->getBasicBlockList().insert(It, copy0MBB);
5762 F->getBasicBlockList().insert(It, sinkMBB);
5763 // Update machine-CFG edges by first adding all successors of the current
5764 // block to the new block which will contain the Phi node for the select.
5765 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5766 e = BB->succ_end(); i != e; ++i)
5767 sinkMBB->addSuccessor(*i);
5768 // Next, remove all successors of the current block, and add the true
5769 // and fallthrough blocks as its successors.
5770 while(!BB->succ_empty())
5771 BB->removeSuccessor(BB->succ_begin());
5772 BB->addSuccessor(copy0MBB);
5773 BB->addSuccessor(sinkMBB);
5776 // %FalseValue = ...
5777 // # fallthrough to sinkMBB
5780 // Update machine-CFG edges
5781 BB->addSuccessor(sinkMBB);
5784 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5787 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5788 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5789 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5791 delete MI; // The pseudo instruction is gone now.
5795 case X86::FP32_TO_INT16_IN_MEM:
5796 case X86::FP32_TO_INT32_IN_MEM:
5797 case X86::FP32_TO_INT64_IN_MEM:
5798 case X86::FP64_TO_INT16_IN_MEM:
5799 case X86::FP64_TO_INT32_IN_MEM:
5800 case X86::FP64_TO_INT64_IN_MEM:
5801 case X86::FP80_TO_INT16_IN_MEM:
5802 case X86::FP80_TO_INT32_IN_MEM:
5803 case X86::FP80_TO_INT64_IN_MEM: {
5804 // Change the floating point control register to use "round towards zero"
5805 // mode when truncating to an integer value.
5806 MachineFunction *F = BB->getParent();
5807 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5808 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5810 // Load the old value of the high byte of the control word...
5812 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5813 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5815 // Set the high part to be round to zero...
5816 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5819 // Reload the modified control word now...
5820 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5822 // Restore the memory image of control word to original value
5823 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5826 // Get the X86 opcode to use.
5828 switch (MI->getOpcode()) {
5829 default: assert(0 && "illegal opcode!");
5830 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5831 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5832 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5833 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5834 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5835 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5836 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5837 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5838 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5842 MachineOperand &Op = MI->getOperand(0);
5843 if (Op.isRegister()) {
5844 AM.BaseType = X86AddressMode::RegBase;
5845 AM.Base.Reg = Op.getReg();
5847 AM.BaseType = X86AddressMode::FrameIndexBase;
5848 AM.Base.FrameIndex = Op.getIndex();
5850 Op = MI->getOperand(1);
5851 if (Op.isImmediate())
5852 AM.Scale = Op.getImm();
5853 Op = MI->getOperand(2);
5854 if (Op.isImmediate())
5855 AM.IndexReg = Op.getImm();
5856 Op = MI->getOperand(3);
5857 if (Op.isGlobalAddress()) {
5858 AM.GV = Op.getGlobal();
5860 AM.Disp = Op.getImm();
5862 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5863 .addReg(MI->getOperand(4).getReg());
5865 // Reload the original control word now.
5866 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5868 delete MI; // The pseudo instruction is gone now.
5874 //===----------------------------------------------------------------------===//
5875 // X86 Optimization Hooks
5876 //===----------------------------------------------------------------------===//
5878 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5880 uint64_t &KnownZero,
5882 const SelectionDAG &DAG,
5883 unsigned Depth) const {
5884 unsigned Opc = Op.getOpcode();
5885 assert((Opc >= ISD::BUILTIN_OP_END ||
5886 Opc == ISD::INTRINSIC_WO_CHAIN ||
5887 Opc == ISD::INTRINSIC_W_CHAIN ||
5888 Opc == ISD::INTRINSIC_VOID) &&
5889 "Should use MaskedValueIsZero if you don't know whether Op"
5890 " is a target node!");
5892 KnownZero = KnownOne = 0; // Don't know anything.
5896 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5901 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5902 /// element of the result of the vector shuffle.
5903 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5904 MVT::ValueType VT = N->getValueType(0);
5905 SDOperand PermMask = N->getOperand(2);
5906 unsigned NumElems = PermMask.getNumOperands();
5907 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5909 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5911 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5912 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5913 SDOperand Idx = PermMask.getOperand(i);
5914 if (Idx.getOpcode() == ISD::UNDEF)
5915 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5916 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5921 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5922 /// node is a GlobalAddress + an offset.
5923 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5924 unsigned Opc = N->getOpcode();
5925 if (Opc == X86ISD::Wrapper) {
5926 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5927 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5930 } else if (Opc == ISD::ADD) {
5931 SDOperand N1 = N->getOperand(0);
5932 SDOperand N2 = N->getOperand(1);
5933 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5934 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5936 Offset += V->getSignExtended();
5939 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5940 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5942 Offset += V->getSignExtended();
5950 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5952 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5953 MachineFrameInfo *MFI) {
5954 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5957 SDOperand Loc = N->getOperand(1);
5958 SDOperand BaseLoc = Base->getOperand(1);
5959 if (Loc.getOpcode() == ISD::FrameIndex) {
5960 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5962 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5963 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5964 int FS = MFI->getObjectSize(FI);
5965 int BFS = MFI->getObjectSize(BFI);
5966 if (FS != BFS || FS != Size) return false;
5967 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5969 GlobalValue *GV1 = NULL;
5970 GlobalValue *GV2 = NULL;
5971 int64_t Offset1 = 0;
5972 int64_t Offset2 = 0;
5973 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5974 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5975 if (isGA1 && isGA2 && GV1 == GV2)
5976 return Offset1 == (Offset2 + Dist*Size);
5982 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5983 const X86Subtarget *Subtarget) {
5986 if (isGAPlusOffset(Base, GV, Offset))
5987 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5989 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
5990 int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
5992 // Fixed objects do not specify alignment, however the offsets are known.
5993 return ((Subtarget->getStackAlignment() % 16) == 0 &&
5994 (MFI->getObjectOffset(BFI) % 16) == 0);
5996 return MFI->getObjectAlignment(BFI) >= 16;
6002 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6003 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6004 /// if the load addresses are consecutive, non-overlapping, and in the right
6006 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6007 const X86Subtarget *Subtarget) {
6008 MachineFunction &MF = DAG.getMachineFunction();
6009 MachineFrameInfo *MFI = MF.getFrameInfo();
6010 MVT::ValueType VT = N->getValueType(0);
6011 MVT::ValueType EVT = MVT::getVectorElementType(VT);
6012 SDOperand PermMask = N->getOperand(2);
6013 int NumElems = (int)PermMask.getNumOperands();
6014 SDNode *Base = NULL;
6015 for (int i = 0; i < NumElems; ++i) {
6016 SDOperand Idx = PermMask.getOperand(i);
6017 if (Idx.getOpcode() == ISD::UNDEF) {
6018 if (!Base) return SDOperand();
6021 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
6022 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
6026 else if (!isConsecutiveLoad(Arg.Val, Base,
6027 i, MVT::getSizeInBits(EVT)/8,MFI))
6032 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
6033 LoadSDNode *LD = cast<LoadSDNode>(Base);
6035 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6036 LD->getSrcValueOffset(), LD->isVolatile());
6038 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6039 LD->getSrcValueOffset(), LD->isVolatile(),
6040 LD->getAlignment());
6044 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6045 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6046 const X86Subtarget *Subtarget) {
6047 SDOperand Cond = N->getOperand(0);
6049 // If we have SSE[12] support, try to form min/max nodes.
6050 if (Subtarget->hasSSE2() &&
6051 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6052 if (Cond.getOpcode() == ISD::SETCC) {
6053 // Get the LHS/RHS of the select.
6054 SDOperand LHS = N->getOperand(1);
6055 SDOperand RHS = N->getOperand(2);
6056 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6058 unsigned Opcode = 0;
6059 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6062 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6065 if (!UnsafeFPMath) break;
6067 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6069 Opcode = X86ISD::FMIN;
6072 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6075 if (!UnsafeFPMath) break;
6077 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6079 Opcode = X86ISD::FMAX;
6082 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6085 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6088 if (!UnsafeFPMath) break;
6090 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6092 Opcode = X86ISD::FMIN;
6095 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6098 if (!UnsafeFPMath) break;
6100 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6102 Opcode = X86ISD::FMAX;
6108 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6117 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6118 DAGCombinerInfo &DCI) const {
6119 SelectionDAG &DAG = DCI.DAG;
6120 switch (N->getOpcode()) {
6122 case ISD::VECTOR_SHUFFLE:
6123 return PerformShuffleCombine(N, DAG, Subtarget);
6125 return PerformSELECTCombine(N, DAG, Subtarget);
6131 //===----------------------------------------------------------------------===//
6132 // X86 Inline Assembly Support
6133 //===----------------------------------------------------------------------===//
6135 /// getConstraintType - Given a constraint letter, return the type of
6136 /// constraint it is for this target.
6137 X86TargetLowering::ConstraintType
6138 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6139 if (Constraint.size() == 1) {
6140 switch (Constraint[0]) {
6149 return C_RegisterClass;
6154 return TargetLowering::getConstraintType(Constraint);
6157 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6158 /// vector. If it is invalid, don't add anything to Ops.
6159 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6161 std::vector<SDOperand>&Ops,
6162 SelectionDAG &DAG) {
6163 SDOperand Result(0, 0);
6165 switch (Constraint) {
6168 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6169 if (C->getValue() <= 31) {
6170 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6176 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6177 if (C->getValue() <= 255) {
6178 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6184 // Literal immediates are always ok.
6185 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6186 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6190 // If we are in non-pic codegen mode, we allow the address of a global (with
6191 // an optional displacement) to be used with 'i'.
6192 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6195 // Match either (GA) or (GA+C)
6197 Offset = GA->getOffset();
6198 } else if (Op.getOpcode() == ISD::ADD) {
6199 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6200 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6202 Offset = GA->getOffset()+C->getValue();
6204 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6205 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6207 Offset = GA->getOffset()+C->getValue();
6214 // If addressing this global requires a load (e.g. in PIC mode), we can't
6216 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6220 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6226 // Otherwise, not valid for this mode.
6232 Ops.push_back(Result);
6235 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6238 std::vector<unsigned> X86TargetLowering::
6239 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6240 MVT::ValueType VT) const {
6241 if (Constraint.size() == 1) {
6242 // FIXME: not handling fp-stack yet!
6243 switch (Constraint[0]) { // GCC X86 Constraint Letters
6244 default: break; // Unknown constraint letter
6245 case 'A': // EAX/EDX
6246 if (VT == MVT::i32 || VT == MVT::i64)
6247 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6249 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6252 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6253 else if (VT == MVT::i16)
6254 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6255 else if (VT == MVT::i8)
6256 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6257 else if (VT == MVT::i64)
6258 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6263 return std::vector<unsigned>();
6266 std::pair<unsigned, const TargetRegisterClass*>
6267 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6268 MVT::ValueType VT) const {
6269 // First, see if this is a constraint that directly corresponds to an LLVM
6271 if (Constraint.size() == 1) {
6272 // GCC Constraint Letters
6273 switch (Constraint[0]) {
6275 case 'r': // GENERAL_REGS
6276 case 'R': // LEGACY_REGS
6277 case 'l': // INDEX_REGS
6278 if (VT == MVT::i64 && Subtarget->is64Bit())
6279 return std::make_pair(0U, X86::GR64RegisterClass);
6281 return std::make_pair(0U, X86::GR32RegisterClass);
6282 else if (VT == MVT::i16)
6283 return std::make_pair(0U, X86::GR16RegisterClass);
6284 else if (VT == MVT::i8)
6285 return std::make_pair(0U, X86::GR8RegisterClass);
6287 case 'y': // MMX_REGS if MMX allowed.
6288 if (!Subtarget->hasMMX()) break;
6289 return std::make_pair(0U, X86::VR64RegisterClass);
6291 case 'Y': // SSE_REGS if SSE2 allowed
6292 if (!Subtarget->hasSSE2()) break;
6294 case 'x': // SSE_REGS if SSE1 allowed
6295 if (!Subtarget->hasSSE1()) break;
6299 // Scalar SSE types.
6302 return std::make_pair(0U, X86::FR32RegisterClass);
6305 return std::make_pair(0U, X86::FR64RegisterClass);
6313 return std::make_pair(0U, X86::VR128RegisterClass);
6319 // Use the default implementation in TargetLowering to convert the register
6320 // constraint into a member of a register class.
6321 std::pair<unsigned, const TargetRegisterClass*> Res;
6322 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6324 // Not found as a standard register?
6325 if (Res.second == 0) {
6326 // GCC calls "st(0)" just plain "st".
6327 if (StringsEqualNoCase("{st}", Constraint)) {
6328 Res.first = X86::ST0;
6329 Res.second = X86::RFP80RegisterClass;
6335 // Otherwise, check to see if this is a register class of the wrong value
6336 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6337 // turn into {ax},{dx}.
6338 if (Res.second->hasType(VT))
6339 return Res; // Correct type already, nothing to do.
6341 // All of the single-register GCC register classes map their values onto
6342 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6343 // really want an 8-bit or 32-bit register, map to the appropriate register
6344 // class and return the appropriate register.
6345 if (Res.second != X86::GR16RegisterClass)
6348 if (VT == MVT::i8) {
6349 unsigned DestReg = 0;
6350 switch (Res.first) {
6352 case X86::AX: DestReg = X86::AL; break;
6353 case X86::DX: DestReg = X86::DL; break;
6354 case X86::CX: DestReg = X86::CL; break;
6355 case X86::BX: DestReg = X86::BL; break;
6358 Res.first = DestReg;
6359 Res.second = Res.second = X86::GR8RegisterClass;
6361 } else if (VT == MVT::i32) {
6362 unsigned DestReg = 0;
6363 switch (Res.first) {
6365 case X86::AX: DestReg = X86::EAX; break;
6366 case X86::DX: DestReg = X86::EDX; break;
6367 case X86::CX: DestReg = X86::ECX; break;
6368 case X86::BX: DestReg = X86::EBX; break;
6369 case X86::SI: DestReg = X86::ESI; break;
6370 case X86::DI: DestReg = X86::EDI; break;
6371 case X86::BP: DestReg = X86::EBP; break;
6372 case X86::SP: DestReg = X86::ESP; break;
6375 Res.first = DestReg;
6376 Res.second = Res.second = X86::GR32RegisterClass;
6378 } else if (VT == MVT::i64) {
6379 unsigned DestReg = 0;
6380 switch (Res.first) {
6382 case X86::AX: DestReg = X86::RAX; break;
6383 case X86::DX: DestReg = X86::RDX; break;
6384 case X86::CX: DestReg = X86::RCX; break;
6385 case X86::BX: DestReg = X86::RBX; break;
6386 case X86::SI: DestReg = X86::RSI; break;
6387 case X86::DI: DestReg = X86::RDI; break;
6388 case X86::BP: DestReg = X86::RBP; break;
6389 case X86::SP: DestReg = X86::RSP; break;
6392 Res.first = DestReg;
6393 Res.second = Res.second = X86::GR64RegisterClass;