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/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/SmallSet.h"
41 #include "llvm/ADT/StringExtras.h"
42 #include "llvm/ParameterAttributes.h"
45 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
46 : TargetLowering(TM) {
47 Subtarget = &TM.getSubtarget<X86Subtarget>();
48 X86ScalarSSEf64 = Subtarget->hasSSE2();
49 X86ScalarSSEf32 = Subtarget->hasSSE1();
50 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
54 RegInfo = TM.getRegisterInfo();
56 // Set up the TargetLowering object.
58 // X86 is weird, it always uses i8 for shift amounts and setcc results.
59 setShiftAmountType(MVT::i8);
60 setSetCCResultType(MVT::i8);
61 setSetCCResultContents(ZeroOrOneSetCCResult);
62 setSchedulingPreference(SchedulingForRegPressure);
63 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
64 setStackPointerRegisterToSaveRestore(X86StackPtr);
66 if (Subtarget->isTargetDarwin()) {
67 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
68 setUseUnderscoreSetJmp(false);
69 setUseUnderscoreLongJmp(false);
70 } else if (Subtarget->isTargetMingw()) {
71 // MS runtime is weird: it exports _setjmp, but longjmp!
72 setUseUnderscoreSetJmp(true);
73 setUseUnderscoreLongJmp(false);
75 setUseUnderscoreSetJmp(true);
76 setUseUnderscoreLongJmp(true);
79 // Set up the register classes.
80 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
81 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
82 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
83 if (Subtarget->is64Bit())
84 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
86 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
88 // We don't accept any truncstore of integer registers.
89 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
90 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
91 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
92 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
93 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
94 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
96 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
98 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
99 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
100 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
102 if (Subtarget->is64Bit()) {
103 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
104 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
107 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
108 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
110 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
113 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
115 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
116 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
117 // SSE has no i16 to fp conversion, only i32
118 if (X86ScalarSSEf32) {
119 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
120 // f32 and f64 cases are Legal, f80 case is not
121 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
123 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
124 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
127 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
128 // are Legal, f80 is custom lowered.
129 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
130 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
132 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
134 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
135 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
137 if (X86ScalarSSEf32) {
138 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
139 // f32 and f64 cases are Legal, f80 case is not
140 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
142 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
143 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
146 // Handle FP_TO_UINT by promoting the destination to a larger signed
148 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
149 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
150 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
152 if (Subtarget->is64Bit()) {
153 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
154 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
156 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
157 // Expand FP_TO_UINT into a select.
158 // FIXME: We would like to use a Custom expander here eventually to do
159 // the optimal thing for SSE vs. the default expansion in the legalizer.
160 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
162 // With SSE3 we can use fisttpll to convert to a signed i64.
163 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
166 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
167 if (!X86ScalarSSEf64) {
168 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
169 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
172 // Scalar integer multiply, multiply-high, divide, and remainder are
173 // lowered to use operations that produce two results, to match the
174 // available instructions. This exposes the two-result form to trivial
175 // CSE, which is able to combine x/y and x%y into a single instruction,
176 // for example. The single-result multiply instructions are introduced
177 // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
179 setOperationAction(ISD::MUL , MVT::i8 , Expand);
180 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
181 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
182 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
183 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
184 setOperationAction(ISD::SREM , MVT::i8 , Expand);
185 setOperationAction(ISD::UREM , MVT::i8 , Expand);
186 setOperationAction(ISD::MUL , MVT::i16 , Expand);
187 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
188 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
189 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
190 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
191 setOperationAction(ISD::SREM , MVT::i16 , Expand);
192 setOperationAction(ISD::UREM , MVT::i16 , Expand);
193 setOperationAction(ISD::MUL , MVT::i32 , Expand);
194 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
195 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
196 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
197 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
198 setOperationAction(ISD::SREM , MVT::i32 , Expand);
199 setOperationAction(ISD::UREM , MVT::i32 , Expand);
200 setOperationAction(ISD::MUL , MVT::i64 , Expand);
201 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
202 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
203 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
204 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
205 setOperationAction(ISD::SREM , MVT::i64 , Expand);
206 setOperationAction(ISD::UREM , MVT::i64 , Expand);
208 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
209 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
210 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
211 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
212 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
213 if (Subtarget->is64Bit())
214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
218 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
219 setOperationAction(ISD::FREM , MVT::f64 , Expand);
220 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
222 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
223 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
224 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
225 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
226 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
227 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
228 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
229 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
230 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
231 if (Subtarget->is64Bit()) {
232 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
233 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
234 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
237 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
238 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
240 // These should be promoted to a larger select which is supported.
241 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
242 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
243 // X86 wants to expand cmov itself.
244 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
245 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
246 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
247 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
248 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
249 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
250 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
251 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
252 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
253 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
254 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
255 if (Subtarget->is64Bit()) {
256 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
257 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
259 // X86 ret instruction may pop stack.
260 setOperationAction(ISD::RET , MVT::Other, Custom);
261 if (!Subtarget->is64Bit())
262 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
265 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
266 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
267 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
268 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
269 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
270 if (Subtarget->is64Bit()) {
271 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
272 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
273 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
274 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
276 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
277 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
278 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
279 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
280 // X86 wants to expand memset / memcpy itself.
281 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
282 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
284 // Use the default ISD::LOCATION, ISD::DECLARE expansion.
285 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
286 // FIXME - use subtarget debug flags
287 if (!Subtarget->isTargetDarwin() &&
288 !Subtarget->isTargetELF() &&
289 !Subtarget->isTargetCygMing())
290 setOperationAction(ISD::LABEL, MVT::Other, Expand);
292 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
293 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
294 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
295 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
296 if (Subtarget->is64Bit()) {
298 setExceptionPointerRegister(X86::RAX);
299 setExceptionSelectorRegister(X86::RDX);
301 setExceptionPointerRegister(X86::EAX);
302 setExceptionSelectorRegister(X86::EDX);
304 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
306 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
308 setOperationAction(ISD::TRAP, MVT::Other, Legal);
310 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
311 setOperationAction(ISD::VASTART , MVT::Other, Custom);
312 setOperationAction(ISD::VAARG , MVT::Other, Expand);
313 setOperationAction(ISD::VAEND , MVT::Other, Expand);
314 if (Subtarget->is64Bit())
315 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
317 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
319 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
320 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
321 if (Subtarget->is64Bit())
322 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
323 if (Subtarget->isTargetCygMing())
324 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
326 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
328 if (X86ScalarSSEf64) {
329 // f32 and f64 use SSE.
330 // Set up the FP register classes.
331 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
332 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
334 // Use ANDPD to simulate FABS.
335 setOperationAction(ISD::FABS , MVT::f64, Custom);
336 setOperationAction(ISD::FABS , MVT::f32, Custom);
338 // Use XORP to simulate FNEG.
339 setOperationAction(ISD::FNEG , MVT::f64, Custom);
340 setOperationAction(ISD::FNEG , MVT::f32, Custom);
342 // Use ANDPD and ORPD to simulate FCOPYSIGN.
343 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
344 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
346 // We don't support sin/cos/fmod
347 setOperationAction(ISD::FSIN , MVT::f64, Expand);
348 setOperationAction(ISD::FCOS , MVT::f64, Expand);
349 setOperationAction(ISD::FREM , MVT::f64, Expand);
350 setOperationAction(ISD::FSIN , MVT::f32, Expand);
351 setOperationAction(ISD::FCOS , MVT::f32, Expand);
352 setOperationAction(ISD::FREM , MVT::f32, Expand);
354 // Expand FP immediates into loads from the stack, except for the special
356 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
357 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
358 addLegalFPImmediate(APFloat(+0.0)); // xorpd
359 addLegalFPImmediate(APFloat(+0.0f)); // xorps
361 // Floating truncations from f80 and extensions to f80 go through memory.
362 // If optimizing, we lie about this though and handle it in
363 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
365 setConvertAction(MVT::f32, MVT::f80, Expand);
366 setConvertAction(MVT::f64, MVT::f80, Expand);
367 setConvertAction(MVT::f80, MVT::f32, Expand);
368 setConvertAction(MVT::f80, MVT::f64, Expand);
370 } else if (X86ScalarSSEf32) {
371 // Use SSE for f32, x87 for f64.
372 // Set up the FP register classes.
373 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
374 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
376 // Use ANDPS to simulate FABS.
377 setOperationAction(ISD::FABS , MVT::f32, Custom);
379 // Use XORP to simulate FNEG.
380 setOperationAction(ISD::FNEG , MVT::f32, Custom);
382 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
384 // Use ANDPS and ORPS to simulate FCOPYSIGN.
385 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
386 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
388 // We don't support sin/cos/fmod
389 setOperationAction(ISD::FSIN , MVT::f32, Expand);
390 setOperationAction(ISD::FCOS , MVT::f32, Expand);
391 setOperationAction(ISD::FREM , MVT::f32, Expand);
393 // Expand FP immediates into loads from the stack, except for the special
395 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
396 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
397 addLegalFPImmediate(APFloat(+0.0f)); // xorps
398 addLegalFPImmediate(APFloat(+0.0)); // FLD0
399 addLegalFPImmediate(APFloat(+1.0)); // FLD1
400 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
401 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
403 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
404 // this though and handle it in InstructionSelectPreprocess so that
405 // dagcombine2 can hack on these.
407 setConvertAction(MVT::f32, MVT::f64, Expand);
408 setConvertAction(MVT::f32, MVT::f80, Expand);
409 setConvertAction(MVT::f80, MVT::f32, Expand);
410 setConvertAction(MVT::f64, MVT::f32, Expand);
411 // And x87->x87 truncations also.
412 setConvertAction(MVT::f80, MVT::f64, Expand);
416 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
417 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
420 // f32 and f64 in x87.
421 // Set up the FP register classes.
422 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
423 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
425 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
426 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
427 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
428 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
430 // Floating truncations go through memory. If optimizing, we lie about
431 // this though and handle it in InstructionSelectPreprocess so that
432 // dagcombine2 can hack on these.
434 setConvertAction(MVT::f80, MVT::f32, Expand);
435 setConvertAction(MVT::f64, MVT::f32, Expand);
436 setConvertAction(MVT::f80, MVT::f64, Expand);
440 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
441 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
444 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
445 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
446 addLegalFPImmediate(APFloat(+0.0)); // FLD0
447 addLegalFPImmediate(APFloat(+1.0)); // FLD1
448 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
449 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
450 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
451 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
452 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
453 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
456 // Long double always uses X87.
457 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
458 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
459 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
461 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
462 APFloat TmpFlt(+0.0);
463 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
464 addLegalFPImmediate(TmpFlt); // FLD0
466 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
467 APFloat TmpFlt2(+1.0);
468 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
469 addLegalFPImmediate(TmpFlt2); // FLD1
470 TmpFlt2.changeSign();
471 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
475 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
476 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
479 // Always use a library call for pow.
480 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
481 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
482 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
484 // First set operation action for all vector types to expand. Then we
485 // will selectively turn on ones that can be effectively codegen'd.
486 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
487 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
488 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
489 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
490 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
491 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
492 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
493 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
494 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
495 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
496 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
497 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
498 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
499 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
500 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
501 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
502 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
503 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
504 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
505 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
506 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
507 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
508 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
509 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
510 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
511 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
512 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
513 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
514 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
515 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
516 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
517 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
518 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
519 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
520 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
521 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
522 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
523 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
524 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
527 if (Subtarget->hasMMX()) {
528 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
529 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
530 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
531 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
533 // FIXME: add MMX packed arithmetics
535 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
536 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
537 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
538 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
540 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
541 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
542 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
543 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
545 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
546 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
548 setOperationAction(ISD::AND, MVT::v8i8, Promote);
549 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
550 setOperationAction(ISD::AND, MVT::v4i16, Promote);
551 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
552 setOperationAction(ISD::AND, MVT::v2i32, Promote);
553 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
554 setOperationAction(ISD::AND, MVT::v1i64, Legal);
556 setOperationAction(ISD::OR, MVT::v8i8, Promote);
557 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
558 setOperationAction(ISD::OR, MVT::v4i16, Promote);
559 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
560 setOperationAction(ISD::OR, MVT::v2i32, Promote);
561 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
562 setOperationAction(ISD::OR, MVT::v1i64, Legal);
564 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
565 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
566 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
567 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
568 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
569 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
570 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
572 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
573 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
574 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
575 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
576 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
577 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
578 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
580 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
581 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
582 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
583 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
585 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
586 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
587 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
588 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
590 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
591 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
592 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
593 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
596 if (Subtarget->hasSSE1()) {
597 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
599 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
600 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
601 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
602 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
603 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
604 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
605 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
606 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
607 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
608 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
609 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
612 if (Subtarget->hasSSE2()) {
613 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
614 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
615 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
616 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
617 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
619 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
620 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
621 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
622 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
623 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
624 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
625 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
626 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
627 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
628 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
629 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
630 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
631 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
632 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
633 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
635 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
636 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
637 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
638 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
639 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
640 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
642 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
643 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
644 // Do not attempt to custom lower non-power-of-2 vectors
645 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
647 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
648 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
649 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
651 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
652 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
653 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
654 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
655 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
656 if (Subtarget->is64Bit())
657 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
659 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
660 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
661 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
662 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
663 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
664 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
665 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
666 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
667 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
668 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
669 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
670 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
673 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
675 // Custom lower v2i64 and v2f64 selects.
676 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
677 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
678 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
679 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
682 // We want to custom lower some of our intrinsics.
683 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
685 // We have target-specific dag combine patterns for the following nodes:
686 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
687 setTargetDAGCombine(ISD::SELECT);
689 computeRegisterProperties();
691 // FIXME: These should be based on subtarget info. Plus, the values should
692 // be smaller when we are in optimizing for size mode.
693 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
694 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
695 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
696 allowUnalignedMemoryAccesses = true; // x86 supports it!
699 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
700 /// the desired ByVal argument alignment.
701 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
704 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
705 if (VTy->getBitWidth() == 128)
707 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
708 unsigned EltAlign = 0;
709 getMaxByValAlign(ATy->getElementType(), EltAlign);
710 if (EltAlign > MaxAlign)
712 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
713 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
714 unsigned EltAlign = 0;
715 getMaxByValAlign(STy->getElementType(i), EltAlign);
716 if (EltAlign > MaxAlign)
725 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
726 /// function arguments in the caller parameter area. For X86, aggregates
727 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
728 /// are at 4-byte boundaries.
729 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
730 if (Subtarget->is64Bit())
731 return getTargetData()->getABITypeAlignment(Ty);
733 if (Subtarget->hasSSE1())
734 getMaxByValAlign(Ty, Align);
738 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
740 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
741 SelectionDAG &DAG) const {
742 if (usesGlobalOffsetTable())
743 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
744 if (!Subtarget->isPICStyleRIPRel())
745 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
749 //===----------------------------------------------------------------------===//
750 // Return Value Calling Convention Implementation
751 //===----------------------------------------------------------------------===//
753 #include "X86GenCallingConv.inc"
755 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
756 /// exists skip possible ISD:TokenFactor.
757 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
758 if (Chain.getOpcode() == X86ISD::TAILCALL) {
760 } else if (Chain.getOpcode() == ISD::TokenFactor) {
761 if (Chain.getNumOperands() &&
762 Chain.getOperand(0).getOpcode() == X86ISD::TAILCALL)
763 return Chain.getOperand(0);
768 /// LowerRET - Lower an ISD::RET node.
769 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
770 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
772 SmallVector<CCValAssign, 16> RVLocs;
773 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
774 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
775 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
776 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
778 // If this is the first return lowered for this function, add the regs to the
779 // liveout set for the function.
780 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
781 for (unsigned i = 0; i != RVLocs.size(); ++i)
782 if (RVLocs[i].isRegLoc())
783 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
785 SDOperand Chain = Op.getOperand(0);
787 // Handle tail call return.
788 Chain = GetPossiblePreceedingTailCall(Chain);
789 if (Chain.getOpcode() == X86ISD::TAILCALL) {
790 SDOperand TailCall = Chain;
791 SDOperand TargetAddress = TailCall.getOperand(1);
792 SDOperand StackAdjustment = TailCall.getOperand(2);
793 assert(((TargetAddress.getOpcode() == ISD::Register &&
794 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
795 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
796 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
797 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
798 "Expecting an global address, external symbol, or register");
799 assert(StackAdjustment.getOpcode() == ISD::Constant &&
800 "Expecting a const value");
802 SmallVector<SDOperand,8> Operands;
803 Operands.push_back(Chain.getOperand(0));
804 Operands.push_back(TargetAddress);
805 Operands.push_back(StackAdjustment);
806 // Copy registers used by the call. Last operand is a flag so it is not
808 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
809 Operands.push_back(Chain.getOperand(i));
811 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
818 // Copy the result values into the output registers.
819 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
820 RVLocs[0].getLocReg() != X86::ST0) {
821 for (unsigned i = 0; i != RVLocs.size(); ++i) {
822 CCValAssign &VA = RVLocs[i];
823 assert(VA.isRegLoc() && "Can only return in registers!");
824 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
826 Flag = Chain.getValue(1);
829 // We need to handle a destination of ST0 specially, because it isn't really
831 SDOperand Value = Op.getOperand(1);
833 // an XMM register onto the fp-stack. Do this with an FP_EXTEND to f80.
834 // This will get legalized into a load/store if it can't get optimized away.
835 if (isScalarFPTypeInSSEReg(RVLocs[0].getValVT()))
836 Value = DAG.getNode(ISD::FP_EXTEND, MVT::f80, Value);
838 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
839 SDOperand Ops[] = { Chain, Value };
840 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
841 Flag = Chain.getValue(1);
844 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
846 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
848 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
852 /// LowerCallResult - Lower the result values of an ISD::CALL into the
853 /// appropriate copies out of appropriate physical registers. This assumes that
854 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
855 /// being lowered. The returns a SDNode with the same number of values as the
857 SDNode *X86TargetLowering::
858 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
859 unsigned CallingConv, SelectionDAG &DAG) {
861 // Assign locations to each value returned by this call.
862 SmallVector<CCValAssign, 16> RVLocs;
863 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
864 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
865 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
867 SmallVector<SDOperand, 8> ResultVals;
869 // Copy all of the result registers out of their specified physreg.
870 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
871 for (unsigned i = 0; i != RVLocs.size(); ++i) {
872 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
873 RVLocs[i].getValVT(), InFlag).getValue(1);
874 InFlag = Chain.getValue(2);
875 ResultVals.push_back(Chain.getValue(0));
878 // Copies from the FP stack are special, as ST0 isn't a valid register
879 // before the fp stackifier runs.
881 // Copy ST0 into an RFP register with FP_GET_RESULT. If this will end up
882 // in an SSE register, copy it out as F80 and do a truncate, otherwise use
883 // the specified value type.
884 MVT::ValueType GetResultTy = RVLocs[0].getValVT();
885 if (isScalarFPTypeInSSEReg(GetResultTy))
886 GetResultTy = MVT::f80;
887 SDVTList Tys = DAG.getVTList(GetResultTy, MVT::Other, MVT::Flag);
889 SDOperand GROps[] = { Chain, InFlag };
890 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
891 Chain = RetVal.getValue(1);
892 InFlag = RetVal.getValue(2);
894 // If we want the result in an SSE register, use an FP_TRUNCATE to get it
896 if (GetResultTy != RVLocs[0].getValVT())
897 RetVal = DAG.getNode(ISD::FP_ROUND, RVLocs[0].getValVT(), RetVal,
898 // This truncation won't change the value.
899 DAG.getIntPtrConstant(1));
901 ResultVals.push_back(RetVal);
904 // Merge everything together with a MERGE_VALUES node.
905 ResultVals.push_back(Chain);
906 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
907 &ResultVals[0], ResultVals.size()).Val;
910 /// LowerCallResultToTwo64BitRegs - Lower the result values of an x86-64
911 /// ISD::CALL where the results are known to be in two 64-bit registers,
912 /// e.g. XMM0 and XMM1. This simplify store the two values back to the
913 /// fixed stack slot allocated for StructRet.
914 SDNode *X86TargetLowering::
915 LowerCallResultToTwo64BitRegs(SDOperand Chain, SDOperand InFlag,
916 SDNode *TheCall, unsigned Reg1, unsigned Reg2,
917 MVT::ValueType VT, SelectionDAG &DAG) {
918 SDOperand RetVal1 = DAG.getCopyFromReg(Chain, Reg1, VT, InFlag);
919 Chain = RetVal1.getValue(1);
920 InFlag = RetVal1.getValue(2);
921 SDOperand RetVal2 = DAG.getCopyFromReg(Chain, Reg2, VT, InFlag);
922 Chain = RetVal2.getValue(1);
923 InFlag = RetVal2.getValue(2);
924 SDOperand FIN = TheCall->getOperand(5);
925 Chain = DAG.getStore(Chain, RetVal1, FIN, NULL, 0);
926 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
927 Chain = DAG.getStore(Chain, RetVal2, FIN, NULL, 0);
931 /// LowerCallResultToTwoX87Regs - Lower the result values of an x86-64 ISD::CALL
932 /// where the results are known to be in ST0 and ST1.
933 SDNode *X86TargetLowering::
934 LowerCallResultToTwoX87Regs(SDOperand Chain, SDOperand InFlag,
935 SDNode *TheCall, SelectionDAG &DAG) {
936 SmallVector<SDOperand, 8> ResultVals;
937 const MVT::ValueType VTs[] = { MVT::f80, MVT::f80, MVT::Other, MVT::Flag };
938 SDVTList Tys = DAG.getVTList(VTs, 4);
939 SDOperand Ops[] = { Chain, InFlag };
940 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT2, Tys, Ops, 2);
941 Chain = RetVal.getValue(2);
942 SDOperand FIN = TheCall->getOperand(5);
943 Chain = DAG.getStore(Chain, RetVal.getValue(1), FIN, NULL, 0);
944 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(16));
945 Chain = DAG.getStore(Chain, RetVal, FIN, NULL, 0);
949 //===----------------------------------------------------------------------===//
950 // C & StdCall & Fast Calling Convention implementation
951 //===----------------------------------------------------------------------===//
952 // StdCall calling convention seems to be standard for many Windows' API
953 // routines and around. It differs from C calling convention just a little:
954 // callee should clean up the stack, not caller. Symbols should be also
955 // decorated in some fancy way :) It doesn't support any vector arguments.
956 // For info on fast calling convention see Fast Calling Convention (tail call)
957 // implementation LowerX86_32FastCCCallTo.
959 /// AddLiveIn - This helper function adds the specified physical register to the
960 /// MachineFunction as a live in value. It also creates a corresponding virtual
962 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
963 const TargetRegisterClass *RC) {
964 assert(RC->contains(PReg) && "Not the correct regclass!");
965 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
966 MF.getRegInfo().addLiveIn(PReg, VReg);
970 // Determines whether a CALL node uses struct return semantics.
971 static bool CallIsStructReturn(SDOperand Op) {
972 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
976 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(6));
977 return Flags->getValue() & ISD::ParamFlags::StructReturn;
980 // Determines whether a FORMAL_ARGUMENTS node uses struct return semantics.
981 static bool ArgsAreStructReturn(SDOperand Op) {
982 unsigned NumArgs = Op.Val->getNumValues() - 1;
986 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(3));
987 return Flags->getValue() & ISD::ParamFlags::StructReturn;
990 // Determines whether a CALL or FORMAL_ARGUMENTS node requires the callee to pop
991 // its own arguments. Callee pop is necessary to support tail calls.
992 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
993 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
997 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1000 case CallingConv::X86_StdCall:
1001 return !Subtarget->is64Bit();
1002 case CallingConv::X86_FastCall:
1003 return !Subtarget->is64Bit();
1004 case CallingConv::Fast:
1005 return PerformTailCallOpt;
1009 // Selects the correct CCAssignFn for a CALL or FORMAL_ARGUMENTS node.
1010 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1011 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1013 if (Subtarget->is64Bit())
1014 if (CC == CallingConv::Fast && PerformTailCallOpt)
1015 return CC_X86_64_TailCall;
1019 if (CC == CallingConv::X86_FastCall)
1020 return CC_X86_32_FastCall;
1021 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1022 return CC_X86_32_TailCall;
1027 // Selects the appropriate decoration to apply to a MachineFunction containing a
1028 // given FORMAL_ARGUMENTS node.
1030 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1031 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1032 if (CC == CallingConv::X86_FastCall)
1034 else if (CC == CallingConv::X86_StdCall)
1040 // IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could possibly
1041 // be overwritten when lowering the outgoing arguments in a tail call. Currently
1042 // the implementation of this call is very conservative and assumes all
1043 // arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with virtual
1044 // registers would be overwritten by direct lowering.
1045 // Possible improvement:
1046 // Check FORMAL_ARGUMENTS corresponding MERGE_VALUES for CopyFromReg nodes
1047 // indicating inreg passed arguments which also need not be lowered to a safe
1049 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op) {
1050 RegisterSDNode * OpReg = NULL;
1051 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
1052 (Op.getOpcode()== ISD::CopyFromReg &&
1053 (OpReg = cast<RegisterSDNode>(Op.getOperand(1))) &&
1054 OpReg->getReg() >= MRegisterInfo::FirstVirtualRegister))
1059 // CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1060 // by "Src" to address "Dst" with size and alignment information specified by
1061 // the specific parameter attribute. The copy will be passed as a byval function
1064 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1065 unsigned Flags, SelectionDAG &DAG) {
1066 unsigned Align = 1 <<
1067 ((Flags & ISD::ParamFlags::ByValAlign) >> ISD::ParamFlags::ByValAlignOffs);
1068 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1069 ISD::ParamFlags::ByValSizeOffs;
1070 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1071 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1072 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1073 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, AlignNode, AlwaysInline);
1076 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1077 const CCValAssign &VA,
1078 MachineFrameInfo *MFI,
1079 SDOperand Root, unsigned i) {
1080 // Create the nodes corresponding to a load from this parameter slot.
1081 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
1082 bool isByVal = Flags & ISD::ParamFlags::ByVal;
1084 // FIXME: For now, all byval parameter objects are marked mutable. This
1085 // can be changed with more analysis.
1086 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1087 VA.getLocMemOffset(), !isByVal);
1088 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1091 return DAG.getLoad(VA.getValVT(), Root, FIN,
1092 PseudoSourceValue::getFixedStack(), FI);
1096 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1097 MachineFunction &MF = DAG.getMachineFunction();
1098 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1100 const Function* Fn = MF.getFunction();
1101 if (Fn->hasExternalLinkage() &&
1102 Subtarget->isTargetCygMing() &&
1103 Fn->getName() == "main")
1104 FuncInfo->setForceFramePointer(true);
1106 // Decorate the function name.
1107 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1109 MachineFrameInfo *MFI = MF.getFrameInfo();
1110 SDOperand Root = Op.getOperand(0);
1111 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1112 unsigned CC = MF.getFunction()->getCallingConv();
1113 bool Is64Bit = Subtarget->is64Bit();
1115 assert(!(isVarArg && CC == CallingConv::Fast) &&
1116 "Var args not supported with calling convention fastcc");
1118 // Assign locations to all of the incoming arguments.
1119 SmallVector<CCValAssign, 16> ArgLocs;
1120 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1121 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1123 SmallVector<SDOperand, 8> ArgValues;
1124 unsigned LastVal = ~0U;
1125 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1126 CCValAssign &VA = ArgLocs[i];
1127 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1129 assert(VA.getValNo() != LastVal &&
1130 "Don't support value assigned to multiple locs yet");
1131 LastVal = VA.getValNo();
1133 if (VA.isRegLoc()) {
1134 MVT::ValueType RegVT = VA.getLocVT();
1135 TargetRegisterClass *RC;
1136 if (RegVT == MVT::i32)
1137 RC = X86::GR32RegisterClass;
1138 else if (Is64Bit && RegVT == MVT::i64)
1139 RC = X86::GR64RegisterClass;
1140 else if (RegVT == MVT::f32)
1141 RC = X86::FR32RegisterClass;
1142 else if (RegVT == MVT::f64)
1143 RC = X86::FR64RegisterClass;
1145 assert(MVT::isVector(RegVT));
1146 if (Is64Bit && MVT::getSizeInBits(RegVT) == 64) {
1147 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1150 RC = X86::VR128RegisterClass;
1153 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1154 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1156 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1157 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1159 if (VA.getLocInfo() == CCValAssign::SExt)
1160 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1161 DAG.getValueType(VA.getValVT()));
1162 else if (VA.getLocInfo() == CCValAssign::ZExt)
1163 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1164 DAG.getValueType(VA.getValVT()));
1166 if (VA.getLocInfo() != CCValAssign::Full)
1167 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1169 // Handle MMX values passed in GPRs.
1170 if (Is64Bit && RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1171 MVT::getSizeInBits(RegVT) == 64)
1172 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1174 ArgValues.push_back(ArgValue);
1176 assert(VA.isMemLoc());
1177 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1181 unsigned StackSize = CCInfo.getNextStackOffset();
1182 // align stack specially for tail calls
1183 if (CC == CallingConv::Fast)
1184 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1186 // If the function takes variable number of arguments, make a frame index for
1187 // the start of the first vararg value... for expansion of llvm.va_start.
1189 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1190 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1193 static const unsigned GPR64ArgRegs[] = {
1194 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1196 static const unsigned XMMArgRegs[] = {
1197 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1198 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1201 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1202 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1204 // For X86-64, if there are vararg parameters that are passed via
1205 // registers, then we must store them to their spots on the stack so they
1206 // may be loaded by deferencing the result of va_next.
1207 VarArgsGPOffset = NumIntRegs * 8;
1208 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1209 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1211 // Store the integer parameter registers.
1212 SmallVector<SDOperand, 8> MemOps;
1213 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1214 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1215 DAG.getIntPtrConstant(VarArgsGPOffset));
1216 for (; NumIntRegs != 6; ++NumIntRegs) {
1217 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1218 X86::GR64RegisterClass);
1219 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1221 DAG.getStore(Val.getValue(1), Val, FIN,
1222 PseudoSourceValue::getFixedStack(),
1224 MemOps.push_back(Store);
1225 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1226 DAG.getIntPtrConstant(8));
1229 // Now store the XMM (fp + vector) parameter registers.
1230 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1231 DAG.getIntPtrConstant(VarArgsFPOffset));
1232 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1233 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1234 X86::VR128RegisterClass);
1235 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1237 DAG.getStore(Val.getValue(1), Val, FIN,
1238 PseudoSourceValue::getFixedStack(),
1240 MemOps.push_back(Store);
1241 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1242 DAG.getIntPtrConstant(16));
1244 if (!MemOps.empty())
1245 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1246 &MemOps[0], MemOps.size());
1250 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1251 // arguments and the arguments after the retaddr has been pushed are
1253 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1254 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1255 (StackSize & 7) == 0)
1258 ArgValues.push_back(Root);
1260 // Some CCs need callee pop.
1261 if (IsCalleePop(Op)) {
1262 BytesToPopOnReturn = StackSize; // Callee pops everything.
1263 BytesCallerReserves = 0;
1265 BytesToPopOnReturn = 0; // Callee pops nothing.
1266 // If this is an sret function, the return should pop the hidden pointer.
1267 if (!Is64Bit && ArgsAreStructReturn(Op))
1268 BytesToPopOnReturn = 4;
1269 BytesCallerReserves = StackSize;
1273 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1274 if (CC == CallingConv::X86_FastCall)
1275 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1278 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1280 // Return the new list of results.
1281 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1282 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1286 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1287 const SDOperand &StackPtr,
1288 const CCValAssign &VA,
1291 unsigned LocMemOffset = VA.getLocMemOffset();
1292 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1293 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1294 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1295 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1296 if (Flags & ISD::ParamFlags::ByVal) {
1297 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1299 return DAG.getStore(Chain, Arg, PtrOff,
1300 PseudoSourceValue::getStack(), LocMemOffset);
1303 /// ClassifyX86_64SRetCallReturn - Classify how to implement a x86-64
1304 /// struct return call to the specified function. X86-64 ABI specifies
1305 /// some SRet calls are actually returned in registers. Since current
1306 /// LLVM cannot represent multi-value calls, they are represent as
1307 /// calls where the results are passed in a hidden struct provided by
1308 /// the caller. This function examines the type of the struct to
1309 /// determine the correct way to implement the call.
1311 X86TargetLowering::ClassifyX86_64SRetCallReturn(const Function *Fn) {
1312 // FIXME: Disabled for now.
1313 return X86::InMemory;
1315 const PointerType *PTy = cast<PointerType>(Fn->arg_begin()->getType());
1316 const Type *RTy = PTy->getElementType();
1317 unsigned Size = getTargetData()->getABITypeSize(RTy);
1318 if (Size != 16 && Size != 32)
1319 return X86::InMemory;
1322 const StructType *STy = dyn_cast<StructType>(RTy);
1323 if (!STy) return X86::InMemory;
1324 if (STy->getNumElements() == 2 &&
1325 STy->getElementType(0) == Type::X86_FP80Ty &&
1326 STy->getElementType(1) == Type::X86_FP80Ty)
1331 for (Type::subtype_iterator I = RTy->subtype_begin(), E = RTy->subtype_end();
1333 const Type *STy = I->get();
1334 if (!STy->isFPOrFPVector()) {
1342 return X86::InGPR64;
1345 void X86TargetLowering::X86_64AnalyzeSRetCallOperands(SDNode *TheCall,
1348 unsigned NumOps = (TheCall->getNumOperands() - 5) / 2;
1349 for (unsigned i = 1; i != NumOps; ++i) {
1350 MVT::ValueType ArgVT = TheCall->getOperand(5+2*i).getValueType();
1351 SDOperand FlagOp = TheCall->getOperand(5+2*i+1);
1352 unsigned ArgFlags =cast<ConstantSDNode>(FlagOp)->getValue();
1353 if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo)) {
1354 cerr << "Call operand #" << i << " has unhandled type "
1355 << MVT::getValueTypeString(ArgVT) << "\n";
1361 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1362 MachineFunction &MF = DAG.getMachineFunction();
1363 SDOperand Chain = Op.getOperand(0);
1364 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1365 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1366 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1367 && CC == CallingConv::Fast && PerformTailCallOpt;
1368 SDOperand Callee = Op.getOperand(4);
1369 bool Is64Bit = Subtarget->is64Bit();
1370 bool IsStructRet = CallIsStructReturn(Op);
1372 assert(!(isVarArg && CC == CallingConv::Fast) &&
1373 "Var args not supported with calling convention fastcc");
1375 // Analyze operands of the call, assigning locations to each operand.
1376 SmallVector<CCValAssign, 16> ArgLocs;
1377 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1378 CCAssignFn *CCFn = CCAssignFnForNode(Op);
1380 X86::X86_64SRet SRetMethod = X86::InMemory;
1381 if (Is64Bit && IsStructRet)
1382 // FIXME: We can't figure out type of the sret structure for indirect
1383 // calls. We need to copy more information from CallSite to the ISD::CALL
1385 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1387 ClassifyX86_64SRetCallReturn(dyn_cast<Function>(G->getGlobal()));
1389 // UGLY HACK! For x86-64, some 128-bit aggregates are returns in a pair of
1390 // registers. Unfortunately, llvm does not support i128 yet so we pretend it's
1392 if (SRetMethod != X86::InMemory)
1393 X86_64AnalyzeSRetCallOperands(Op.Val, CCFn, CCInfo);
1395 CCInfo.AnalyzeCallOperands(Op.Val, CCFn);
1397 // Get a count of how many bytes are to be pushed on the stack.
1398 unsigned NumBytes = CCInfo.getNextStackOffset();
1399 if (CC == CallingConv::Fast)
1400 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1402 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1403 // arguments and the arguments after the retaddr has been pushed are aligned.
1404 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1405 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1406 (NumBytes & 7) == 0)
1411 // Lower arguments at fp - stackoffset + fpdiff.
1412 unsigned NumBytesCallerPushed =
1413 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1414 FPDiff = NumBytesCallerPushed - NumBytes;
1416 // Set the delta of movement of the returnaddr stackslot.
1417 // But only set if delta is greater than previous delta.
1418 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1419 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1422 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1424 SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
1426 // Adjust the Return address stack slot.
1428 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1429 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1430 // Load the "old" Return address.
1432 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1433 // Calculate the new stack slot for the return address.
1434 int SlotSize = Is64Bit ? 8 : 4;
1435 int NewReturnAddrFI =
1436 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1437 NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1438 Chain = SDOperand(RetAddrFrIdx.Val, 1);
1442 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1443 SmallVector<SDOperand, 8> MemOpChains;
1447 // Walk the register/memloc assignments, inserting copies/loads. For tail
1448 // calls, lower arguments which could otherwise be possibly overwritten to the
1449 // stack slot where they would go on normal function calls.
1450 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1451 CCValAssign &VA = ArgLocs[i];
1452 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1454 // Promote the value if needed.
1455 switch (VA.getLocInfo()) {
1456 default: assert(0 && "Unknown loc info!");
1457 case CCValAssign::Full: break;
1458 case CCValAssign::SExt:
1459 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1461 case CCValAssign::ZExt:
1462 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1464 case CCValAssign::AExt:
1465 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1469 if (VA.isRegLoc()) {
1470 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1472 if (!IsTailCall || IsPossiblyOverwrittenArgumentOfTailCall(Arg)) {
1473 assert(VA.isMemLoc());
1474 if (StackPtr.Val == 0)
1475 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1477 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1483 if (!MemOpChains.empty())
1484 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1485 &MemOpChains[0], MemOpChains.size());
1487 // Build a sequence of copy-to-reg nodes chained together with token chain
1488 // and flag operands which copy the outgoing args into registers.
1490 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1491 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1493 InFlag = Chain.getValue(1);
1497 InFlag = SDOperand(); // ??? Isn't this nuking the preceding loop's output?
1499 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1501 // Does not work with tail call since ebx is not restored correctly by
1502 // tailcaller. TODO: at least for x86 - verify for x86-64
1503 if (!IsTailCall && !Is64Bit &&
1504 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1505 Subtarget->isPICStyleGOT()) {
1506 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1507 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1509 InFlag = Chain.getValue(1);
1512 if (Is64Bit && isVarArg) {
1513 // From AMD64 ABI document:
1514 // For calls that may call functions that use varargs or stdargs
1515 // (prototype-less calls or calls to functions containing ellipsis (...) in
1516 // the declaration) %al is used as hidden argument to specify the number
1517 // of SSE registers used. The contents of %al do not need to match exactly
1518 // the number of registers, but must be an ubound on the number of SSE
1519 // registers used and is in the range 0 - 8 inclusive.
1521 // Count the number of XMM registers allocated.
1522 static const unsigned XMMArgRegs[] = {
1523 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1524 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1526 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1528 Chain = DAG.getCopyToReg(Chain, X86::AL,
1529 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1530 InFlag = Chain.getValue(1);
1533 // For tail calls lower the arguments to the 'real' stack slot.
1535 SmallVector<SDOperand, 8> MemOpChains2;
1538 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1539 CCValAssign &VA = ArgLocs[i];
1540 if (!VA.isRegLoc()) {
1541 assert(VA.isMemLoc());
1542 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1543 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1544 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1545 // Create frame index.
1546 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1547 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1548 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1549 FIN = DAG.getFrameIndex(FI, MVT::i32);
1550 SDOperand Source = Arg;
1551 if (IsPossiblyOverwrittenArgumentOfTailCall(Arg)) {
1552 // Copy from stack slots to stack slot of a tail called function. This
1553 // needs to be done because if we would lower the arguments directly
1554 // to their real stack slot we might end up overwriting each other.
1555 // Get source stack slot.
1556 Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1557 if (StackPtr.Val == 0)
1558 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1559 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1560 if ((Flags & ISD::ParamFlags::ByVal)==0)
1561 Source = DAG.getLoad(VA.getValVT(), Chain, Source, NULL, 0);
1564 if (Flags & ISD::ParamFlags::ByVal) {
1565 // Copy relative to framepointer.
1566 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1569 // Store relative to framepointer.
1570 MemOpChains2.push_back(
1571 DAG.getStore(Chain, Source, FIN,
1572 PseudoSourceValue::getFixedStack(), FI));
1577 if (!MemOpChains2.empty())
1578 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1579 &MemOpChains2[0], MemOpChains2.size());
1581 // Store the return address to the appropriate stack slot.
1583 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1586 // If the callee is a GlobalAddress node (quite common, every direct call is)
1587 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1588 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1589 // We should use extra load for direct calls to dllimported functions in
1591 if ((IsTailCall || !Is64Bit ||
1592 getTargetMachine().getCodeModel() != CodeModel::Large)
1593 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1594 getTargetMachine(), true))
1595 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1596 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1597 if (IsTailCall || !Is64Bit ||
1598 getTargetMachine().getCodeModel() != CodeModel::Large)
1599 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1600 } else if (IsTailCall) {
1601 assert(Callee.getOpcode() == ISD::LOAD &&
1602 "Function destination must be loaded into virtual register");
1603 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1605 Chain = DAG.getCopyToReg(Chain,
1606 DAG.getRegister(Opc, getPointerTy()) ,
1608 Callee = DAG.getRegister(Opc, getPointerTy());
1609 // Add register as live out.
1610 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1613 // Returns a chain & a flag for retval copy to use.
1614 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1615 SmallVector<SDOperand, 8> Ops;
1618 Ops.push_back(Chain);
1619 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1620 Ops.push_back(DAG.getIntPtrConstant(0));
1622 Ops.push_back(InFlag);
1623 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1624 InFlag = Chain.getValue(1);
1626 // Returns a chain & a flag for retval copy to use.
1627 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1631 Ops.push_back(Chain);
1632 Ops.push_back(Callee);
1635 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1637 // Add an implicit use GOT pointer in EBX.
1638 if (!IsTailCall && !Is64Bit &&
1639 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1640 Subtarget->isPICStyleGOT())
1641 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1643 // Add argument registers to the end of the list so that they are known live
1645 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1646 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1647 RegsToPass[i].second.getValueType()));
1650 Ops.push_back(InFlag);
1653 assert(InFlag.Val &&
1654 "Flag must be set. Depend on flag being set in LowerRET");
1655 Chain = DAG.getNode(X86ISD::TAILCALL,
1656 Op.Val->getVTList(), &Ops[0], Ops.size());
1658 return SDOperand(Chain.Val, Op.ResNo);
1661 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1662 InFlag = Chain.getValue(1);
1664 // Create the CALLSEQ_END node.
1665 unsigned NumBytesForCalleeToPush;
1666 if (IsCalleePop(Op))
1667 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1668 else if (!Is64Bit && IsStructRet)
1669 // If this is is a call to a struct-return function, the callee
1670 // pops the hidden struct pointer, so we have to push it back.
1671 // This is common for Darwin/X86, Linux & Mingw32 targets.
1672 NumBytesForCalleeToPush = 4;
1674 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1676 // Returns a flag for retval copy to use.
1677 Chain = DAG.getCALLSEQ_END(Chain,
1678 DAG.getIntPtrConstant(NumBytes),
1679 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1681 InFlag = Chain.getValue(1);
1683 // Handle result values, copying them out of physregs into vregs that we
1685 switch (SRetMethod) {
1687 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1689 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1691 MVT::i64, DAG), Op.ResNo);
1693 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1694 X86::XMM0, X86::XMM1,
1695 MVT::f64, DAG), Op.ResNo);
1697 return SDOperand(LowerCallResultToTwoX87Regs(Chain, InFlag, Op.Val, DAG),
1703 //===----------------------------------------------------------------------===//
1704 // Fast Calling Convention (tail call) implementation
1705 //===----------------------------------------------------------------------===//
1707 // Like std call, callee cleans arguments, convention except that ECX is
1708 // reserved for storing the tail called function address. Only 2 registers are
1709 // free for argument passing (inreg). Tail call optimization is performed
1711 // * tailcallopt is enabled
1712 // * caller/callee are fastcc
1713 // * elf/pic is disabled OR
1714 // * elf/pic enabled + callee is in module + callee has
1715 // visibility protected or hidden
1716 // To keep the stack aligned according to platform abi the function
1717 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1718 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1719 // If a tail called function callee has more arguments than the caller the
1720 // caller needs to make sure that there is room to move the RETADDR to. This is
1721 // achieved by reserving an area the size of the argument delta right after the
1722 // original REtADDR, but before the saved framepointer or the spilled registers
1723 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1735 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1736 /// for a 16 byte align requirement.
1737 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1738 SelectionDAG& DAG) {
1739 if (PerformTailCallOpt) {
1740 MachineFunction &MF = DAG.getMachineFunction();
1741 const TargetMachine &TM = MF.getTarget();
1742 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1743 unsigned StackAlignment = TFI.getStackAlignment();
1744 uint64_t AlignMask = StackAlignment - 1;
1745 int64_t Offset = StackSize;
1746 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1747 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1748 // Number smaller than 12 so just add the difference.
1749 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1751 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1752 Offset = ((~AlignMask) & Offset) + StackAlignment +
1753 (StackAlignment-SlotSize);
1760 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1761 /// following the call is a return. A function is eligible if caller/callee
1762 /// calling conventions match, currently only fastcc supports tail calls, and
1763 /// the function CALL is immediatly followed by a RET.
1764 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1766 SelectionDAG& DAG) const {
1767 if (!PerformTailCallOpt)
1770 // Check whether CALL node immediatly preceeds the RET node and whether the
1771 // return uses the result of the node or is a void return.
1772 unsigned NumOps = Ret.getNumOperands();
1774 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1775 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1777 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1778 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1779 MachineFunction &MF = DAG.getMachineFunction();
1780 unsigned CallerCC = MF.getFunction()->getCallingConv();
1781 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1782 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1783 SDOperand Callee = Call.getOperand(4);
1784 // On elf/pic %ebx needs to be livein.
1785 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1786 !Subtarget->isPICStyleGOT())
1789 // Can only do local tail calls with PIC.
1790 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1791 return G->getGlobal()->hasHiddenVisibility()
1792 || G->getGlobal()->hasProtectedVisibility();
1799 //===----------------------------------------------------------------------===//
1800 // Other Lowering Hooks
1801 //===----------------------------------------------------------------------===//
1804 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1805 MachineFunction &MF = DAG.getMachineFunction();
1806 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1807 int ReturnAddrIndex = FuncInfo->getRAIndex();
1809 if (ReturnAddrIndex == 0) {
1810 // Set up a frame object for the return address.
1811 if (Subtarget->is64Bit())
1812 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1814 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1816 FuncInfo->setRAIndex(ReturnAddrIndex);
1819 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1824 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1825 /// specific condition code. It returns a false if it cannot do a direct
1826 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1828 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1829 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1830 SelectionDAG &DAG) {
1831 X86CC = X86::COND_INVALID;
1833 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1834 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1835 // X > -1 -> X == 0, jump !sign.
1836 RHS = DAG.getConstant(0, RHS.getValueType());
1837 X86CC = X86::COND_NS;
1839 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1840 // X < 0 -> X == 0, jump on sign.
1841 X86CC = X86::COND_S;
1843 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1845 RHS = DAG.getConstant(0, RHS.getValueType());
1846 X86CC = X86::COND_LE;
1851 switch (SetCCOpcode) {
1853 case ISD::SETEQ: X86CC = X86::COND_E; break;
1854 case ISD::SETGT: X86CC = X86::COND_G; break;
1855 case ISD::SETGE: X86CC = X86::COND_GE; break;
1856 case ISD::SETLT: X86CC = X86::COND_L; break;
1857 case ISD::SETLE: X86CC = X86::COND_LE; break;
1858 case ISD::SETNE: X86CC = X86::COND_NE; break;
1859 case ISD::SETULT: X86CC = X86::COND_B; break;
1860 case ISD::SETUGT: X86CC = X86::COND_A; break;
1861 case ISD::SETULE: X86CC = X86::COND_BE; break;
1862 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1865 // On a floating point condition, the flags are set as follows:
1867 // 0 | 0 | 0 | X > Y
1868 // 0 | 0 | 1 | X < Y
1869 // 1 | 0 | 0 | X == Y
1870 // 1 | 1 | 1 | unordered
1872 switch (SetCCOpcode) {
1875 case ISD::SETEQ: X86CC = X86::COND_E; break;
1876 case ISD::SETOLT: Flip = true; // Fallthrough
1878 case ISD::SETGT: X86CC = X86::COND_A; break;
1879 case ISD::SETOLE: Flip = true; // Fallthrough
1881 case ISD::SETGE: X86CC = X86::COND_AE; break;
1882 case ISD::SETUGT: Flip = true; // Fallthrough
1884 case ISD::SETLT: X86CC = X86::COND_B; break;
1885 case ISD::SETUGE: Flip = true; // Fallthrough
1887 case ISD::SETLE: X86CC = X86::COND_BE; break;
1889 case ISD::SETNE: X86CC = X86::COND_NE; break;
1890 case ISD::SETUO: X86CC = X86::COND_P; break;
1891 case ISD::SETO: X86CC = X86::COND_NP; break;
1894 std::swap(LHS, RHS);
1897 return X86CC != X86::COND_INVALID;
1900 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1901 /// code. Current x86 isa includes the following FP cmov instructions:
1902 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1903 static bool hasFPCMov(unsigned X86CC) {
1919 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1920 /// true if Op is undef or if its value falls within the specified range (L, H].
1921 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1922 if (Op.getOpcode() == ISD::UNDEF)
1925 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1926 return (Val >= Low && Val < Hi);
1929 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
1930 /// true if Op is undef or if its value equal to the specified value.
1931 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1932 if (Op.getOpcode() == ISD::UNDEF)
1934 return cast<ConstantSDNode>(Op)->getValue() == Val;
1937 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1938 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1939 bool X86::isPSHUFDMask(SDNode *N) {
1940 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1942 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
1945 // Check if the value doesn't reference the second vector.
1946 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1947 SDOperand Arg = N->getOperand(i);
1948 if (Arg.getOpcode() == ISD::UNDEF) continue;
1949 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1950 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
1957 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1958 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1959 bool X86::isPSHUFHWMask(SDNode *N) {
1960 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1962 if (N->getNumOperands() != 8)
1965 // Lower quadword copied in order.
1966 for (unsigned i = 0; i != 4; ++i) {
1967 SDOperand Arg = N->getOperand(i);
1968 if (Arg.getOpcode() == ISD::UNDEF) continue;
1969 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1970 if (cast<ConstantSDNode>(Arg)->getValue() != i)
1974 // Upper quadword shuffled.
1975 for (unsigned i = 4; i != 8; ++i) {
1976 SDOperand Arg = N->getOperand(i);
1977 if (Arg.getOpcode() == ISD::UNDEF) continue;
1978 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1979 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1980 if (Val < 4 || Val > 7)
1987 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
1988 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
1989 bool X86::isPSHUFLWMask(SDNode *N) {
1990 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1992 if (N->getNumOperands() != 8)
1995 // Upper quadword copied in order.
1996 for (unsigned i = 4; i != 8; ++i)
1997 if (!isUndefOrEqual(N->getOperand(i), i))
2000 // Lower quadword shuffled.
2001 for (unsigned i = 0; i != 4; ++i)
2002 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2008 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2009 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2010 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2011 if (NumElems != 2 && NumElems != 4) return false;
2013 unsigned Half = NumElems / 2;
2014 for (unsigned i = 0; i < Half; ++i)
2015 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2017 for (unsigned i = Half; i < NumElems; ++i)
2018 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2024 bool X86::isSHUFPMask(SDNode *N) {
2025 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2026 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2029 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2030 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2031 /// half elements to come from vector 1 (which would equal the dest.) and
2032 /// the upper half to come from vector 2.
2033 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2034 if (NumOps != 2 && NumOps != 4) return false;
2036 unsigned Half = NumOps / 2;
2037 for (unsigned i = 0; i < Half; ++i)
2038 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2040 for (unsigned i = Half; i < NumOps; ++i)
2041 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2046 static bool isCommutedSHUFP(SDNode *N) {
2047 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2048 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2051 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2052 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2053 bool X86::isMOVHLPSMask(SDNode *N) {
2054 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2056 if (N->getNumOperands() != 4)
2059 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2060 return isUndefOrEqual(N->getOperand(0), 6) &&
2061 isUndefOrEqual(N->getOperand(1), 7) &&
2062 isUndefOrEqual(N->getOperand(2), 2) &&
2063 isUndefOrEqual(N->getOperand(3), 3);
2066 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2067 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2069 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2070 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2072 if (N->getNumOperands() != 4)
2075 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2076 return isUndefOrEqual(N->getOperand(0), 2) &&
2077 isUndefOrEqual(N->getOperand(1), 3) &&
2078 isUndefOrEqual(N->getOperand(2), 2) &&
2079 isUndefOrEqual(N->getOperand(3), 3);
2082 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2083 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2084 bool X86::isMOVLPMask(SDNode *N) {
2085 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2087 unsigned NumElems = N->getNumOperands();
2088 if (NumElems != 2 && NumElems != 4)
2091 for (unsigned i = 0; i < NumElems/2; ++i)
2092 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2095 for (unsigned i = NumElems/2; i < NumElems; ++i)
2096 if (!isUndefOrEqual(N->getOperand(i), i))
2102 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2103 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2105 bool X86::isMOVHPMask(SDNode *N) {
2106 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2108 unsigned NumElems = N->getNumOperands();
2109 if (NumElems != 2 && NumElems != 4)
2112 for (unsigned i = 0; i < NumElems/2; ++i)
2113 if (!isUndefOrEqual(N->getOperand(i), i))
2116 for (unsigned i = 0; i < NumElems/2; ++i) {
2117 SDOperand Arg = N->getOperand(i + NumElems/2);
2118 if (!isUndefOrEqual(Arg, i + NumElems))
2125 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2126 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2127 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2128 bool V2IsSplat = false) {
2129 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2132 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2133 SDOperand BitI = Elts[i];
2134 SDOperand BitI1 = Elts[i+1];
2135 if (!isUndefOrEqual(BitI, j))
2138 if (isUndefOrEqual(BitI1, NumElts))
2141 if (!isUndefOrEqual(BitI1, j + NumElts))
2149 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2150 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2151 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2154 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2155 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2156 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2157 bool V2IsSplat = false) {
2158 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2161 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2162 SDOperand BitI = Elts[i];
2163 SDOperand BitI1 = Elts[i+1];
2164 if (!isUndefOrEqual(BitI, j + NumElts/2))
2167 if (isUndefOrEqual(BitI1, NumElts))
2170 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2178 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2179 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2180 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2183 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2184 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2186 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2187 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2189 unsigned NumElems = N->getNumOperands();
2190 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2193 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2194 SDOperand BitI = N->getOperand(i);
2195 SDOperand BitI1 = N->getOperand(i+1);
2197 if (!isUndefOrEqual(BitI, j))
2199 if (!isUndefOrEqual(BitI1, j))
2206 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2207 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2209 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2210 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2212 unsigned NumElems = N->getNumOperands();
2213 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2216 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2217 SDOperand BitI = N->getOperand(i);
2218 SDOperand BitI1 = N->getOperand(i + 1);
2220 if (!isUndefOrEqual(BitI, j))
2222 if (!isUndefOrEqual(BitI1, j))
2229 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2230 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2231 /// MOVSD, and MOVD, i.e. setting the lowest element.
2232 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2233 if (NumElts != 2 && NumElts != 4)
2236 if (!isUndefOrEqual(Elts[0], NumElts))
2239 for (unsigned i = 1; i < NumElts; ++i) {
2240 if (!isUndefOrEqual(Elts[i], i))
2247 bool X86::isMOVLMask(SDNode *N) {
2248 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2249 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2252 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2253 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2254 /// element of vector 2 and the other elements to come from vector 1 in order.
2255 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2256 bool V2IsSplat = false,
2257 bool V2IsUndef = false) {
2258 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2261 if (!isUndefOrEqual(Ops[0], 0))
2264 for (unsigned i = 1; i < NumOps; ++i) {
2265 SDOperand Arg = Ops[i];
2266 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2267 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2268 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2275 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2276 bool V2IsUndef = false) {
2277 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2278 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2279 V2IsSplat, V2IsUndef);
2282 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2283 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2284 bool X86::isMOVSHDUPMask(SDNode *N) {
2285 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2287 if (N->getNumOperands() != 4)
2290 // Expect 1, 1, 3, 3
2291 for (unsigned i = 0; i < 2; ++i) {
2292 SDOperand Arg = N->getOperand(i);
2293 if (Arg.getOpcode() == ISD::UNDEF) continue;
2294 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2295 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2296 if (Val != 1) return false;
2300 for (unsigned i = 2; i < 4; ++i) {
2301 SDOperand Arg = N->getOperand(i);
2302 if (Arg.getOpcode() == ISD::UNDEF) continue;
2303 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2304 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2305 if (Val != 3) return false;
2309 // Don't use movshdup if it can be done with a shufps.
2313 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2314 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2315 bool X86::isMOVSLDUPMask(SDNode *N) {
2316 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2318 if (N->getNumOperands() != 4)
2321 // Expect 0, 0, 2, 2
2322 for (unsigned i = 0; i < 2; ++i) {
2323 SDOperand Arg = N->getOperand(i);
2324 if (Arg.getOpcode() == ISD::UNDEF) continue;
2325 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2326 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2327 if (Val != 0) return false;
2331 for (unsigned i = 2; i < 4; ++i) {
2332 SDOperand Arg = N->getOperand(i);
2333 if (Arg.getOpcode() == ISD::UNDEF) continue;
2334 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2335 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2336 if (Val != 2) return false;
2340 // Don't use movshdup if it can be done with a shufps.
2344 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2345 /// specifies a identity operation on the LHS or RHS.
2346 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2347 unsigned NumElems = N->getNumOperands();
2348 for (unsigned i = 0; i < NumElems; ++i)
2349 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2354 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2355 /// a splat of a single element.
2356 static bool isSplatMask(SDNode *N) {
2357 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2359 // This is a splat operation if each element of the permute is the same, and
2360 // if the value doesn't reference the second vector.
2361 unsigned NumElems = N->getNumOperands();
2362 SDOperand ElementBase;
2364 for (; i != NumElems; ++i) {
2365 SDOperand Elt = N->getOperand(i);
2366 if (isa<ConstantSDNode>(Elt)) {
2372 if (!ElementBase.Val)
2375 for (; i != NumElems; ++i) {
2376 SDOperand Arg = N->getOperand(i);
2377 if (Arg.getOpcode() == ISD::UNDEF) continue;
2378 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2379 if (Arg != ElementBase) return false;
2382 // Make sure it is a splat of the first vector operand.
2383 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2386 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2387 /// a splat of a single element and it's a 2 or 4 element mask.
2388 bool X86::isSplatMask(SDNode *N) {
2389 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2391 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2392 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2394 return ::isSplatMask(N);
2397 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2398 /// specifies a splat of zero element.
2399 bool X86::isSplatLoMask(SDNode *N) {
2400 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2402 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2403 if (!isUndefOrEqual(N->getOperand(i), 0))
2408 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2409 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2411 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2412 unsigned NumOperands = N->getNumOperands();
2413 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2415 for (unsigned i = 0; i < NumOperands; ++i) {
2417 SDOperand Arg = N->getOperand(NumOperands-i-1);
2418 if (Arg.getOpcode() != ISD::UNDEF)
2419 Val = cast<ConstantSDNode>(Arg)->getValue();
2420 if (Val >= NumOperands) Val -= NumOperands;
2422 if (i != NumOperands - 1)
2429 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2430 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2432 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2434 // 8 nodes, but we only care about the last 4.
2435 for (unsigned i = 7; i >= 4; --i) {
2437 SDOperand Arg = N->getOperand(i);
2438 if (Arg.getOpcode() != ISD::UNDEF)
2439 Val = cast<ConstantSDNode>(Arg)->getValue();
2448 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2449 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2451 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2453 // 8 nodes, but we only care about the first 4.
2454 for (int i = 3; i >= 0; --i) {
2456 SDOperand Arg = N->getOperand(i);
2457 if (Arg.getOpcode() != ISD::UNDEF)
2458 Val = cast<ConstantSDNode>(Arg)->getValue();
2467 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2468 /// specifies a 8 element shuffle that can be broken into a pair of
2469 /// PSHUFHW and PSHUFLW.
2470 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2471 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2473 if (N->getNumOperands() != 8)
2476 // Lower quadword shuffled.
2477 for (unsigned i = 0; i != 4; ++i) {
2478 SDOperand Arg = N->getOperand(i);
2479 if (Arg.getOpcode() == ISD::UNDEF) continue;
2480 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2481 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2486 // Upper quadword shuffled.
2487 for (unsigned i = 4; i != 8; ++i) {
2488 SDOperand Arg = N->getOperand(i);
2489 if (Arg.getOpcode() == ISD::UNDEF) continue;
2490 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2491 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2492 if (Val < 4 || Val > 7)
2499 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2500 /// values in ther permute mask.
2501 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2502 SDOperand &V2, SDOperand &Mask,
2503 SelectionDAG &DAG) {
2504 MVT::ValueType VT = Op.getValueType();
2505 MVT::ValueType MaskVT = Mask.getValueType();
2506 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2507 unsigned NumElems = Mask.getNumOperands();
2508 SmallVector<SDOperand, 8> MaskVec;
2510 for (unsigned i = 0; i != NumElems; ++i) {
2511 SDOperand Arg = Mask.getOperand(i);
2512 if (Arg.getOpcode() == ISD::UNDEF) {
2513 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2516 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2517 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2519 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2521 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2525 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2526 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2529 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2530 /// the two vector operands have swapped position.
2532 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2533 MVT::ValueType MaskVT = Mask.getValueType();
2534 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2535 unsigned NumElems = Mask.getNumOperands();
2536 SmallVector<SDOperand, 8> MaskVec;
2537 for (unsigned i = 0; i != NumElems; ++i) {
2538 SDOperand Arg = Mask.getOperand(i);
2539 if (Arg.getOpcode() == ISD::UNDEF) {
2540 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2543 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2544 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2546 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2548 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2550 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2554 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2555 /// match movhlps. The lower half elements should come from upper half of
2556 /// V1 (and in order), and the upper half elements should come from the upper
2557 /// half of V2 (and in order).
2558 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2559 unsigned NumElems = Mask->getNumOperands();
2562 for (unsigned i = 0, e = 2; i != e; ++i)
2563 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2565 for (unsigned i = 2; i != 4; ++i)
2566 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2571 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2572 /// is promoted to a vector.
2573 static inline bool isScalarLoadToVector(SDNode *N) {
2574 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2575 N = N->getOperand(0).Val;
2576 return ISD::isNON_EXTLoad(N);
2581 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2582 /// match movlp{s|d}. The lower half elements should come from lower half of
2583 /// V1 (and in order), and the upper half elements should come from the upper
2584 /// half of V2 (and in order). And since V1 will become the source of the
2585 /// MOVLP, it must be either a vector load or a scalar load to vector.
2586 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2587 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2589 // Is V2 is a vector load, don't do this transformation. We will try to use
2590 // load folding shufps op.
2591 if (ISD::isNON_EXTLoad(V2))
2594 unsigned NumElems = Mask->getNumOperands();
2595 if (NumElems != 2 && NumElems != 4)
2597 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2598 if (!isUndefOrEqual(Mask->getOperand(i), i))
2600 for (unsigned i = NumElems/2; i != NumElems; ++i)
2601 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2606 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2608 static bool isSplatVector(SDNode *N) {
2609 if (N->getOpcode() != ISD::BUILD_VECTOR)
2612 SDOperand SplatValue = N->getOperand(0);
2613 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2614 if (N->getOperand(i) != SplatValue)
2619 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2621 static bool isUndefShuffle(SDNode *N) {
2622 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2625 SDOperand V1 = N->getOperand(0);
2626 SDOperand V2 = N->getOperand(1);
2627 SDOperand Mask = N->getOperand(2);
2628 unsigned NumElems = Mask.getNumOperands();
2629 for (unsigned i = 0; i != NumElems; ++i) {
2630 SDOperand Arg = Mask.getOperand(i);
2631 if (Arg.getOpcode() != ISD::UNDEF) {
2632 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2633 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2635 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2642 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2644 static inline bool isZeroNode(SDOperand Elt) {
2645 return ((isa<ConstantSDNode>(Elt) &&
2646 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2647 (isa<ConstantFPSDNode>(Elt) &&
2648 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2651 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2652 /// to an zero vector.
2653 static bool isZeroShuffle(SDNode *N) {
2654 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2657 SDOperand V1 = N->getOperand(0);
2658 SDOperand V2 = N->getOperand(1);
2659 SDOperand Mask = N->getOperand(2);
2660 unsigned NumElems = Mask.getNumOperands();
2661 for (unsigned i = 0; i != NumElems; ++i) {
2662 SDOperand Arg = Mask.getOperand(i);
2663 if (Arg.getOpcode() == ISD::UNDEF)
2666 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2667 if (Idx < NumElems) {
2668 unsigned Opc = V1.Val->getOpcode();
2669 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2671 if (Opc != ISD::BUILD_VECTOR ||
2672 !isZeroNode(V1.Val->getOperand(Idx)))
2674 } else if (Idx >= NumElems) {
2675 unsigned Opc = V2.Val->getOpcode();
2676 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2678 if (Opc != ISD::BUILD_VECTOR ||
2679 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2686 /// getZeroVector - Returns a vector of specified type with all zero elements.
2688 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2689 assert(MVT::isVector(VT) && "Expected a vector type");
2691 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2692 // type. This ensures they get CSE'd.
2693 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2695 if (MVT::getSizeInBits(VT) == 64) // MMX
2696 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2698 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2699 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2702 /// getOnesVector - Returns a vector of specified type with all bits set.
2704 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2705 assert(MVT::isVector(VT) && "Expected a vector type");
2707 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2708 // type. This ensures they get CSE'd.
2709 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2711 if (MVT::getSizeInBits(VT) == 64) // MMX
2712 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2714 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2715 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2719 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2720 /// that point to V2 points to its first element.
2721 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2722 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2724 bool Changed = false;
2725 SmallVector<SDOperand, 8> MaskVec;
2726 unsigned NumElems = Mask.getNumOperands();
2727 for (unsigned i = 0; i != NumElems; ++i) {
2728 SDOperand Arg = Mask.getOperand(i);
2729 if (Arg.getOpcode() != ISD::UNDEF) {
2730 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2731 if (Val > NumElems) {
2732 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2736 MaskVec.push_back(Arg);
2740 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2741 &MaskVec[0], MaskVec.size());
2745 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2746 /// operation of specified width.
2747 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2748 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2749 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2751 SmallVector<SDOperand, 8> MaskVec;
2752 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2753 for (unsigned i = 1; i != NumElems; ++i)
2754 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2755 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2758 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2759 /// of specified width.
2760 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2761 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2762 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2763 SmallVector<SDOperand, 8> MaskVec;
2764 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2765 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2766 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2768 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2771 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2772 /// of specified width.
2773 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2774 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2775 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2776 unsigned Half = NumElems/2;
2777 SmallVector<SDOperand, 8> MaskVec;
2778 for (unsigned i = 0; i != Half; ++i) {
2779 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2780 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2782 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2785 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2787 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2788 SDOperand V1 = Op.getOperand(0);
2789 SDOperand Mask = Op.getOperand(2);
2790 MVT::ValueType VT = Op.getValueType();
2791 unsigned NumElems = Mask.getNumOperands();
2792 Mask = getUnpacklMask(NumElems, DAG);
2793 while (NumElems != 4) {
2794 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2797 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2799 Mask = getZeroVector(MVT::v4i32, DAG);
2800 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2801 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2802 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2805 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2806 /// vector of zero or undef vector. This produces a shuffle where the low
2807 /// element of V2 is swizzled into the zero/undef vector, landing at element
2808 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2809 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2810 unsigned NumElems, unsigned Idx,
2811 bool isZero, SelectionDAG &DAG) {
2812 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2813 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2814 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2815 SmallVector<SDOperand, 16> MaskVec;
2816 for (unsigned i = 0; i != NumElems; ++i)
2817 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2818 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2820 MaskVec.push_back(DAG.getConstant(i, EVT));
2821 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2822 &MaskVec[0], MaskVec.size());
2823 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2826 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2828 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2829 unsigned NumNonZero, unsigned NumZero,
2830 SelectionDAG &DAG, TargetLowering &TLI) {
2836 for (unsigned i = 0; i < 16; ++i) {
2837 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2838 if (ThisIsNonZero && First) {
2840 V = getZeroVector(MVT::v8i16, DAG);
2842 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2847 SDOperand ThisElt(0, 0), LastElt(0, 0);
2848 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2849 if (LastIsNonZero) {
2850 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2852 if (ThisIsNonZero) {
2853 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2854 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2855 ThisElt, DAG.getConstant(8, MVT::i8));
2857 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2862 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2863 DAG.getIntPtrConstant(i/2));
2867 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2870 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2872 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2873 unsigned NumNonZero, unsigned NumZero,
2874 SelectionDAG &DAG, TargetLowering &TLI) {
2880 for (unsigned i = 0; i < 8; ++i) {
2881 bool isNonZero = (NonZeros & (1 << i)) != 0;
2885 V = getZeroVector(MVT::v8i16, DAG);
2887 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2890 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2891 DAG.getIntPtrConstant(i));
2899 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2900 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
2901 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
2902 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
2903 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
2904 // eliminated on x86-32 hosts.
2905 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
2908 if (ISD::isBuildVectorAllOnes(Op.Val))
2909 return getOnesVector(Op.getValueType(), DAG);
2910 return getZeroVector(Op.getValueType(), DAG);
2913 MVT::ValueType VT = Op.getValueType();
2914 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2915 unsigned EVTBits = MVT::getSizeInBits(EVT);
2917 unsigned NumElems = Op.getNumOperands();
2918 unsigned NumZero = 0;
2919 unsigned NumNonZero = 0;
2920 unsigned NonZeros = 0;
2921 bool HasNonImms = false;
2922 SmallSet<SDOperand, 8> Values;
2923 for (unsigned i = 0; i < NumElems; ++i) {
2924 SDOperand Elt = Op.getOperand(i);
2925 if (Elt.getOpcode() == ISD::UNDEF)
2928 if (Elt.getOpcode() != ISD::Constant &&
2929 Elt.getOpcode() != ISD::ConstantFP)
2931 if (isZeroNode(Elt))
2934 NonZeros |= (1 << i);
2939 if (NumNonZero == 0) {
2940 // All undef vector. Return an UNDEF. All zero vectors were handled above.
2941 return DAG.getNode(ISD::UNDEF, VT);
2944 // Splat is obviously ok. Let legalizer expand it to a shuffle.
2945 if (Values.size() == 1)
2948 // Special case for single non-zero element.
2949 if (NumNonZero == 1 && NumElems <= 4) {
2950 unsigned Idx = CountTrailingZeros_32(NonZeros);
2951 SDOperand Item = Op.getOperand(Idx);
2952 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
2954 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
2955 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
2957 else if (!HasNonImms) // Otherwise, it's better to do a constpool load.
2960 if (EVTBits == 32) {
2961 // Turn it into a shuffle of zero and zero-extended scalar to vector.
2962 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
2964 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2965 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
2966 SmallVector<SDOperand, 8> MaskVec;
2967 for (unsigned i = 0; i < NumElems; i++)
2968 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
2969 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2970 &MaskVec[0], MaskVec.size());
2971 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
2972 DAG.getNode(ISD::UNDEF, VT), Mask);
2976 // A vector full of immediates; various special cases are already
2977 // handled, so this is best done with a single constant-pool load.
2981 // Let legalizer expand 2-wide build_vectors.
2985 // If element VT is < 32 bits, convert it to inserts into a zero vector.
2986 if (EVTBits == 8 && NumElems == 16) {
2987 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
2989 if (V.Val) return V;
2992 if (EVTBits == 16 && NumElems == 8) {
2993 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
2995 if (V.Val) return V;
2998 // If element VT is == 32 bits, turn it into a number of shuffles.
2999 SmallVector<SDOperand, 8> V;
3001 if (NumElems == 4 && NumZero > 0) {
3002 for (unsigned i = 0; i < 4; ++i) {
3003 bool isZero = !(NonZeros & (1 << i));
3005 V[i] = getZeroVector(VT, DAG);
3007 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3010 for (unsigned i = 0; i < 2; ++i) {
3011 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3014 V[i] = V[i*2]; // Must be a zero vector.
3017 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3018 getMOVLMask(NumElems, DAG));
3021 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3022 getMOVLMask(NumElems, DAG));
3025 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3026 getUnpacklMask(NumElems, DAG));
3031 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3032 // clears the upper bits.
3033 // FIXME: we can do the same for v4f32 case when we know both parts of
3034 // the lower half come from scalar_to_vector (loadf32). We should do
3035 // that in post legalizer dag combiner with target specific hooks.
3036 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3038 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3039 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3040 SmallVector<SDOperand, 8> MaskVec;
3041 bool Reverse = (NonZeros & 0x3) == 2;
3042 for (unsigned i = 0; i < 2; ++i)
3044 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3046 MaskVec.push_back(DAG.getConstant(i, EVT));
3047 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3048 for (unsigned i = 0; i < 2; ++i)
3050 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3052 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3053 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3054 &MaskVec[0], MaskVec.size());
3055 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3058 if (Values.size() > 2) {
3059 // Expand into a number of unpckl*.
3061 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3062 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3063 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3064 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3065 for (unsigned i = 0; i < NumElems; ++i)
3066 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3068 while (NumElems != 0) {
3069 for (unsigned i = 0; i < NumElems; ++i)
3070 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3081 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3082 SDOperand PermMask, SelectionDAG &DAG,
3083 TargetLowering &TLI) {
3085 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3086 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3087 MVT::ValueType PtrVT = TLI.getPointerTy();
3088 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3089 PermMask.Val->op_end());
3091 // First record which half of which vector the low elements come from.
3092 SmallVector<unsigned, 4> LowQuad(4);
3093 for (unsigned i = 0; i < 4; ++i) {
3094 SDOperand Elt = MaskElts[i];
3095 if (Elt.getOpcode() == ISD::UNDEF)
3097 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3098 int QuadIdx = EltIdx / 4;
3101 int BestLowQuad = -1;
3102 unsigned MaxQuad = 1;
3103 for (unsigned i = 0; i < 4; ++i) {
3104 if (LowQuad[i] > MaxQuad) {
3106 MaxQuad = LowQuad[i];
3110 // Record which half of which vector the high elements come from.
3111 SmallVector<unsigned, 4> HighQuad(4);
3112 for (unsigned i = 4; i < 8; ++i) {
3113 SDOperand Elt = MaskElts[i];
3114 if (Elt.getOpcode() == ISD::UNDEF)
3116 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3117 int QuadIdx = EltIdx / 4;
3118 ++HighQuad[QuadIdx];
3120 int BestHighQuad = -1;
3122 for (unsigned i = 0; i < 4; ++i) {
3123 if (HighQuad[i] > MaxQuad) {
3125 MaxQuad = HighQuad[i];
3129 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3130 if (BestLowQuad != -1 || BestHighQuad != -1) {
3131 // First sort the 4 chunks in order using shufpd.
3132 SmallVector<SDOperand, 8> MaskVec;
3133 if (BestLowQuad != -1)
3134 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3136 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3137 if (BestHighQuad != -1)
3138 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3140 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3141 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3142 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3143 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3144 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3145 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3147 // Now sort high and low parts separately.
3148 BitVector InOrder(8);
3149 if (BestLowQuad != -1) {
3150 // Sort lower half in order using PSHUFLW.
3152 bool AnyOutOrder = false;
3153 for (unsigned i = 0; i != 4; ++i) {
3154 SDOperand Elt = MaskElts[i];
3155 if (Elt.getOpcode() == ISD::UNDEF) {
3156 MaskVec.push_back(Elt);
3159 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3162 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3163 // If this element is in the right place after this shuffle, then
3165 if ((int)(EltIdx / 4) == BestLowQuad)
3170 for (unsigned i = 4; i != 8; ++i)
3171 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3172 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3173 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3177 if (BestHighQuad != -1) {
3178 // Sort high half in order using PSHUFHW if possible.
3180 for (unsigned i = 0; i != 4; ++i)
3181 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3182 bool AnyOutOrder = false;
3183 for (unsigned i = 4; i != 8; ++i) {
3184 SDOperand Elt = MaskElts[i];
3185 if (Elt.getOpcode() == ISD::UNDEF) {
3186 MaskVec.push_back(Elt);
3189 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3192 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3193 // If this element is in the right place after this shuffle, then
3195 if ((int)(EltIdx / 4) == BestHighQuad)
3200 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3201 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3205 // The other elements are put in the right place using pextrw and pinsrw.
3206 for (unsigned i = 0; i != 8; ++i) {
3209 SDOperand Elt = MaskElts[i];
3210 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3213 SDOperand ExtOp = (EltIdx < 8)
3214 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3215 DAG.getConstant(EltIdx, PtrVT))
3216 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3217 DAG.getConstant(EltIdx - 8, PtrVT));
3218 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3219 DAG.getConstant(i, PtrVT));
3224 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3225 ///as few as possible.
3226 // First, let's find out how many elements are already in the right order.
3227 unsigned V1InOrder = 0;
3228 unsigned V1FromV1 = 0;
3229 unsigned V2InOrder = 0;
3230 unsigned V2FromV2 = 0;
3231 SmallVector<SDOperand, 8> V1Elts;
3232 SmallVector<SDOperand, 8> V2Elts;
3233 for (unsigned i = 0; i < 8; ++i) {
3234 SDOperand Elt = MaskElts[i];
3235 if (Elt.getOpcode() == ISD::UNDEF) {
3236 V1Elts.push_back(Elt);
3237 V2Elts.push_back(Elt);
3242 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3244 V1Elts.push_back(Elt);
3245 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3247 } else if (EltIdx == i+8) {
3248 V1Elts.push_back(Elt);
3249 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3251 } else if (EltIdx < 8) {
3252 V1Elts.push_back(Elt);
3255 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3260 if (V2InOrder > V1InOrder) {
3261 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3263 std::swap(V1Elts, V2Elts);
3264 std::swap(V1FromV1, V2FromV2);
3267 if ((V1FromV1 + V1InOrder) != 8) {
3268 // Some elements are from V2.
3270 // If there are elements that are from V1 but out of place,
3271 // then first sort them in place
3272 SmallVector<SDOperand, 8> MaskVec;
3273 for (unsigned i = 0; i < 8; ++i) {
3274 SDOperand Elt = V1Elts[i];
3275 if (Elt.getOpcode() == ISD::UNDEF) {
3276 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3279 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3281 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3283 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3285 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3286 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3290 for (unsigned i = 0; i < 8; ++i) {
3291 SDOperand Elt = V1Elts[i];
3292 if (Elt.getOpcode() == ISD::UNDEF)
3294 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3297 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3298 DAG.getConstant(EltIdx - 8, PtrVT));
3299 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3300 DAG.getConstant(i, PtrVT));
3304 // All elements are from V1.
3306 for (unsigned i = 0; i < 8; ++i) {
3307 SDOperand Elt = V1Elts[i];
3308 if (Elt.getOpcode() == ISD::UNDEF)
3310 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3311 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3312 DAG.getConstant(EltIdx, PtrVT));
3313 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3314 DAG.getConstant(i, PtrVT));
3320 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3321 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3322 /// done when every pair / quad of shuffle mask elements point to elements in
3323 /// the right sequence. e.g.
3324 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3326 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3328 SDOperand PermMask, SelectionDAG &DAG,
3329 TargetLowering &TLI) {
3330 unsigned NumElems = PermMask.getNumOperands();
3331 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3332 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3333 MVT::ValueType NewVT = MaskVT;
3335 case MVT::v4f32: NewVT = MVT::v2f64; break;
3336 case MVT::v4i32: NewVT = MVT::v2i64; break;
3337 case MVT::v8i16: NewVT = MVT::v4i32; break;
3338 case MVT::v16i8: NewVT = MVT::v4i32; break;
3339 default: assert(false && "Unexpected!");
3343 if (MVT::isInteger(VT))
3347 unsigned Scale = NumElems / NewWidth;
3348 SmallVector<SDOperand, 8> MaskVec;
3349 for (unsigned i = 0; i < NumElems; i += Scale) {
3350 unsigned StartIdx = ~0U;
3351 for (unsigned j = 0; j < Scale; ++j) {
3352 SDOperand Elt = PermMask.getOperand(i+j);
3353 if (Elt.getOpcode() == ISD::UNDEF)
3355 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3356 if (StartIdx == ~0U)
3357 StartIdx = EltIdx - (EltIdx % Scale);
3358 if (EltIdx != StartIdx + j)
3361 if (StartIdx == ~0U)
3362 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3364 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3367 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3368 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3369 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3370 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3371 &MaskVec[0], MaskVec.size()));
3375 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3376 SDOperand V1 = Op.getOperand(0);
3377 SDOperand V2 = Op.getOperand(1);
3378 SDOperand PermMask = Op.getOperand(2);
3379 MVT::ValueType VT = Op.getValueType();
3380 unsigned NumElems = PermMask.getNumOperands();
3381 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3382 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3383 bool V1IsSplat = false;
3384 bool V2IsSplat = false;
3386 if (isUndefShuffle(Op.Val))
3387 return DAG.getNode(ISD::UNDEF, VT);
3389 if (isZeroShuffle(Op.Val))
3390 return getZeroVector(VT, DAG);
3392 if (isIdentityMask(PermMask.Val))
3394 else if (isIdentityMask(PermMask.Val, true))
3397 if (isSplatMask(PermMask.Val)) {
3398 if (NumElems <= 4) return Op;
3399 // Promote it to a v4i32 splat.
3400 return PromoteSplat(Op, DAG);
3403 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3405 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3406 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3408 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3409 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3410 // FIXME: Figure out a cleaner way to do this.
3411 // Try to make use of movq to zero out the top part.
3412 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3413 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3415 SDOperand NewV1 = NewOp.getOperand(0);
3416 SDOperand NewV2 = NewOp.getOperand(1);
3417 SDOperand NewMask = NewOp.getOperand(2);
3418 if (isCommutedMOVL(NewMask.Val, true, false)) {
3419 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3420 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3421 NewV1, NewV2, getMOVLMask(2, DAG));
3422 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3425 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3426 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3427 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3428 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3432 if (X86::isMOVLMask(PermMask.Val))
3433 return (V1IsUndef) ? V2 : Op;
3435 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3436 X86::isMOVSLDUPMask(PermMask.Val) ||
3437 X86::isMOVHLPSMask(PermMask.Val) ||
3438 X86::isMOVHPMask(PermMask.Val) ||
3439 X86::isMOVLPMask(PermMask.Val))
3442 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3443 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3444 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3446 bool Commuted = false;
3447 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3448 // 1,1,1,1 -> v8i16 though.
3449 V1IsSplat = isSplatVector(V1.Val);
3450 V2IsSplat = isSplatVector(V2.Val);
3452 // Canonicalize the splat or undef, if present, to be on the RHS.
3453 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3454 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3455 std::swap(V1IsSplat, V2IsSplat);
3456 std::swap(V1IsUndef, V2IsUndef);
3460 // FIXME: Figure out a cleaner way to do this.
3461 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3462 if (V2IsUndef) return V1;
3463 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3465 // V2 is a splat, so the mask may be malformed. That is, it may point
3466 // to any V2 element. The instruction selectior won't like this. Get
3467 // a corrected mask and commute to form a proper MOVS{S|D}.
3468 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3469 if (NewMask.Val != PermMask.Val)
3470 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3475 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3476 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3477 X86::isUNPCKLMask(PermMask.Val) ||
3478 X86::isUNPCKHMask(PermMask.Val))
3482 // Normalize mask so all entries that point to V2 points to its first
3483 // element then try to match unpck{h|l} again. If match, return a
3484 // new vector_shuffle with the corrected mask.
3485 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3486 if (NewMask.Val != PermMask.Val) {
3487 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3488 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3489 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3490 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3491 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3492 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3497 // Normalize the node to match x86 shuffle ops if needed
3498 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3499 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3502 // Commute is back and try unpck* again.
3503 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3504 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3505 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3506 X86::isUNPCKLMask(PermMask.Val) ||
3507 X86::isUNPCKHMask(PermMask.Val))
3511 // If VT is integer, try PSHUF* first, then SHUFP*.
3512 if (MVT::isInteger(VT)) {
3513 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3514 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3515 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3516 X86::isPSHUFDMask(PermMask.Val)) ||
3517 X86::isPSHUFHWMask(PermMask.Val) ||
3518 X86::isPSHUFLWMask(PermMask.Val)) {
3519 if (V2.getOpcode() != ISD::UNDEF)
3520 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3521 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3525 if (X86::isSHUFPMask(PermMask.Val) &&
3526 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3529 // Floating point cases in the other order.
3530 if (X86::isSHUFPMask(PermMask.Val))
3532 if (X86::isPSHUFDMask(PermMask.Val) ||
3533 X86::isPSHUFHWMask(PermMask.Val) ||
3534 X86::isPSHUFLWMask(PermMask.Val)) {
3535 if (V2.getOpcode() != ISD::UNDEF)
3536 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3537 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3542 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3543 if (VT == MVT::v8i16) {
3544 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3549 // Handle all 4 wide cases with a number of shuffles.
3550 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3551 // Don't do this for MMX.
3552 MVT::ValueType MaskVT = PermMask.getValueType();
3553 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3554 SmallVector<std::pair<int, int>, 8> Locs;
3555 Locs.reserve(NumElems);
3556 SmallVector<SDOperand, 8> Mask1(NumElems,
3557 DAG.getNode(ISD::UNDEF, MaskEVT));
3558 SmallVector<SDOperand, 8> Mask2(NumElems,
3559 DAG.getNode(ISD::UNDEF, MaskEVT));
3562 // If no more than two elements come from either vector. This can be
3563 // implemented with two shuffles. First shuffle gather the elements.
3564 // The second shuffle, which takes the first shuffle as both of its
3565 // vector operands, put the elements into the right order.
3566 for (unsigned i = 0; i != NumElems; ++i) {
3567 SDOperand Elt = PermMask.getOperand(i);
3568 if (Elt.getOpcode() == ISD::UNDEF) {
3569 Locs[i] = std::make_pair(-1, -1);
3571 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3572 if (Val < NumElems) {
3573 Locs[i] = std::make_pair(0, NumLo);
3577 Locs[i] = std::make_pair(1, NumHi);
3578 if (2+NumHi < NumElems)
3579 Mask1[2+NumHi] = Elt;
3584 if (NumLo <= 2 && NumHi <= 2) {
3585 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3586 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3587 &Mask1[0], Mask1.size()));
3588 for (unsigned i = 0; i != NumElems; ++i) {
3589 if (Locs[i].first == -1)
3592 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3593 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3594 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3598 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3599 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3600 &Mask2[0], Mask2.size()));
3603 // Break it into (shuffle shuffle_hi, shuffle_lo).
3605 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3606 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3607 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3608 unsigned MaskIdx = 0;
3610 unsigned HiIdx = NumElems/2;
3611 for (unsigned i = 0; i != NumElems; ++i) {
3612 if (i == NumElems/2) {
3618 SDOperand Elt = PermMask.getOperand(i);
3619 if (Elt.getOpcode() == ISD::UNDEF) {
3620 Locs[i] = std::make_pair(-1, -1);
3621 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3622 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3623 (*MaskPtr)[LoIdx] = Elt;
3626 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3627 (*MaskPtr)[HiIdx] = Elt;
3632 SDOperand LoShuffle =
3633 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3634 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3635 &LoMask[0], LoMask.size()));
3636 SDOperand HiShuffle =
3637 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3638 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3639 &HiMask[0], HiMask.size()));
3640 SmallVector<SDOperand, 8> MaskOps;
3641 for (unsigned i = 0; i != NumElems; ++i) {
3642 if (Locs[i].first == -1) {
3643 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3645 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3646 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3649 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3650 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3651 &MaskOps[0], MaskOps.size()));
3658 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3659 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3662 MVT::ValueType VT = Op.getValueType();
3663 // TODO: handle v16i8.
3664 if (MVT::getSizeInBits(VT) == 16) {
3665 SDOperand Vec = Op.getOperand(0);
3666 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3668 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3669 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3670 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3672 // Transform it so it match pextrw which produces a 32-bit result.
3673 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3674 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3675 Op.getOperand(0), Op.getOperand(1));
3676 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3677 DAG.getValueType(VT));
3678 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3679 } else if (MVT::getSizeInBits(VT) == 32) {
3680 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3683 // SHUFPS the element to the lowest double word, then movss.
3684 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3685 SmallVector<SDOperand, 8> IdxVec;
3687 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3689 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3691 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3693 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3694 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3695 &IdxVec[0], IdxVec.size());
3696 SDOperand Vec = Op.getOperand(0);
3697 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3698 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3699 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3700 DAG.getIntPtrConstant(0));
3701 } else if (MVT::getSizeInBits(VT) == 64) {
3702 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3706 // UNPCKHPD the element to the lowest double word, then movsd.
3707 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3708 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3709 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3710 SmallVector<SDOperand, 8> IdxVec;
3711 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3713 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3714 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3715 &IdxVec[0], IdxVec.size());
3716 SDOperand Vec = Op.getOperand(0);
3717 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3718 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3719 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3720 DAG.getIntPtrConstant(0));
3727 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3728 MVT::ValueType VT = Op.getValueType();
3729 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3733 SDOperand N0 = Op.getOperand(0);
3734 SDOperand N1 = Op.getOperand(1);
3735 SDOperand N2 = Op.getOperand(2);
3737 if (MVT::getSizeInBits(EVT) == 16) {
3738 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3739 // as its second argument.
3740 if (N1.getValueType() != MVT::i32)
3741 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3742 if (N2.getValueType() != MVT::i32)
3743 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3744 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3750 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3751 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3752 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3755 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3756 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3757 // one of the above mentioned nodes. It has to be wrapped because otherwise
3758 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3759 // be used to form addressing mode. These wrapped nodes will be selected
3762 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3763 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3764 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3766 CP->getAlignment());
3767 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3768 // With PIC, the address is actually $g + Offset.
3769 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3770 !Subtarget->isPICStyleRIPRel()) {
3771 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3772 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3780 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3781 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3782 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3783 // If it's a debug information descriptor, don't mess with it.
3784 if (DAG.isVerifiedDebugInfoDesc(Op))
3786 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3787 // With PIC, the address is actually $g + Offset.
3788 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3789 !Subtarget->isPICStyleRIPRel()) {
3790 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3791 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3795 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3796 // load the value at address GV, not the value of GV itself. This means that
3797 // the GlobalAddress must be in the base or index register of the address, not
3798 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3799 // The same applies for external symbols during PIC codegen
3800 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3801 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
3802 PseudoSourceValue::getGOT(), 0);
3807 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3809 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3810 const MVT::ValueType PtrVT) {
3812 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3813 DAG.getNode(X86ISD::GlobalBaseReg,
3815 InFlag = Chain.getValue(1);
3817 // emit leal symbol@TLSGD(,%ebx,1), %eax
3818 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3819 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3820 GA->getValueType(0),
3822 SDOperand Ops[] = { Chain, TGA, InFlag };
3823 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3824 InFlag = Result.getValue(2);
3825 Chain = Result.getValue(1);
3827 // call ___tls_get_addr. This function receives its argument in
3828 // the register EAX.
3829 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3830 InFlag = Chain.getValue(1);
3832 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3833 SDOperand Ops1[] = { Chain,
3834 DAG.getTargetExternalSymbol("___tls_get_addr",
3836 DAG.getRegister(X86::EAX, PtrVT),
3837 DAG.getRegister(X86::EBX, PtrVT),
3839 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3840 InFlag = Chain.getValue(1);
3842 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3845 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3846 // "local exec" model.
3848 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3849 const MVT::ValueType PtrVT) {
3850 // Get the Thread Pointer
3851 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3852 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3854 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3855 GA->getValueType(0),
3857 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3859 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3860 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
3861 PseudoSourceValue::getGOT(), 0);
3863 // The address of the thread local variable is the add of the thread
3864 // pointer with the offset of the variable.
3865 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3869 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3870 // TODO: implement the "local dynamic" model
3871 // TODO: implement the "initial exec"model for pic executables
3872 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3873 "TLS not implemented for non-ELF and 64-bit targets");
3874 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3875 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3876 // otherwise use the "Local Exec"TLS Model
3877 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3878 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3880 return LowerToTLSExecModel(GA, DAG, getPointerTy());
3884 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3885 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3886 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3887 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3888 // With PIC, the address is actually $g + Offset.
3889 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3890 !Subtarget->isPICStyleRIPRel()) {
3891 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3892 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3899 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3900 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3901 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3902 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3903 // With PIC, the address is actually $g + Offset.
3904 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3905 !Subtarget->isPICStyleRIPRel()) {
3906 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3907 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3914 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
3915 /// take a 2 x i32 value to shift plus a shift amount.
3916 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
3917 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
3918 "Not an i64 shift!");
3919 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
3920 SDOperand ShOpLo = Op.getOperand(0);
3921 SDOperand ShOpHi = Op.getOperand(1);
3922 SDOperand ShAmt = Op.getOperand(2);
3923 SDOperand Tmp1 = isSRA ?
3924 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
3925 DAG.getConstant(0, MVT::i32);
3927 SDOperand Tmp2, Tmp3;
3928 if (Op.getOpcode() == ISD::SHL_PARTS) {
3929 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
3930 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
3932 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
3933 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
3936 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3937 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
3938 DAG.getConstant(32, MVT::i8));
3939 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
3940 AndNode, DAG.getConstant(0, MVT::i8));
3943 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3944 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
3945 SmallVector<SDOperand, 4> Ops;
3946 if (Op.getOpcode() == ISD::SHL_PARTS) {
3947 Ops.push_back(Tmp2);
3948 Ops.push_back(Tmp3);
3950 Ops.push_back(Cond);
3951 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3954 Ops.push_back(Tmp3);
3955 Ops.push_back(Tmp1);
3957 Ops.push_back(Cond);
3958 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3960 Ops.push_back(Tmp2);
3961 Ops.push_back(Tmp3);
3963 Ops.push_back(Cond);
3964 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3967 Ops.push_back(Tmp3);
3968 Ops.push_back(Tmp1);
3970 Ops.push_back(Cond);
3971 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3974 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
3978 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
3981 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
3982 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
3983 Op.getOperand(0).getValueType() >= MVT::i16 &&
3984 "Unknown SINT_TO_FP to lower!");
3987 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
3988 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
3989 MachineFunction &MF = DAG.getMachineFunction();
3990 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
3991 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3992 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
3994 PseudoSourceValue::getFixedStack(),
3997 // These are really Legal; caller falls through into that case.
3998 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4000 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4001 Subtarget->is64Bit())
4006 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4008 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4010 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4011 SmallVector<SDOperand, 8> Ops;
4012 Ops.push_back(Chain);
4013 Ops.push_back(StackSlot);
4014 Ops.push_back(DAG.getValueType(SrcVT));
4015 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
4016 Tys, &Ops[0], Ops.size());
4019 Chain = Result.getValue(1);
4020 SDOperand InFlag = Result.getValue(2);
4022 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4023 // shouldn't be necessary except that RFP cannot be live across
4024 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4025 MachineFunction &MF = DAG.getMachineFunction();
4026 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4027 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4028 Tys = DAG.getVTList(MVT::Other);
4029 SmallVector<SDOperand, 8> Ops;
4030 Ops.push_back(Chain);
4031 Ops.push_back(Result);
4032 Ops.push_back(StackSlot);
4033 Ops.push_back(DAG.getValueType(Op.getValueType()));
4034 Ops.push_back(InFlag);
4035 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4036 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4037 PseudoSourceValue::getFixedStack(), SSFI);
4043 std::pair<SDOperand,SDOperand> X86TargetLowering::
4044 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4045 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4046 "Unknown FP_TO_SINT to lower!");
4048 // These are really Legal.
4049 if (Op.getValueType() == MVT::i32 &&
4050 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4051 return std::make_pair(SDOperand(), SDOperand());
4052 if (Subtarget->is64Bit() &&
4053 Op.getValueType() == MVT::i64 &&
4054 Op.getOperand(0).getValueType() != MVT::f80)
4055 return std::make_pair(SDOperand(), SDOperand());
4057 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4059 MachineFunction &MF = DAG.getMachineFunction();
4060 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4061 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4062 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4064 switch (Op.getValueType()) {
4065 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4066 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4067 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4068 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4071 SDOperand Chain = DAG.getEntryNode();
4072 SDOperand Value = Op.getOperand(0);
4073 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4074 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4075 Chain = DAG.getStore(Chain, Value, StackSlot,
4076 PseudoSourceValue::getFixedStack(), SSFI);
4077 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4079 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4081 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4082 Chain = Value.getValue(1);
4083 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4084 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4087 // Build the FP_TO_INT*_IN_MEM
4088 SDOperand Ops[] = { Chain, Value, StackSlot };
4089 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4091 return std::make_pair(FIST, StackSlot);
4094 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4095 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4096 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4097 if (FIST.Val == 0) return SDOperand();
4100 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4103 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4104 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4105 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4106 if (FIST.Val == 0) return 0;
4108 // Return an i64 load from the stack slot.
4109 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4111 // Use a MERGE_VALUES node to drop the chain result value.
4112 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4115 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4116 MVT::ValueType VT = Op.getValueType();
4117 MVT::ValueType EltVT = VT;
4118 if (MVT::isVector(VT))
4119 EltVT = MVT::getVectorElementType(VT);
4120 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4121 std::vector<Constant*> CV;
4122 if (EltVT == MVT::f64) {
4123 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4127 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4133 Constant *C = ConstantVector::get(CV);
4134 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4135 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4136 PseudoSourceValue::getConstantPool(), 0,
4138 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4141 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4142 MVT::ValueType VT = Op.getValueType();
4143 MVT::ValueType EltVT = VT;
4144 unsigned EltNum = 1;
4145 if (MVT::isVector(VT)) {
4146 EltVT = MVT::getVectorElementType(VT);
4147 EltNum = MVT::getVectorNumElements(VT);
4149 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4150 std::vector<Constant*> CV;
4151 if (EltVT == MVT::f64) {
4152 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4156 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4162 Constant *C = ConstantVector::get(CV);
4163 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4164 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4165 PseudoSourceValue::getConstantPool(), 0,
4167 if (MVT::isVector(VT)) {
4168 return DAG.getNode(ISD::BIT_CONVERT, VT,
4169 DAG.getNode(ISD::XOR, MVT::v2i64,
4170 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4171 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4173 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4177 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4178 SDOperand Op0 = Op.getOperand(0);
4179 SDOperand Op1 = Op.getOperand(1);
4180 MVT::ValueType VT = Op.getValueType();
4181 MVT::ValueType SrcVT = Op1.getValueType();
4182 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4184 // If second operand is smaller, extend it first.
4185 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4186 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4188 SrcTy = MVT::getTypeForValueType(SrcVT);
4190 // And if it is bigger, shrink it first.
4191 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4192 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4194 SrcTy = MVT::getTypeForValueType(SrcVT);
4197 // At this point the operands and the result should have the same
4198 // type, and that won't be f80 since that is not custom lowered.
4200 // First get the sign bit of second operand.
4201 std::vector<Constant*> CV;
4202 if (SrcVT == MVT::f64) {
4203 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4204 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4206 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4207 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4208 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4209 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4211 Constant *C = ConstantVector::get(CV);
4212 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4213 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4214 PseudoSourceValue::getConstantPool(), 0,
4216 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4218 // Shift sign bit right or left if the two operands have different types.
4219 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4220 // Op0 is MVT::f32, Op1 is MVT::f64.
4221 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4222 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4223 DAG.getConstant(32, MVT::i32));
4224 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4225 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4226 DAG.getIntPtrConstant(0));
4229 // Clear first operand sign bit.
4231 if (VT == MVT::f64) {
4232 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4233 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4235 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4236 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4237 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4238 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4240 C = ConstantVector::get(CV);
4241 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4242 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4243 PseudoSourceValue::getConstantPool(), 0,
4245 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4247 // Or the value with the sign bit.
4248 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4251 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4252 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4254 SDOperand Op0 = Op.getOperand(0);
4255 SDOperand Op1 = Op.getOperand(1);
4256 SDOperand CC = Op.getOperand(2);
4257 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4258 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4261 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4263 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4264 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4265 DAG.getConstant(X86CC, MVT::i8), Cond);
4268 assert(isFP && "Illegal integer SetCC!");
4270 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4271 switch (SetCCOpcode) {
4272 default: assert(false && "Illegal floating point SetCC!");
4273 case ISD::SETOEQ: { // !PF & ZF
4274 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4275 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4276 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4277 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4278 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4280 case ISD::SETUNE: { // PF | !ZF
4281 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4282 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4283 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4284 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4285 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4291 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4292 bool addTest = true;
4293 SDOperand Cond = Op.getOperand(0);
4296 if (Cond.getOpcode() == ISD::SETCC)
4297 Cond = LowerSETCC(Cond, DAG);
4299 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4300 // setting operand in place of the X86ISD::SETCC.
4301 if (Cond.getOpcode() == X86ISD::SETCC) {
4302 CC = Cond.getOperand(0);
4304 SDOperand Cmp = Cond.getOperand(1);
4305 unsigned Opc = Cmp.getOpcode();
4306 MVT::ValueType VT = Op.getValueType();
4308 bool IllegalFPCMov = false;
4309 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4310 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4311 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4313 if ((Opc == X86ISD::CMP ||
4314 Opc == X86ISD::COMI ||
4315 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4322 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4323 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4326 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4328 SmallVector<SDOperand, 4> Ops;
4329 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4330 // condition is true.
4331 Ops.push_back(Op.getOperand(2));
4332 Ops.push_back(Op.getOperand(1));
4334 Ops.push_back(Cond);
4335 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4338 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4339 bool addTest = true;
4340 SDOperand Chain = Op.getOperand(0);
4341 SDOperand Cond = Op.getOperand(1);
4342 SDOperand Dest = Op.getOperand(2);
4345 if (Cond.getOpcode() == ISD::SETCC)
4346 Cond = LowerSETCC(Cond, DAG);
4348 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4349 // setting operand in place of the X86ISD::SETCC.
4350 if (Cond.getOpcode() == X86ISD::SETCC) {
4351 CC = Cond.getOperand(0);
4353 SDOperand Cmp = Cond.getOperand(1);
4354 unsigned Opc = Cmp.getOpcode();
4355 if (Opc == X86ISD::CMP ||
4356 Opc == X86ISD::COMI ||
4357 Opc == X86ISD::UCOMI) {
4364 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4365 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4367 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4368 Chain, Op.getOperand(2), CC, Cond);
4372 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4373 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4374 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4375 // that the guard pages used by the OS virtual memory manager are allocated in
4376 // correct sequence.
4378 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4379 SelectionDAG &DAG) {
4380 assert(Subtarget->isTargetCygMing() &&
4381 "This should be used only on Cygwin/Mingw targets");
4384 SDOperand Chain = Op.getOperand(0);
4385 SDOperand Size = Op.getOperand(1);
4386 // FIXME: Ensure alignment here
4390 MVT::ValueType IntPtr = getPointerTy();
4391 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4393 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4394 Flag = Chain.getValue(1);
4396 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4397 SDOperand Ops[] = { Chain,
4398 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4399 DAG.getRegister(X86::EAX, IntPtr),
4401 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4402 Flag = Chain.getValue(1);
4404 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4406 std::vector<MVT::ValueType> Tys;
4407 Tys.push_back(SPTy);
4408 Tys.push_back(MVT::Other);
4409 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4410 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4413 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4414 SDOperand InFlag(0, 0);
4415 SDOperand Chain = Op.getOperand(0);
4417 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4418 if (Align == 0) Align = 1;
4420 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4421 // If not DWORD aligned or size is more than the threshold, call memset.
4422 // The libc version is likely to be faster for these cases. It can use the
4423 // address value and run time information about the CPU.
4424 if ((Align & 3) != 0 ||
4425 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4426 MVT::ValueType IntPtr = getPointerTy();
4427 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4428 TargetLowering::ArgListTy Args;
4429 TargetLowering::ArgListEntry Entry;
4430 Entry.Node = Op.getOperand(1);
4431 Entry.Ty = IntPtrTy;
4432 Args.push_back(Entry);
4433 // Extend the unsigned i8 argument to be an int value for the call.
4434 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4435 Entry.Ty = IntPtrTy;
4436 Args.push_back(Entry);
4437 Entry.Node = Op.getOperand(3);
4438 Args.push_back(Entry);
4439 std::pair<SDOperand,SDOperand> CallResult =
4440 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4441 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4442 return CallResult.second;
4447 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4448 unsigned BytesLeft = 0;
4449 bool TwoRepStos = false;
4452 uint64_t Val = ValC->getValue() & 255;
4454 // If the value is a constant, then we can potentially use larger sets.
4455 switch (Align & 3) {
4456 case 2: // WORD aligned
4459 Val = (Val << 8) | Val;
4461 case 0: // DWORD aligned
4464 Val = (Val << 8) | Val;
4465 Val = (Val << 16) | Val;
4466 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4469 Val = (Val << 32) | Val;
4472 default: // Byte aligned
4475 Count = Op.getOperand(3);
4479 if (AVT > MVT::i8) {
4481 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4482 Count = DAG.getIntPtrConstant(I->getValue() / UBytes);
4483 BytesLeft = I->getValue() % UBytes;
4485 assert(AVT >= MVT::i32 &&
4486 "Do not use rep;stos if not at least DWORD aligned");
4487 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4488 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4493 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4495 InFlag = Chain.getValue(1);
4498 Count = Op.getOperand(3);
4499 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4500 InFlag = Chain.getValue(1);
4503 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4505 InFlag = Chain.getValue(1);
4506 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4507 Op.getOperand(1), InFlag);
4508 InFlag = Chain.getValue(1);
4510 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4511 SmallVector<SDOperand, 8> Ops;
4512 Ops.push_back(Chain);
4513 Ops.push_back(DAG.getValueType(AVT));
4514 Ops.push_back(InFlag);
4515 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4518 InFlag = Chain.getValue(1);
4519 Count = Op.getOperand(3);
4520 MVT::ValueType CVT = Count.getValueType();
4521 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4522 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4523 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4525 InFlag = Chain.getValue(1);
4526 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4528 Ops.push_back(Chain);
4529 Ops.push_back(DAG.getValueType(MVT::i8));
4530 Ops.push_back(InFlag);
4531 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4532 } else if (BytesLeft) {
4533 // Issue stores for the last 1 - 7 bytes.
4535 unsigned Val = ValC->getValue() & 255;
4536 unsigned Offset = I->getValue() - BytesLeft;
4537 SDOperand DstAddr = Op.getOperand(1);
4538 MVT::ValueType AddrVT = DstAddr.getValueType();
4539 if (BytesLeft >= 4) {
4540 Val = (Val << 8) | Val;
4541 Val = (Val << 16) | Val;
4542 Value = DAG.getConstant(Val, MVT::i32);
4543 Chain = DAG.getStore(Chain, Value,
4544 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4545 DAG.getConstant(Offset, AddrVT)),
4550 if (BytesLeft >= 2) {
4551 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4552 Chain = DAG.getStore(Chain, Value,
4553 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4554 DAG.getConstant(Offset, AddrVT)),
4559 if (BytesLeft == 1) {
4560 Value = DAG.getConstant(Val, MVT::i8);
4561 Chain = DAG.getStore(Chain, Value,
4562 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4563 DAG.getConstant(Offset, AddrVT)),
4571 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4576 SelectionDAG &DAG) {
4578 unsigned BytesLeft = 0;
4579 switch (Align & 3) {
4580 case 2: // WORD aligned
4583 case 0: // DWORD aligned
4585 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4588 default: // Byte aligned
4593 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4594 SDOperand Count = DAG.getIntPtrConstant(Size / UBytes);
4595 BytesLeft = Size % UBytes;
4597 SDOperand InFlag(0, 0);
4598 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4600 InFlag = Chain.getValue(1);
4601 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4603 InFlag = Chain.getValue(1);
4604 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4606 InFlag = Chain.getValue(1);
4608 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4609 SmallVector<SDOperand, 8> Ops;
4610 Ops.push_back(Chain);
4611 Ops.push_back(DAG.getValueType(AVT));
4612 Ops.push_back(InFlag);
4613 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4616 // Issue loads and stores for the last 1 - 7 bytes.
4617 unsigned Offset = Size - BytesLeft;
4618 SDOperand DstAddr = Dest;
4619 MVT::ValueType DstVT = DstAddr.getValueType();
4620 SDOperand SrcAddr = Source;
4621 MVT::ValueType SrcVT = SrcAddr.getValueType();
4623 if (BytesLeft >= 4) {
4624 Value = DAG.getLoad(MVT::i32, Chain,
4625 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4626 DAG.getConstant(Offset, SrcVT)),
4628 Chain = Value.getValue(1);
4629 Chain = DAG.getStore(Chain, Value,
4630 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4631 DAG.getConstant(Offset, DstVT)),
4636 if (BytesLeft >= 2) {
4637 Value = DAG.getLoad(MVT::i16, Chain,
4638 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4639 DAG.getConstant(Offset, SrcVT)),
4641 Chain = Value.getValue(1);
4642 Chain = DAG.getStore(Chain, Value,
4643 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4644 DAG.getConstant(Offset, DstVT)),
4650 if (BytesLeft == 1) {
4651 Value = DAG.getLoad(MVT::i8, Chain,
4652 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4653 DAG.getConstant(Offset, SrcVT)),
4655 Chain = Value.getValue(1);
4656 Chain = DAG.getStore(Chain, Value,
4657 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4658 DAG.getConstant(Offset, DstVT)),
4666 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4667 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4668 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4669 SDOperand TheChain = N->getOperand(0);
4670 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4671 if (Subtarget->is64Bit()) {
4672 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4673 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4674 MVT::i64, rax.getValue(2));
4675 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4676 DAG.getConstant(32, MVT::i8));
4678 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4681 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4682 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4685 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4686 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4687 MVT::i32, eax.getValue(2));
4688 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4689 SDOperand Ops[] = { eax, edx };
4690 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4692 // Use a MERGE_VALUES to return the value and chain.
4693 Ops[1] = edx.getValue(1);
4694 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4695 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4698 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4699 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4701 if (!Subtarget->is64Bit()) {
4702 // vastart just stores the address of the VarArgsFrameIndex slot into the
4703 // memory location argument.
4704 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4705 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4709 // gp_offset (0 - 6 * 8)
4710 // fp_offset (48 - 48 + 8 * 16)
4711 // overflow_arg_area (point to parameters coming in memory).
4713 SmallVector<SDOperand, 8> MemOps;
4714 SDOperand FIN = Op.getOperand(1);
4716 SDOperand Store = DAG.getStore(Op.getOperand(0),
4717 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4719 MemOps.push_back(Store);
4722 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4723 Store = DAG.getStore(Op.getOperand(0),
4724 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4726 MemOps.push_back(Store);
4728 // Store ptr to overflow_arg_area
4729 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4730 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4731 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4732 MemOps.push_back(Store);
4734 // Store ptr to reg_save_area.
4735 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4736 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4737 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4738 MemOps.push_back(Store);
4739 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4742 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4743 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4744 SDOperand Chain = Op.getOperand(0);
4745 SDOperand DstPtr = Op.getOperand(1);
4746 SDOperand SrcPtr = Op.getOperand(2);
4747 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4748 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4750 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr, SrcSV, 0);
4751 Chain = SrcPtr.getValue(1);
4752 for (unsigned i = 0; i < 3; ++i) {
4753 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr, SrcSV, 0);
4754 Chain = Val.getValue(1);
4755 Chain = DAG.getStore(Chain, Val, DstPtr, DstSV, 0);
4758 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
4759 DAG.getIntPtrConstant(8));
4760 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
4761 DAG.getIntPtrConstant(8));
4767 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4768 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4770 default: return SDOperand(); // Don't custom lower most intrinsics.
4771 // Comparison intrinsics.
4772 case Intrinsic::x86_sse_comieq_ss:
4773 case Intrinsic::x86_sse_comilt_ss:
4774 case Intrinsic::x86_sse_comile_ss:
4775 case Intrinsic::x86_sse_comigt_ss:
4776 case Intrinsic::x86_sse_comige_ss:
4777 case Intrinsic::x86_sse_comineq_ss:
4778 case Intrinsic::x86_sse_ucomieq_ss:
4779 case Intrinsic::x86_sse_ucomilt_ss:
4780 case Intrinsic::x86_sse_ucomile_ss:
4781 case Intrinsic::x86_sse_ucomigt_ss:
4782 case Intrinsic::x86_sse_ucomige_ss:
4783 case Intrinsic::x86_sse_ucomineq_ss:
4784 case Intrinsic::x86_sse2_comieq_sd:
4785 case Intrinsic::x86_sse2_comilt_sd:
4786 case Intrinsic::x86_sse2_comile_sd:
4787 case Intrinsic::x86_sse2_comigt_sd:
4788 case Intrinsic::x86_sse2_comige_sd:
4789 case Intrinsic::x86_sse2_comineq_sd:
4790 case Intrinsic::x86_sse2_ucomieq_sd:
4791 case Intrinsic::x86_sse2_ucomilt_sd:
4792 case Intrinsic::x86_sse2_ucomile_sd:
4793 case Intrinsic::x86_sse2_ucomigt_sd:
4794 case Intrinsic::x86_sse2_ucomige_sd:
4795 case Intrinsic::x86_sse2_ucomineq_sd: {
4797 ISD::CondCode CC = ISD::SETCC_INVALID;
4800 case Intrinsic::x86_sse_comieq_ss:
4801 case Intrinsic::x86_sse2_comieq_sd:
4805 case Intrinsic::x86_sse_comilt_ss:
4806 case Intrinsic::x86_sse2_comilt_sd:
4810 case Intrinsic::x86_sse_comile_ss:
4811 case Intrinsic::x86_sse2_comile_sd:
4815 case Intrinsic::x86_sse_comigt_ss:
4816 case Intrinsic::x86_sse2_comigt_sd:
4820 case Intrinsic::x86_sse_comige_ss:
4821 case Intrinsic::x86_sse2_comige_sd:
4825 case Intrinsic::x86_sse_comineq_ss:
4826 case Intrinsic::x86_sse2_comineq_sd:
4830 case Intrinsic::x86_sse_ucomieq_ss:
4831 case Intrinsic::x86_sse2_ucomieq_sd:
4832 Opc = X86ISD::UCOMI;
4835 case Intrinsic::x86_sse_ucomilt_ss:
4836 case Intrinsic::x86_sse2_ucomilt_sd:
4837 Opc = X86ISD::UCOMI;
4840 case Intrinsic::x86_sse_ucomile_ss:
4841 case Intrinsic::x86_sse2_ucomile_sd:
4842 Opc = X86ISD::UCOMI;
4845 case Intrinsic::x86_sse_ucomigt_ss:
4846 case Intrinsic::x86_sse2_ucomigt_sd:
4847 Opc = X86ISD::UCOMI;
4850 case Intrinsic::x86_sse_ucomige_ss:
4851 case Intrinsic::x86_sse2_ucomige_sd:
4852 Opc = X86ISD::UCOMI;
4855 case Intrinsic::x86_sse_ucomineq_ss:
4856 case Intrinsic::x86_sse2_ucomineq_sd:
4857 Opc = X86ISD::UCOMI;
4863 SDOperand LHS = Op.getOperand(1);
4864 SDOperand RHS = Op.getOperand(2);
4865 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4867 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
4868 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
4869 DAG.getConstant(X86CC, MVT::i8), Cond);
4870 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
4875 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4876 // Depths > 0 not supported yet!
4877 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4880 // Just load the return address
4881 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4882 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4885 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4886 // Depths > 0 not supported yet!
4887 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4890 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4891 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
4892 DAG.getIntPtrConstant(4));
4895 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
4896 SelectionDAG &DAG) {
4897 // Is not yet supported on x86-64
4898 if (Subtarget->is64Bit())
4901 return DAG.getIntPtrConstant(8);
4904 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
4906 assert(!Subtarget->is64Bit() &&
4907 "Lowering of eh_return builtin is not supported yet on x86-64");
4909 MachineFunction &MF = DAG.getMachineFunction();
4910 SDOperand Chain = Op.getOperand(0);
4911 SDOperand Offset = Op.getOperand(1);
4912 SDOperand Handler = Op.getOperand(2);
4914 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
4917 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
4918 DAG.getIntPtrConstant(-4UL));
4919 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
4920 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
4921 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
4922 MF.getRegInfo().addLiveOut(X86::ECX);
4924 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
4925 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
4928 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
4929 SelectionDAG &DAG) {
4930 SDOperand Root = Op.getOperand(0);
4931 SDOperand Trmp = Op.getOperand(1); // trampoline
4932 SDOperand FPtr = Op.getOperand(2); // nested function
4933 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
4935 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4937 const X86InstrInfo *TII =
4938 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
4940 if (Subtarget->is64Bit()) {
4941 SDOperand OutChains[6];
4943 // Large code-model.
4945 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
4946 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
4948 const unsigned char N86R10 =
4949 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
4950 const unsigned char N86R11 =
4951 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
4953 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
4955 // Load the pointer to the nested function into R11.
4956 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
4957 SDOperand Addr = Trmp;
4958 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
4961 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
4962 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
4964 // Load the 'nest' parameter value into R10.
4965 // R10 is specified in X86CallingConv.td
4966 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
4967 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
4968 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
4971 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
4972 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
4974 // Jump to the nested function.
4975 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
4976 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
4977 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
4980 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
4981 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
4982 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
4986 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
4987 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
4989 const Function *Func =
4990 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
4991 unsigned CC = Func->getCallingConv();
4996 assert(0 && "Unsupported calling convention");
4997 case CallingConv::C:
4998 case CallingConv::X86_StdCall: {
4999 // Pass 'nest' parameter in ECX.
5000 // Must be kept in sync with X86CallingConv.td
5003 // Check that ECX wasn't needed by an 'inreg' parameter.
5004 const FunctionType *FTy = Func->getFunctionType();
5005 const ParamAttrsList *Attrs = Func->getParamAttrs();
5007 if (Attrs && !Func->isVarArg()) {
5008 unsigned InRegCount = 0;
5011 for (FunctionType::param_iterator I = FTy->param_begin(),
5012 E = FTy->param_end(); I != E; ++I, ++Idx)
5013 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5014 // FIXME: should only count parameters that are lowered to integers.
5015 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5017 if (InRegCount > 2) {
5018 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5024 case CallingConv::X86_FastCall:
5025 // Pass 'nest' parameter in EAX.
5026 // Must be kept in sync with X86CallingConv.td
5031 SDOperand OutChains[4];
5032 SDOperand Addr, Disp;
5034 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5035 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5037 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5038 const unsigned char N86Reg =
5039 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5040 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5043 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5044 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5046 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5047 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5048 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5049 TrmpAddr, 5, false, 1);
5051 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5052 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5055 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5056 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5060 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5062 The rounding mode is in bits 11:10 of FPSR, and has the following
5069 FLT_ROUNDS, on the other hand, expects the following:
5076 To perform the conversion, we do:
5077 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5080 MachineFunction &MF = DAG.getMachineFunction();
5081 const TargetMachine &TM = MF.getTarget();
5082 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5083 unsigned StackAlignment = TFI.getStackAlignment();
5084 MVT::ValueType VT = Op.getValueType();
5086 // Save FP Control Word to stack slot
5087 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5088 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5090 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5091 DAG.getEntryNode(), StackSlot);
5093 // Load FP Control Word from stack slot
5094 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5096 // Transform as necessary
5098 DAG.getNode(ISD::SRL, MVT::i16,
5099 DAG.getNode(ISD::AND, MVT::i16,
5100 CWD, DAG.getConstant(0x800, MVT::i16)),
5101 DAG.getConstant(11, MVT::i8));
5103 DAG.getNode(ISD::SRL, MVT::i16,
5104 DAG.getNode(ISD::AND, MVT::i16,
5105 CWD, DAG.getConstant(0x400, MVT::i16)),
5106 DAG.getConstant(9, MVT::i8));
5109 DAG.getNode(ISD::AND, MVT::i16,
5110 DAG.getNode(ISD::ADD, MVT::i16,
5111 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5112 DAG.getConstant(1, MVT::i16)),
5113 DAG.getConstant(3, MVT::i16));
5116 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5117 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5120 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5121 MVT::ValueType VT = Op.getValueType();
5122 MVT::ValueType OpVT = VT;
5123 unsigned NumBits = MVT::getSizeInBits(VT);
5125 Op = Op.getOperand(0);
5126 if (VT == MVT::i8) {
5127 // Zero extend to i32 since there is not an i8 bsr.
5129 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5132 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5133 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5134 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5136 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5137 SmallVector<SDOperand, 4> Ops;
5139 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5140 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5141 Ops.push_back(Op.getValue(1));
5142 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5144 // Finally xor with NumBits-1.
5145 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5148 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5152 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5153 MVT::ValueType VT = Op.getValueType();
5154 MVT::ValueType OpVT = VT;
5155 unsigned NumBits = MVT::getSizeInBits(VT);
5157 Op = Op.getOperand(0);
5158 if (VT == MVT::i8) {
5160 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5163 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5164 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5165 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5167 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5168 SmallVector<SDOperand, 4> Ops;
5170 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5171 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5172 Ops.push_back(Op.getValue(1));
5173 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5176 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5180 /// LowerOperation - Provide custom lowering hooks for some operations.
5182 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5183 switch (Op.getOpcode()) {
5184 default: assert(0 && "Should not custom lower this!");
5185 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5186 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5187 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5188 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5189 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5190 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5191 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5192 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5193 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5194 case ISD::SHL_PARTS:
5195 case ISD::SRA_PARTS:
5196 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5197 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5198 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5199 case ISD::FABS: return LowerFABS(Op, DAG);
5200 case ISD::FNEG: return LowerFNEG(Op, DAG);
5201 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5202 case ISD::SETCC: return LowerSETCC(Op, DAG);
5203 case ISD::SELECT: return LowerSELECT(Op, DAG);
5204 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5205 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5206 case ISD::CALL: return LowerCALL(Op, DAG);
5207 case ISD::RET: return LowerRET(Op, DAG);
5208 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5209 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5210 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
5211 case ISD::VASTART: return LowerVASTART(Op, DAG);
5212 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5213 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5214 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5215 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5216 case ISD::FRAME_TO_ARGS_OFFSET:
5217 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5218 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5219 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5220 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5221 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5222 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5223 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5225 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5226 case ISD::READCYCLECOUNTER:
5227 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5231 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5232 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5233 switch (N->getOpcode()) {
5234 default: assert(0 && "Should not custom lower this!");
5235 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5236 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5240 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5242 default: return NULL;
5243 case X86ISD::BSF: return "X86ISD::BSF";
5244 case X86ISD::BSR: return "X86ISD::BSR";
5245 case X86ISD::SHLD: return "X86ISD::SHLD";
5246 case X86ISD::SHRD: return "X86ISD::SHRD";
5247 case X86ISD::FAND: return "X86ISD::FAND";
5248 case X86ISD::FOR: return "X86ISD::FOR";
5249 case X86ISD::FXOR: return "X86ISD::FXOR";
5250 case X86ISD::FSRL: return "X86ISD::FSRL";
5251 case X86ISD::FILD: return "X86ISD::FILD";
5252 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5253 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5254 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5255 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5256 case X86ISD::FLD: return "X86ISD::FLD";
5257 case X86ISD::FST: return "X86ISD::FST";
5258 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5259 case X86ISD::FP_GET_RESULT2: return "X86ISD::FP_GET_RESULT2";
5260 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5261 case X86ISD::CALL: return "X86ISD::CALL";
5262 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5263 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5264 case X86ISD::CMP: return "X86ISD::CMP";
5265 case X86ISD::COMI: return "X86ISD::COMI";
5266 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5267 case X86ISD::SETCC: return "X86ISD::SETCC";
5268 case X86ISD::CMOV: return "X86ISD::CMOV";
5269 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5270 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5271 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5272 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5273 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5274 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5275 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5276 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5277 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5278 case X86ISD::FMAX: return "X86ISD::FMAX";
5279 case X86ISD::FMIN: return "X86ISD::FMIN";
5280 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5281 case X86ISD::FRCP: return "X86ISD::FRCP";
5282 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5283 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5284 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5285 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5286 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5290 // isLegalAddressingMode - Return true if the addressing mode represented
5291 // by AM is legal for this target, for a load/store of the specified type.
5292 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5293 const Type *Ty) const {
5294 // X86 supports extremely general addressing modes.
5296 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5297 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5301 // We can only fold this if we don't need an extra load.
5302 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5305 // X86-64 only supports addr of globals in small code model.
5306 if (Subtarget->is64Bit()) {
5307 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5309 // If lower 4G is not available, then we must use rip-relative addressing.
5310 if (AM.BaseOffs || AM.Scale > 1)
5321 // These scales always work.
5326 // These scales are formed with basereg+scalereg. Only accept if there is
5331 default: // Other stuff never works.
5339 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5340 if (!Ty1->isInteger() || !Ty2->isInteger())
5342 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5343 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5344 if (NumBits1 <= NumBits2)
5346 return Subtarget->is64Bit() || NumBits1 < 64;
5349 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5350 MVT::ValueType VT2) const {
5351 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5353 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5354 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5355 if (NumBits1 <= NumBits2)
5357 return Subtarget->is64Bit() || NumBits1 < 64;
5360 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5361 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5362 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5363 /// are assumed to be legal.
5365 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5366 // Only do shuffles on 128-bit vector types for now.
5367 if (MVT::getSizeInBits(VT) == 64) return false;
5368 return (Mask.Val->getNumOperands() <= 4 ||
5369 isIdentityMask(Mask.Val) ||
5370 isIdentityMask(Mask.Val, true) ||
5371 isSplatMask(Mask.Val) ||
5372 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5373 X86::isUNPCKLMask(Mask.Val) ||
5374 X86::isUNPCKHMask(Mask.Val) ||
5375 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5376 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5379 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5381 SelectionDAG &DAG) const {
5382 unsigned NumElts = BVOps.size();
5383 // Only do shuffles on 128-bit vector types for now.
5384 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5385 if (NumElts == 2) return true;
5387 return (isMOVLMask(&BVOps[0], 4) ||
5388 isCommutedMOVL(&BVOps[0], 4, true) ||
5389 isSHUFPMask(&BVOps[0], 4) ||
5390 isCommutedSHUFP(&BVOps[0], 4));
5395 //===----------------------------------------------------------------------===//
5396 // X86 Scheduler Hooks
5397 //===----------------------------------------------------------------------===//
5400 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5401 MachineBasicBlock *BB) {
5402 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5403 switch (MI->getOpcode()) {
5404 default: assert(false && "Unexpected instr type to insert");
5405 case X86::CMOV_FR32:
5406 case X86::CMOV_FR64:
5407 case X86::CMOV_V4F32:
5408 case X86::CMOV_V2F64:
5409 case X86::CMOV_V2I64: {
5410 // To "insert" a SELECT_CC instruction, we actually have to insert the
5411 // diamond control-flow pattern. The incoming instruction knows the
5412 // destination vreg to set, the condition code register to branch on, the
5413 // true/false values to select between, and a branch opcode to use.
5414 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5415 ilist<MachineBasicBlock>::iterator It = BB;
5421 // cmpTY ccX, r1, r2
5423 // fallthrough --> copy0MBB
5424 MachineBasicBlock *thisMBB = BB;
5425 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5426 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5428 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5429 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5430 MachineFunction *F = BB->getParent();
5431 F->getBasicBlockList().insert(It, copy0MBB);
5432 F->getBasicBlockList().insert(It, sinkMBB);
5433 // Update machine-CFG edges by first adding all successors of the current
5434 // block to the new block which will contain the Phi node for the select.
5435 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5436 e = BB->succ_end(); i != e; ++i)
5437 sinkMBB->addSuccessor(*i);
5438 // Next, remove all successors of the current block, and add the true
5439 // and fallthrough blocks as its successors.
5440 while(!BB->succ_empty())
5441 BB->removeSuccessor(BB->succ_begin());
5442 BB->addSuccessor(copy0MBB);
5443 BB->addSuccessor(sinkMBB);
5446 // %FalseValue = ...
5447 // # fallthrough to sinkMBB
5450 // Update machine-CFG edges
5451 BB->addSuccessor(sinkMBB);
5454 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5457 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5458 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5459 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5461 delete MI; // The pseudo instruction is gone now.
5465 case X86::FP32_TO_INT16_IN_MEM:
5466 case X86::FP32_TO_INT32_IN_MEM:
5467 case X86::FP32_TO_INT64_IN_MEM:
5468 case X86::FP64_TO_INT16_IN_MEM:
5469 case X86::FP64_TO_INT32_IN_MEM:
5470 case X86::FP64_TO_INT64_IN_MEM:
5471 case X86::FP80_TO_INT16_IN_MEM:
5472 case X86::FP80_TO_INT32_IN_MEM:
5473 case X86::FP80_TO_INT64_IN_MEM: {
5474 // Change the floating point control register to use "round towards zero"
5475 // mode when truncating to an integer value.
5476 MachineFunction *F = BB->getParent();
5477 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5478 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5480 // Load the old value of the high byte of the control word...
5482 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5483 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5485 // Set the high part to be round to zero...
5486 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5489 // Reload the modified control word now...
5490 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5492 // Restore the memory image of control word to original value
5493 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5496 // Get the X86 opcode to use.
5498 switch (MI->getOpcode()) {
5499 default: assert(0 && "illegal opcode!");
5500 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5501 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5502 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5503 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5504 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5505 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5506 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5507 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5508 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5512 MachineOperand &Op = MI->getOperand(0);
5513 if (Op.isRegister()) {
5514 AM.BaseType = X86AddressMode::RegBase;
5515 AM.Base.Reg = Op.getReg();
5517 AM.BaseType = X86AddressMode::FrameIndexBase;
5518 AM.Base.FrameIndex = Op.getIndex();
5520 Op = MI->getOperand(1);
5521 if (Op.isImmediate())
5522 AM.Scale = Op.getImm();
5523 Op = MI->getOperand(2);
5524 if (Op.isImmediate())
5525 AM.IndexReg = Op.getImm();
5526 Op = MI->getOperand(3);
5527 if (Op.isGlobalAddress()) {
5528 AM.GV = Op.getGlobal();
5530 AM.Disp = Op.getImm();
5532 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5533 .addReg(MI->getOperand(4).getReg());
5535 // Reload the original control word now.
5536 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5538 delete MI; // The pseudo instruction is gone now.
5544 //===----------------------------------------------------------------------===//
5545 // X86 Optimization Hooks
5546 //===----------------------------------------------------------------------===//
5548 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5550 uint64_t &KnownZero,
5552 const SelectionDAG &DAG,
5553 unsigned Depth) const {
5554 unsigned Opc = Op.getOpcode();
5555 assert((Opc >= ISD::BUILTIN_OP_END ||
5556 Opc == ISD::INTRINSIC_WO_CHAIN ||
5557 Opc == ISD::INTRINSIC_W_CHAIN ||
5558 Opc == ISD::INTRINSIC_VOID) &&
5559 "Should use MaskedValueIsZero if you don't know whether Op"
5560 " is a target node!");
5562 KnownZero = KnownOne = 0; // Don't know anything.
5566 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5571 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5572 /// element of the result of the vector shuffle.
5573 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5574 MVT::ValueType VT = N->getValueType(0);
5575 SDOperand PermMask = N->getOperand(2);
5576 unsigned NumElems = PermMask.getNumOperands();
5577 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5579 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5581 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5582 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5583 SDOperand Idx = PermMask.getOperand(i);
5584 if (Idx.getOpcode() == ISD::UNDEF)
5585 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5586 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5591 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5592 /// node is a GlobalAddress + an offset.
5593 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5594 unsigned Opc = N->getOpcode();
5595 if (Opc == X86ISD::Wrapper) {
5596 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5597 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5600 } else if (Opc == ISD::ADD) {
5601 SDOperand N1 = N->getOperand(0);
5602 SDOperand N2 = N->getOperand(1);
5603 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5604 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5606 Offset += V->getSignExtended();
5609 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5610 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5612 Offset += V->getSignExtended();
5620 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5622 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5623 MachineFrameInfo *MFI) {
5624 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5627 SDOperand Loc = N->getOperand(1);
5628 SDOperand BaseLoc = Base->getOperand(1);
5629 if (Loc.getOpcode() == ISD::FrameIndex) {
5630 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5632 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5633 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5634 int FS = MFI->getObjectSize(FI);
5635 int BFS = MFI->getObjectSize(BFI);
5636 if (FS != BFS || FS != Size) return false;
5637 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5639 GlobalValue *GV1 = NULL;
5640 GlobalValue *GV2 = NULL;
5641 int64_t Offset1 = 0;
5642 int64_t Offset2 = 0;
5643 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5644 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5645 if (isGA1 && isGA2 && GV1 == GV2)
5646 return Offset1 == (Offset2 + Dist*Size);
5652 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5653 const X86Subtarget *Subtarget) {
5656 if (isGAPlusOffset(Base, GV, Offset))
5657 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5658 // DAG combine handles the stack object case.
5663 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5664 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5665 /// if the load addresses are consecutive, non-overlapping, and in the right
5667 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5668 const X86Subtarget *Subtarget) {
5669 MachineFunction &MF = DAG.getMachineFunction();
5670 MachineFrameInfo *MFI = MF.getFrameInfo();
5671 MVT::ValueType VT = N->getValueType(0);
5672 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5673 SDOperand PermMask = N->getOperand(2);
5674 int NumElems = (int)PermMask.getNumOperands();
5675 SDNode *Base = NULL;
5676 for (int i = 0; i < NumElems; ++i) {
5677 SDOperand Idx = PermMask.getOperand(i);
5678 if (Idx.getOpcode() == ISD::UNDEF) {
5679 if (!Base) return SDOperand();
5682 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5683 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5687 else if (!isConsecutiveLoad(Arg.Val, Base,
5688 i, MVT::getSizeInBits(EVT)/8,MFI))
5693 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5694 LoadSDNode *LD = cast<LoadSDNode>(Base);
5696 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5697 LD->getSrcValueOffset(), LD->isVolatile());
5699 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5700 LD->getSrcValueOffset(), LD->isVolatile(),
5701 LD->getAlignment());
5705 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5706 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5707 const X86Subtarget *Subtarget) {
5708 SDOperand Cond = N->getOperand(0);
5710 // If we have SSE[12] support, try to form min/max nodes.
5711 if (Subtarget->hasSSE2() &&
5712 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5713 if (Cond.getOpcode() == ISD::SETCC) {
5714 // Get the LHS/RHS of the select.
5715 SDOperand LHS = N->getOperand(1);
5716 SDOperand RHS = N->getOperand(2);
5717 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5719 unsigned Opcode = 0;
5720 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5723 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5726 if (!UnsafeFPMath) break;
5728 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
5730 Opcode = X86ISD::FMIN;
5733 case ISD::SETOGT: // (X > Y) ? X : Y -> max
5736 if (!UnsafeFPMath) break;
5738 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
5740 Opcode = X86ISD::FMAX;
5743 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5746 case ISD::SETOGT: // (X > Y) ? Y : X -> min
5749 if (!UnsafeFPMath) break;
5751 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
5753 Opcode = X86ISD::FMIN;
5756 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
5759 if (!UnsafeFPMath) break;
5761 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
5763 Opcode = X86ISD::FMAX;
5769 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5777 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
5778 /// X86ISD::FXOR nodes.
5779 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
5780 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
5781 // F[X]OR(0.0, x) -> x
5782 // F[X]OR(x, 0.0) -> x
5783 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
5784 if (C->getValueAPF().isPosZero())
5785 return N->getOperand(1);
5786 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
5787 if (C->getValueAPF().isPosZero())
5788 return N->getOperand(0);
5792 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
5793 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
5794 // FAND(0.0, x) -> 0.0
5795 // FAND(x, 0.0) -> 0.0
5796 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
5797 if (C->getValueAPF().isPosZero())
5798 return N->getOperand(0);
5799 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
5800 if (C->getValueAPF().isPosZero())
5801 return N->getOperand(1);
5806 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5807 DAGCombinerInfo &DCI) const {
5808 SelectionDAG &DAG = DCI.DAG;
5809 switch (N->getOpcode()) {
5811 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
5812 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
5814 case X86ISD::FOR: return PerformFORCombine(N, DAG);
5815 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
5821 //===----------------------------------------------------------------------===//
5822 // X86 Inline Assembly Support
5823 //===----------------------------------------------------------------------===//
5825 /// getConstraintType - Given a constraint letter, return the type of
5826 /// constraint it is for this target.
5827 X86TargetLowering::ConstraintType
5828 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
5829 if (Constraint.size() == 1) {
5830 switch (Constraint[0]) {
5839 return C_RegisterClass;
5844 return TargetLowering::getConstraintType(Constraint);
5847 /// LowerXConstraint - try to replace an X constraint, which matches anything,
5848 /// with another that has more specific requirements based on the type of the
5849 /// corresponding operand.
5850 void X86TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT,
5851 std::string& s) const {
5852 if (MVT::isFloatingPoint(ConstraintVT)) {
5853 if (Subtarget->hasSSE2())
5855 else if (Subtarget->hasSSE1())
5860 return TargetLowering::lowerXConstraint(ConstraintVT, s);
5863 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5864 /// vector. If it is invalid, don't add anything to Ops.
5865 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
5867 std::vector<SDOperand>&Ops,
5868 SelectionDAG &DAG) {
5869 SDOperand Result(0, 0);
5871 switch (Constraint) {
5874 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5875 if (C->getValue() <= 31) {
5876 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5882 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5883 if (C->getValue() <= 255) {
5884 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5890 // Literal immediates are always ok.
5891 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
5892 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
5896 // If we are in non-pic codegen mode, we allow the address of a global (with
5897 // an optional displacement) to be used with 'i'.
5898 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
5901 // Match either (GA) or (GA+C)
5903 Offset = GA->getOffset();
5904 } else if (Op.getOpcode() == ISD::ADD) {
5905 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5906 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5908 Offset = GA->getOffset()+C->getValue();
5910 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5911 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5913 Offset = GA->getOffset()+C->getValue();
5920 // If addressing this global requires a load (e.g. in PIC mode), we can't
5922 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
5926 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5932 // Otherwise, not valid for this mode.
5938 Ops.push_back(Result);
5941 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5944 std::vector<unsigned> X86TargetLowering::
5945 getRegClassForInlineAsmConstraint(const std::string &Constraint,
5946 MVT::ValueType VT) const {
5947 if (Constraint.size() == 1) {
5948 // FIXME: not handling fp-stack yet!
5949 switch (Constraint[0]) { // GCC X86 Constraint Letters
5950 default: break; // Unknown constraint letter
5951 case 'A': // EAX/EDX
5952 if (VT == MVT::i32 || VT == MVT::i64)
5953 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
5955 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
5958 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
5959 else if (VT == MVT::i16)
5960 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
5961 else if (VT == MVT::i8)
5962 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
5963 else if (VT == MVT::i64)
5964 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
5969 return std::vector<unsigned>();
5972 std::pair<unsigned, const TargetRegisterClass*>
5973 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
5974 MVT::ValueType VT) const {
5975 // First, see if this is a constraint that directly corresponds to an LLVM
5977 if (Constraint.size() == 1) {
5978 // GCC Constraint Letters
5979 switch (Constraint[0]) {
5981 case 'r': // GENERAL_REGS
5982 case 'R': // LEGACY_REGS
5983 case 'l': // INDEX_REGS
5984 if (VT == MVT::i64 && Subtarget->is64Bit())
5985 return std::make_pair(0U, X86::GR64RegisterClass);
5987 return std::make_pair(0U, X86::GR32RegisterClass);
5988 else if (VT == MVT::i16)
5989 return std::make_pair(0U, X86::GR16RegisterClass);
5990 else if (VT == MVT::i8)
5991 return std::make_pair(0U, X86::GR8RegisterClass);
5993 case 'y': // MMX_REGS if MMX allowed.
5994 if (!Subtarget->hasMMX()) break;
5995 return std::make_pair(0U, X86::VR64RegisterClass);
5997 case 'Y': // SSE_REGS if SSE2 allowed
5998 if (!Subtarget->hasSSE2()) break;
6000 case 'x': // SSE_REGS if SSE1 allowed
6001 if (!Subtarget->hasSSE1()) break;
6005 // Scalar SSE types.
6008 return std::make_pair(0U, X86::FR32RegisterClass);
6011 return std::make_pair(0U, X86::FR64RegisterClass);
6019 return std::make_pair(0U, X86::VR128RegisterClass);
6025 // Use the default implementation in TargetLowering to convert the register
6026 // constraint into a member of a register class.
6027 std::pair<unsigned, const TargetRegisterClass*> Res;
6028 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6030 // Not found as a standard register?
6031 if (Res.second == 0) {
6032 // GCC calls "st(0)" just plain "st".
6033 if (StringsEqualNoCase("{st}", Constraint)) {
6034 Res.first = X86::ST0;
6035 Res.second = X86::RFP80RegisterClass;
6041 // Otherwise, check to see if this is a register class of the wrong value
6042 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6043 // turn into {ax},{dx}.
6044 if (Res.second->hasType(VT))
6045 return Res; // Correct type already, nothing to do.
6047 // All of the single-register GCC register classes map their values onto
6048 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6049 // really want an 8-bit or 32-bit register, map to the appropriate register
6050 // class and return the appropriate register.
6051 if (Res.second != X86::GR16RegisterClass)
6054 if (VT == MVT::i8) {
6055 unsigned DestReg = 0;
6056 switch (Res.first) {
6058 case X86::AX: DestReg = X86::AL; break;
6059 case X86::DX: DestReg = X86::DL; break;
6060 case X86::CX: DestReg = X86::CL; break;
6061 case X86::BX: DestReg = X86::BL; break;
6064 Res.first = DestReg;
6065 Res.second = Res.second = X86::GR8RegisterClass;
6067 } else if (VT == MVT::i32) {
6068 unsigned DestReg = 0;
6069 switch (Res.first) {
6071 case X86::AX: DestReg = X86::EAX; break;
6072 case X86::DX: DestReg = X86::EDX; break;
6073 case X86::CX: DestReg = X86::ECX; break;
6074 case X86::BX: DestReg = X86::EBX; break;
6075 case X86::SI: DestReg = X86::ESI; break;
6076 case X86::DI: DestReg = X86::EDI; break;
6077 case X86::BP: DestReg = X86::EBP; break;
6078 case X86::SP: DestReg = X86::ESP; break;
6081 Res.first = DestReg;
6082 Res.second = Res.second = X86::GR32RegisterClass;
6084 } else if (VT == MVT::i64) {
6085 unsigned DestReg = 0;
6086 switch (Res.first) {
6088 case X86::AX: DestReg = X86::RAX; break;
6089 case X86::DX: DestReg = X86::RDX; break;
6090 case X86::CX: DestReg = X86::RCX; break;
6091 case X86::BX: DestReg = X86::RBX; break;
6092 case X86::SI: DestReg = X86::RSI; break;
6093 case X86::DI: DestReg = X86::RDI; break;
6094 case X86::BP: DestReg = X86::RBP; break;
6095 case X86::SP: DestReg = X86::RSP; break;
6098 Res.first = DestReg;
6099 Res.second = Res.second = X86::GR64RegisterClass;