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/ParamAttrsList.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 divide and remainder are lowered to use operations that
173 // produce two results, to match the available instructions. This exposes
174 // the two-result form to trivial CSE, which is able to combine x/y and x%y
175 // into a single instruction.
177 // Scalar integer multiply-high is also lowered to use two-result
178 // operations, to match the available instructions. However, plain multiply
179 // (low) operations are left as Legal, as there are single-result
180 // instructions for this in x86. Using the two-result multiply instructions
181 // when both high and low results are needed must be arranged by dagcombine.
182 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
183 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
184 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
185 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
186 setOperationAction(ISD::SREM , MVT::i8 , Expand);
187 setOperationAction(ISD::UREM , MVT::i8 , Expand);
188 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
189 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
190 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
191 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
192 setOperationAction(ISD::SREM , MVT::i16 , Expand);
193 setOperationAction(ISD::UREM , MVT::i16 , 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::MULHS , MVT::i64 , Expand);
201 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
202 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
203 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
204 setOperationAction(ISD::SREM , MVT::i64 , Expand);
205 setOperationAction(ISD::UREM , MVT::i64 , Expand);
207 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
208 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
209 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
210 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
211 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
212 if (Subtarget->is64Bit())
213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
217 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
218 setOperationAction(ISD::FREM , MVT::f32 , Expand);
219 setOperationAction(ISD::FREM , MVT::f64 , Expand);
220 setOperationAction(ISD::FREM , MVT::f80 , Expand);
221 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
223 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
224 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
225 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
226 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
227 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
228 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
229 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
230 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
231 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
232 if (Subtarget->is64Bit()) {
233 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
234 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
235 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
238 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
239 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
241 // These should be promoted to a larger select which is supported.
242 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
243 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
244 // X86 wants to expand cmov itself.
245 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
246 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
247 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
248 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
249 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
250 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
251 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
252 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
253 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
254 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
255 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
258 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
260 // X86 ret instruction may pop stack.
261 setOperationAction(ISD::RET , MVT::Other, Custom);
262 if (!Subtarget->is64Bit())
263 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
266 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
267 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
268 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
269 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
270 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
271 if (Subtarget->is64Bit()) {
272 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
273 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
274 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
275 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
277 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
278 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
279 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
280 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
281 if (Subtarget->is64Bit()) {
282 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
283 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
284 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
286 // X86 wants to expand memset / memcpy itself.
287 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
288 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
290 if (!Subtarget->hasSSE1())
291 setOperationAction(ISD::PREFETCH , MVT::Other, Expand);
293 if (!Subtarget->hasSSE2())
294 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
296 setOperationAction(ISD::ATOMIC_LCS , MVT::i8, Custom);
297 setOperationAction(ISD::ATOMIC_LCS , MVT::i16, Custom);
298 setOperationAction(ISD::ATOMIC_LCS , MVT::i32, Custom);
299 setOperationAction(ISD::ATOMIC_LCS , MVT::i64, Custom);
301 // Use the default ISD::LOCATION, ISD::DECLARE expansion.
302 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
303 // FIXME - use subtarget debug flags
304 if (!Subtarget->isTargetDarwin() &&
305 !Subtarget->isTargetELF() &&
306 !Subtarget->isTargetCygMing())
307 setOperationAction(ISD::LABEL, MVT::Other, Expand);
309 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
310 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
311 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
312 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
313 if (Subtarget->is64Bit()) {
315 setExceptionPointerRegister(X86::RAX);
316 setExceptionSelectorRegister(X86::RDX);
318 setExceptionPointerRegister(X86::EAX);
319 setExceptionSelectorRegister(X86::EDX);
321 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
323 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
325 setOperationAction(ISD::TRAP, MVT::Other, Legal);
327 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
328 setOperationAction(ISD::VASTART , MVT::Other, Custom);
329 setOperationAction(ISD::VAARG , MVT::Other, Expand);
330 setOperationAction(ISD::VAEND , MVT::Other, Expand);
331 if (Subtarget->is64Bit())
332 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
334 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
336 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
337 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
338 if (Subtarget->is64Bit())
339 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
340 if (Subtarget->isTargetCygMing())
341 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
343 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
345 if (X86ScalarSSEf64) {
346 // f32 and f64 use SSE.
347 // Set up the FP register classes.
348 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
349 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
351 // Use ANDPD to simulate FABS.
352 setOperationAction(ISD::FABS , MVT::f64, Custom);
353 setOperationAction(ISD::FABS , MVT::f32, Custom);
355 // Use XORP to simulate FNEG.
356 setOperationAction(ISD::FNEG , MVT::f64, Custom);
357 setOperationAction(ISD::FNEG , MVT::f32, Custom);
359 // Use ANDPD and ORPD to simulate FCOPYSIGN.
360 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
361 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
363 // We don't support sin/cos/fmod
364 setOperationAction(ISD::FSIN , MVT::f64, Expand);
365 setOperationAction(ISD::FCOS , MVT::f64, Expand);
366 setOperationAction(ISD::FSIN , MVT::f32, Expand);
367 setOperationAction(ISD::FCOS , MVT::f32, Expand);
369 // Expand FP immediates into loads from the stack, except for the special
371 addLegalFPImmediate(APFloat(+0.0)); // xorpd
372 addLegalFPImmediate(APFloat(+0.0f)); // xorps
374 // Floating truncations from f80 and extensions to f80 go through memory.
375 // If optimizing, we lie about this though and handle it in
376 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
378 setConvertAction(MVT::f32, MVT::f80, Expand);
379 setConvertAction(MVT::f64, MVT::f80, Expand);
380 setConvertAction(MVT::f80, MVT::f32, Expand);
381 setConvertAction(MVT::f80, MVT::f64, Expand);
383 } else if (X86ScalarSSEf32) {
384 // Use SSE for f32, x87 for f64.
385 // Set up the FP register classes.
386 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
387 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
389 // Use ANDPS to simulate FABS.
390 setOperationAction(ISD::FABS , MVT::f32, Custom);
392 // Use XORP to simulate FNEG.
393 setOperationAction(ISD::FNEG , MVT::f32, Custom);
395 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
397 // Use ANDPS and ORPS to simulate FCOPYSIGN.
398 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
399 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
401 // We don't support sin/cos/fmod
402 setOperationAction(ISD::FSIN , MVT::f32, Expand);
403 setOperationAction(ISD::FCOS , MVT::f32, Expand);
405 // Special cases we handle for FP constants.
406 addLegalFPImmediate(APFloat(+0.0f)); // xorps
407 addLegalFPImmediate(APFloat(+0.0)); // FLD0
408 addLegalFPImmediate(APFloat(+1.0)); // FLD1
409 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
410 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
412 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
413 // this though and handle it in InstructionSelectPreprocess so that
414 // dagcombine2 can hack on these.
416 setConvertAction(MVT::f32, MVT::f64, Expand);
417 setConvertAction(MVT::f32, MVT::f80, Expand);
418 setConvertAction(MVT::f80, MVT::f32, Expand);
419 setConvertAction(MVT::f64, MVT::f32, Expand);
420 // And x87->x87 truncations also.
421 setConvertAction(MVT::f80, MVT::f64, Expand);
425 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
426 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
429 // f32 and f64 in x87.
430 // Set up the FP register classes.
431 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
432 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
434 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
435 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
436 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
437 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
439 // Floating truncations go through memory. If optimizing, we lie about
440 // this though and handle it in InstructionSelectPreprocess so that
441 // dagcombine2 can hack on these.
443 setConvertAction(MVT::f80, MVT::f32, Expand);
444 setConvertAction(MVT::f64, MVT::f32, Expand);
445 setConvertAction(MVT::f80, MVT::f64, Expand);
449 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
450 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
452 addLegalFPImmediate(APFloat(+0.0)); // FLD0
453 addLegalFPImmediate(APFloat(+1.0)); // FLD1
454 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
455 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
456 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
457 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
458 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
459 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
462 // Long double always uses X87.
463 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
464 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
465 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
467 APFloat TmpFlt(+0.0);
468 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
469 addLegalFPImmediate(TmpFlt); // FLD0
471 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
472 APFloat TmpFlt2(+1.0);
473 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
474 addLegalFPImmediate(TmpFlt2); // FLD1
475 TmpFlt2.changeSign();
476 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
480 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
481 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
484 // Always use a library call for pow.
485 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
486 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
487 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
489 // First set operation action for all vector types to expand. Then we
490 // will selectively turn on ones that can be effectively codegen'd.
491 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
492 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
493 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
494 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
495 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
496 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
497 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
498 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
499 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
500 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
501 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
502 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
503 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
504 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
505 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
506 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
507 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
508 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
509 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
510 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
511 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
512 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
513 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
514 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
515 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
516 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
517 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
518 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
519 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
520 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
521 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
522 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
523 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
524 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
525 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
526 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
527 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
528 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
529 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
532 if (Subtarget->hasMMX()) {
533 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
534 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
535 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
536 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
538 // FIXME: add MMX packed arithmetics
540 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
541 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
542 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
543 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
545 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
546 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
547 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
548 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
550 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
551 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
553 setOperationAction(ISD::AND, MVT::v8i8, Promote);
554 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
555 setOperationAction(ISD::AND, MVT::v4i16, Promote);
556 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
557 setOperationAction(ISD::AND, MVT::v2i32, Promote);
558 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
559 setOperationAction(ISD::AND, MVT::v1i64, Legal);
561 setOperationAction(ISD::OR, MVT::v8i8, Promote);
562 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
563 setOperationAction(ISD::OR, MVT::v4i16, Promote);
564 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
565 setOperationAction(ISD::OR, MVT::v2i32, Promote);
566 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
567 setOperationAction(ISD::OR, MVT::v1i64, Legal);
569 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
570 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
571 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
572 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
573 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
574 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
575 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
577 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
578 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
579 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
580 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
581 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
582 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
583 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
585 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
586 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
587 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
588 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
590 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
591 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
592 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
593 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
595 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
596 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
597 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
600 if (Subtarget->hasSSE1()) {
601 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
603 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
604 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
605 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
606 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
607 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
608 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
609 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
610 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
611 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
612 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
613 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
616 if (Subtarget->hasSSE2()) {
617 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
618 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
619 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
620 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
621 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
623 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
624 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
625 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
626 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
627 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
628 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
629 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
630 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
631 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
632 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
633 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
634 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
635 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
636 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
637 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
639 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
640 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
641 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
642 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
643 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
645 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
646 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
647 // Do not attempt to custom lower non-power-of-2 vectors
648 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
650 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
651 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
652 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
654 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
655 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
656 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
657 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
658 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
659 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
660 if (Subtarget->is64Bit()) {
661 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
665 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
666 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
667 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
668 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
669 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
670 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
671 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
672 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
673 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
674 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
675 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
676 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
679 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
681 // Custom lower v2i64 and v2f64 selects.
682 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
683 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
684 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
685 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
688 if (Subtarget->hasSSE41()) {
689 // FIXME: Do we need to handle scalar-to-vector here?
690 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
692 // i8 and i16 vectors are custom , because the source register and source
693 // source memory operand types are not the same width. f32 vectors are
694 // custom since the immediate controlling the insert encodes additional
696 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
697 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
698 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
699 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
701 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
702 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
703 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
704 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
706 if (Subtarget->is64Bit()) {
707 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
708 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
712 // We want to custom lower some of our intrinsics.
713 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
715 // We have target-specific dag combine patterns for the following nodes:
716 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
717 setTargetDAGCombine(ISD::SELECT);
718 setTargetDAGCombine(ISD::STORE);
720 computeRegisterProperties();
722 // FIXME: These should be based on subtarget info. Plus, the values should
723 // be smaller when we are in optimizing for size mode.
724 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
725 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
726 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
727 allowUnalignedMemoryAccesses = true; // x86 supports it!
728 setPrefLoopAlignment(16);
731 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
732 /// the desired ByVal argument alignment.
733 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
736 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
737 if (VTy->getBitWidth() == 128)
739 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
740 unsigned EltAlign = 0;
741 getMaxByValAlign(ATy->getElementType(), EltAlign);
742 if (EltAlign > MaxAlign)
744 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
745 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
746 unsigned EltAlign = 0;
747 getMaxByValAlign(STy->getElementType(i), EltAlign);
748 if (EltAlign > MaxAlign)
757 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
758 /// function arguments in the caller parameter area. For X86, aggregates
759 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
760 /// are at 4-byte boundaries.
761 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
762 if (Subtarget->is64Bit())
763 return getTargetData()->getABITypeAlignment(Ty);
765 if (Subtarget->hasSSE1())
766 getMaxByValAlign(Ty, Align);
770 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
772 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
773 SelectionDAG &DAG) const {
774 if (usesGlobalOffsetTable())
775 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
776 if (!Subtarget->isPICStyleRIPRel())
777 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
781 //===----------------------------------------------------------------------===//
782 // Return Value Calling Convention Implementation
783 //===----------------------------------------------------------------------===//
785 #include "X86GenCallingConv.inc"
787 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
788 /// exists skip possible ISD:TokenFactor.
789 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
790 if (Chain.getOpcode() == X86ISD::TAILCALL) {
792 } else if (Chain.getOpcode() == ISD::TokenFactor) {
793 if (Chain.getNumOperands() &&
794 Chain.getOperand(0).getOpcode() == X86ISD::TAILCALL)
795 return Chain.getOperand(0);
800 /// LowerRET - Lower an ISD::RET node.
801 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
802 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
804 SmallVector<CCValAssign, 16> RVLocs;
805 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
806 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
807 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
808 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
810 // If this is the first return lowered for this function, add the regs to the
811 // liveout set for the function.
812 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
813 for (unsigned i = 0; i != RVLocs.size(); ++i)
814 if (RVLocs[i].isRegLoc())
815 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
817 SDOperand Chain = Op.getOperand(0);
819 // Handle tail call return.
820 Chain = GetPossiblePreceedingTailCall(Chain);
821 if (Chain.getOpcode() == X86ISD::TAILCALL) {
822 SDOperand TailCall = Chain;
823 SDOperand TargetAddress = TailCall.getOperand(1);
824 SDOperand StackAdjustment = TailCall.getOperand(2);
825 assert(((TargetAddress.getOpcode() == ISD::Register &&
826 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
827 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
828 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
829 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
830 "Expecting an global address, external symbol, or register");
831 assert(StackAdjustment.getOpcode() == ISD::Constant &&
832 "Expecting a const value");
834 SmallVector<SDOperand,8> Operands;
835 Operands.push_back(Chain.getOperand(0));
836 Operands.push_back(TargetAddress);
837 Operands.push_back(StackAdjustment);
838 // Copy registers used by the call. Last operand is a flag so it is not
840 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
841 Operands.push_back(Chain.getOperand(i));
843 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
850 // Copy the result values into the output registers.
851 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
852 RVLocs[0].getLocReg() != X86::ST0) {
853 for (unsigned i = 0; i != RVLocs.size(); ++i) {
854 CCValAssign &VA = RVLocs[i];
855 assert(VA.isRegLoc() && "Can only return in registers!");
856 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
858 Flag = Chain.getValue(1);
861 // We need to handle a destination of ST0 specially, because it isn't really
863 SDOperand Value = Op.getOperand(1);
865 // an XMM register onto the fp-stack. Do this with an FP_EXTEND to f80.
866 // This will get legalized into a load/store if it can't get optimized away.
867 if (isScalarFPTypeInSSEReg(RVLocs[0].getValVT()))
868 Value = DAG.getNode(ISD::FP_EXTEND, MVT::f80, Value);
870 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
871 SDOperand Ops[] = { Chain, Value };
872 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
873 Flag = Chain.getValue(1);
876 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
878 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
880 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
884 /// LowerCallResult - Lower the result values of an ISD::CALL into the
885 /// appropriate copies out of appropriate physical registers. This assumes that
886 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
887 /// being lowered. The returns a SDNode with the same number of values as the
889 SDNode *X86TargetLowering::
890 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
891 unsigned CallingConv, SelectionDAG &DAG) {
893 // Assign locations to each value returned by this call.
894 SmallVector<CCValAssign, 16> RVLocs;
895 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
896 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
897 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
899 SmallVector<SDOperand, 8> ResultVals;
901 // Copy all of the result registers out of their specified physreg.
902 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
903 for (unsigned i = 0; i != RVLocs.size(); ++i) {
904 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
905 RVLocs[i].getValVT(), InFlag).getValue(1);
906 InFlag = Chain.getValue(2);
907 ResultVals.push_back(Chain.getValue(0));
910 // Copies from the FP stack are special, as ST0 isn't a valid register
911 // before the fp stackifier runs.
913 // Copy ST0 into an RFP register with FP_GET_RESULT. If this will end up
914 // in an SSE register, copy it out as F80 and do a truncate, otherwise use
915 // the specified value type.
916 MVT::ValueType GetResultTy = RVLocs[0].getValVT();
917 if (isScalarFPTypeInSSEReg(GetResultTy))
918 GetResultTy = MVT::f80;
919 SDVTList Tys = DAG.getVTList(GetResultTy, MVT::Other, MVT::Flag);
921 SDOperand GROps[] = { Chain, InFlag };
922 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
923 Chain = RetVal.getValue(1);
924 InFlag = RetVal.getValue(2);
926 // If we want the result in an SSE register, use an FP_TRUNCATE to get it
928 if (GetResultTy != RVLocs[0].getValVT())
929 RetVal = DAG.getNode(ISD::FP_ROUND, RVLocs[0].getValVT(), RetVal,
930 // This truncation won't change the value.
931 DAG.getIntPtrConstant(1));
933 ResultVals.push_back(RetVal);
936 // Merge everything together with a MERGE_VALUES node.
937 ResultVals.push_back(Chain);
938 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
939 &ResultVals[0], ResultVals.size()).Val;
942 /// LowerCallResultToTwo64BitRegs - Lower the result values of an x86-64
943 /// ISD::CALL where the results are known to be in two 64-bit registers,
944 /// e.g. XMM0 and XMM1. This simplify store the two values back to the
945 /// fixed stack slot allocated for StructRet.
946 SDNode *X86TargetLowering::
947 LowerCallResultToTwo64BitRegs(SDOperand Chain, SDOperand InFlag,
948 SDNode *TheCall, unsigned Reg1, unsigned Reg2,
949 MVT::ValueType VT, SelectionDAG &DAG) {
950 SDOperand RetVal1 = DAG.getCopyFromReg(Chain, Reg1, VT, InFlag);
951 Chain = RetVal1.getValue(1);
952 InFlag = RetVal1.getValue(2);
953 SDOperand RetVal2 = DAG.getCopyFromReg(Chain, Reg2, VT, InFlag);
954 Chain = RetVal2.getValue(1);
955 InFlag = RetVal2.getValue(2);
956 SDOperand FIN = TheCall->getOperand(5);
957 Chain = DAG.getStore(Chain, RetVal1, FIN, NULL, 0);
958 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
959 Chain = DAG.getStore(Chain, RetVal2, FIN, NULL, 0);
963 /// LowerCallResultToTwoX87Regs - Lower the result values of an x86-64 ISD::CALL
964 /// where the results are known to be in ST0 and ST1.
965 SDNode *X86TargetLowering::
966 LowerCallResultToTwoX87Regs(SDOperand Chain, SDOperand InFlag,
967 SDNode *TheCall, SelectionDAG &DAG) {
968 SmallVector<SDOperand, 8> ResultVals;
969 const MVT::ValueType VTs[] = { MVT::f80, MVT::f80, MVT::Other, MVT::Flag };
970 SDVTList Tys = DAG.getVTList(VTs, 4);
971 SDOperand Ops[] = { Chain, InFlag };
972 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT2, Tys, Ops, 2);
973 Chain = RetVal.getValue(2);
974 SDOperand FIN = TheCall->getOperand(5);
975 Chain = DAG.getStore(Chain, RetVal.getValue(1), FIN, NULL, 0);
976 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(16));
977 Chain = DAG.getStore(Chain, RetVal, FIN, NULL, 0);
981 //===----------------------------------------------------------------------===//
982 // C & StdCall & Fast Calling Convention implementation
983 //===----------------------------------------------------------------------===//
984 // StdCall calling convention seems to be standard for many Windows' API
985 // routines and around. It differs from C calling convention just a little:
986 // callee should clean up the stack, not caller. Symbols should be also
987 // decorated in some fancy way :) It doesn't support any vector arguments.
988 // For info on fast calling convention see Fast Calling Convention (tail call)
989 // implementation LowerX86_32FastCCCallTo.
991 /// AddLiveIn - This helper function adds the specified physical register to the
992 /// MachineFunction as a live in value. It also creates a corresponding virtual
994 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
995 const TargetRegisterClass *RC) {
996 assert(RC->contains(PReg) && "Not the correct regclass!");
997 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
998 MF.getRegInfo().addLiveIn(PReg, VReg);
1002 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1004 static bool CallIsStructReturn(SDOperand Op) {
1005 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1009 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(6));
1010 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1013 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1014 /// return semantics.
1015 static bool ArgsAreStructReturn(SDOperand Op) {
1016 unsigned NumArgs = Op.Val->getNumValues() - 1;
1020 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(3));
1021 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1024 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires the
1025 /// callee to pop its own arguments. Callee pop is necessary to support tail
1027 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1028 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1032 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1035 case CallingConv::X86_StdCall:
1036 return !Subtarget->is64Bit();
1037 case CallingConv::X86_FastCall:
1038 return !Subtarget->is64Bit();
1039 case CallingConv::Fast:
1040 return PerformTailCallOpt;
1044 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1045 /// FORMAL_ARGUMENTS node.
1046 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1047 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1049 if (Subtarget->is64Bit()) {
1050 if (CC == CallingConv::Fast && PerformTailCallOpt)
1051 return CC_X86_64_TailCall;
1056 if (CC == CallingConv::X86_FastCall)
1057 return CC_X86_32_FastCall;
1058 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1059 return CC_X86_32_TailCall;
1064 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1065 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1067 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1068 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1069 if (CC == CallingConv::X86_FastCall)
1071 else if (CC == CallingConv::X86_StdCall)
1076 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
1077 /// possibly be overwritten when lowering the outgoing arguments in a tail
1078 /// call. Currently the implementation of this call is very conservative and
1079 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
1080 /// virtual registers would be overwritten by direct lowering.
1081 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
1082 MachineFrameInfo * MFI) {
1083 RegisterSDNode * OpReg = NULL;
1084 FrameIndexSDNode * FrameIdxNode = NULL;
1086 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
1087 (Op.getOpcode()== ISD::CopyFromReg &&
1088 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
1089 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
1090 (Op.getOpcode() == ISD::LOAD &&
1091 (FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op.getOperand(1))) &&
1092 (MFI->isFixedObjectIndex((FrameIdx = FrameIdxNode->getIndex()))) &&
1093 (MFI->getObjectOffset(FrameIdx) >= 0)))
1098 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1099 /// in a register before calling.
1100 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1101 return !IsTailCall && !Is64Bit &&
1102 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1103 Subtarget->isPICStyleGOT();
1107 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1108 /// address to be loaded in a register.
1110 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1111 return !Is64Bit && IsTailCall &&
1112 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1113 Subtarget->isPICStyleGOT();
1116 /// CopyTailCallClobberedArgumentsToVRegs - Create virtual registers for all
1117 /// arguments to force loading and guarantee that arguments sourcing from
1118 /// incomming parameters are not overwriting each other.
1120 CopyTailCallClobberedArgumentsToVRegs(SDOperand Chain,
1121 SmallVector<std::pair<unsigned, SDOperand>, 8> &TailCallClobberedVRegs,
1123 MachineFunction &MF,
1124 const TargetLowering * TL) {
1127 for (unsigned i = 0, e = TailCallClobberedVRegs.size(); i != e; i++) {
1128 SDOperand Arg = TailCallClobberedVRegs[i].second;
1129 unsigned Idx = TailCallClobberedVRegs[i].first;
1132 createVirtualRegister(TL->getRegClassFor(Arg.getValueType()));
1133 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
1134 InFlag = Chain.getValue(1);
1135 Arg = DAG.getCopyFromReg(Chain, VReg, Arg.getValueType(), InFlag);
1136 TailCallClobberedVRegs[i] = std::make_pair(Idx, Arg);
1137 Chain = Arg.getValue(1);
1138 InFlag = Arg.getValue(2);
1143 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1144 /// by "Src" to address "Dst" with size and alignment information specified by
1145 /// the specific parameter attribute. The copy will be passed as a byval function
1148 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1149 unsigned Flags, SelectionDAG &DAG) {
1150 unsigned Align = 1 <<
1151 ((Flags & ISD::ParamFlags::ByValAlign) >> ISD::ParamFlags::ByValAlignOffs);
1152 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1153 ISD::ParamFlags::ByValSizeOffs;
1154 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1155 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1156 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1157 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, AlignNode, AlwaysInline);
1160 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1161 const CCValAssign &VA,
1162 MachineFrameInfo *MFI,
1164 SDOperand Root, unsigned i) {
1165 // Create the nodes corresponding to a load from this parameter slot.
1166 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
1167 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1168 bool isByVal = Flags & ISD::ParamFlags::ByVal;
1169 bool isImmutable = !AlwaysUseMutable && !isByVal;
1171 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1172 // changed with more analysis.
1173 // In case of tail call optimization mark all arguments mutable. Since they
1174 // could be overwritten by lowering of arguments in case of a tail call.
1175 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1176 VA.getLocMemOffset(), isImmutable);
1177 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1180 return DAG.getLoad(VA.getValVT(), Root, FIN,
1181 PseudoSourceValue::getFixedStack(), FI);
1185 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1186 MachineFunction &MF = DAG.getMachineFunction();
1187 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1189 const Function* Fn = MF.getFunction();
1190 if (Fn->hasExternalLinkage() &&
1191 Subtarget->isTargetCygMing() &&
1192 Fn->getName() == "main")
1193 FuncInfo->setForceFramePointer(true);
1195 // Decorate the function name.
1196 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1198 MachineFrameInfo *MFI = MF.getFrameInfo();
1199 SDOperand Root = Op.getOperand(0);
1200 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1201 unsigned CC = MF.getFunction()->getCallingConv();
1202 bool Is64Bit = Subtarget->is64Bit();
1204 assert(!(isVarArg && CC == CallingConv::Fast) &&
1205 "Var args not supported with calling convention fastcc");
1207 // Assign locations to all of the incoming arguments.
1208 SmallVector<CCValAssign, 16> ArgLocs;
1209 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1210 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1212 SmallVector<SDOperand, 8> ArgValues;
1213 unsigned LastVal = ~0U;
1214 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1215 CCValAssign &VA = ArgLocs[i];
1216 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1218 assert(VA.getValNo() != LastVal &&
1219 "Don't support value assigned to multiple locs yet");
1220 LastVal = VA.getValNo();
1222 if (VA.isRegLoc()) {
1223 MVT::ValueType RegVT = VA.getLocVT();
1224 TargetRegisterClass *RC;
1225 if (RegVT == MVT::i32)
1226 RC = X86::GR32RegisterClass;
1227 else if (Is64Bit && RegVT == MVT::i64)
1228 RC = X86::GR64RegisterClass;
1229 else if (RegVT == MVT::f32)
1230 RC = X86::FR32RegisterClass;
1231 else if (RegVT == MVT::f64)
1232 RC = X86::FR64RegisterClass;
1234 assert(MVT::isVector(RegVT));
1235 if (Is64Bit && MVT::getSizeInBits(RegVT) == 64) {
1236 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1239 RC = X86::VR128RegisterClass;
1242 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1243 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1245 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1246 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1248 if (VA.getLocInfo() == CCValAssign::SExt)
1249 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1250 DAG.getValueType(VA.getValVT()));
1251 else if (VA.getLocInfo() == CCValAssign::ZExt)
1252 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1253 DAG.getValueType(VA.getValVT()));
1255 if (VA.getLocInfo() != CCValAssign::Full)
1256 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1258 // Handle MMX values passed in GPRs.
1259 if (Is64Bit && RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1260 MVT::getSizeInBits(RegVT) == 64)
1261 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1263 ArgValues.push_back(ArgValue);
1265 assert(VA.isMemLoc());
1266 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1270 unsigned StackSize = CCInfo.getNextStackOffset();
1271 // align stack specially for tail calls
1272 if (CC == CallingConv::Fast)
1273 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1275 // If the function takes variable number of arguments, make a frame index for
1276 // the start of the first vararg value... for expansion of llvm.va_start.
1278 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1279 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1282 static const unsigned GPR64ArgRegs[] = {
1283 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1285 static const unsigned XMMArgRegs[] = {
1286 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1287 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1290 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1291 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1293 // For X86-64, if there are vararg parameters that are passed via
1294 // registers, then we must store them to their spots on the stack so they
1295 // may be loaded by deferencing the result of va_next.
1296 VarArgsGPOffset = NumIntRegs * 8;
1297 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1298 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1300 // Store the integer parameter registers.
1301 SmallVector<SDOperand, 8> MemOps;
1302 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1303 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1304 DAG.getIntPtrConstant(VarArgsGPOffset));
1305 for (; NumIntRegs != 6; ++NumIntRegs) {
1306 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1307 X86::GR64RegisterClass);
1308 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1310 DAG.getStore(Val.getValue(1), Val, FIN,
1311 PseudoSourceValue::getFixedStack(),
1313 MemOps.push_back(Store);
1314 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1315 DAG.getIntPtrConstant(8));
1318 // Now store the XMM (fp + vector) parameter registers.
1319 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1320 DAG.getIntPtrConstant(VarArgsFPOffset));
1321 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1322 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1323 X86::VR128RegisterClass);
1324 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1326 DAG.getStore(Val.getValue(1), Val, FIN,
1327 PseudoSourceValue::getFixedStack(),
1329 MemOps.push_back(Store);
1330 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1331 DAG.getIntPtrConstant(16));
1333 if (!MemOps.empty())
1334 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1335 &MemOps[0], MemOps.size());
1339 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1340 // arguments and the arguments after the retaddr has been pushed are
1342 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1343 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1344 (StackSize & 7) == 0)
1347 ArgValues.push_back(Root);
1349 // Some CCs need callee pop.
1350 if (IsCalleePop(Op)) {
1351 BytesToPopOnReturn = StackSize; // Callee pops everything.
1352 BytesCallerReserves = 0;
1354 BytesToPopOnReturn = 0; // Callee pops nothing.
1355 // If this is an sret function, the return should pop the hidden pointer.
1356 if (!Is64Bit && ArgsAreStructReturn(Op))
1357 BytesToPopOnReturn = 4;
1358 BytesCallerReserves = StackSize;
1362 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1363 if (CC == CallingConv::X86_FastCall)
1364 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1367 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1369 // Return the new list of results.
1370 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1371 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1375 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1376 const SDOperand &StackPtr,
1377 const CCValAssign &VA,
1380 unsigned LocMemOffset = VA.getLocMemOffset();
1381 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1382 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1383 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1384 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1385 if (Flags & ISD::ParamFlags::ByVal) {
1386 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1388 return DAG.getStore(Chain, Arg, PtrOff,
1389 PseudoSourceValue::getStack(), LocMemOffset);
1392 /// ClassifyX86_64SRetCallReturn - Classify how to implement a x86-64
1393 /// struct return call to the specified function. X86-64 ABI specifies
1394 /// some SRet calls are actually returned in registers. Since current
1395 /// LLVM cannot represent multi-value calls, they are represent as
1396 /// calls where the results are passed in a hidden struct provided by
1397 /// the caller. This function examines the type of the struct to
1398 /// determine the correct way to implement the call.
1400 X86TargetLowering::ClassifyX86_64SRetCallReturn(const Function *Fn) {
1401 // FIXME: Disabled for now.
1402 return X86::InMemory;
1404 const PointerType *PTy = cast<PointerType>(Fn->arg_begin()->getType());
1405 const Type *RTy = PTy->getElementType();
1406 unsigned Size = getTargetData()->getABITypeSize(RTy);
1407 if (Size != 16 && Size != 32)
1408 return X86::InMemory;
1411 const StructType *STy = dyn_cast<StructType>(RTy);
1412 if (!STy) return X86::InMemory;
1413 if (STy->getNumElements() == 2 &&
1414 STy->getElementType(0) == Type::X86_FP80Ty &&
1415 STy->getElementType(1) == Type::X86_FP80Ty)
1420 for (Type::subtype_iterator I = RTy->subtype_begin(), E = RTy->subtype_end();
1422 const Type *STy = I->get();
1423 if (!STy->isFPOrFPVector()) {
1431 return X86::InGPR64;
1434 void X86TargetLowering::X86_64AnalyzeSRetCallOperands(SDNode *TheCall,
1437 unsigned NumOps = (TheCall->getNumOperands() - 5) / 2;
1438 for (unsigned i = 1; i != NumOps; ++i) {
1439 MVT::ValueType ArgVT = TheCall->getOperand(5+2*i).getValueType();
1440 SDOperand FlagOp = TheCall->getOperand(5+2*i+1);
1441 unsigned ArgFlags =cast<ConstantSDNode>(FlagOp)->getValue();
1442 if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo)) {
1443 cerr << "Call operand #" << i << " has unhandled type "
1444 << MVT::getValueTypeString(ArgVT) << "\n";
1450 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1451 MachineFunction &MF = DAG.getMachineFunction();
1452 MachineFrameInfo * MFI = MF.getFrameInfo();
1453 SDOperand Chain = Op.getOperand(0);
1454 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1455 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1456 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1457 && CC == CallingConv::Fast && PerformTailCallOpt;
1458 SDOperand Callee = Op.getOperand(4);
1459 bool Is64Bit = Subtarget->is64Bit();
1460 bool IsStructRet = CallIsStructReturn(Op);
1462 assert(!(isVarArg && CC == CallingConv::Fast) &&
1463 "Var args not supported with calling convention fastcc");
1465 // Analyze operands of the call, assigning locations to each operand.
1466 SmallVector<CCValAssign, 16> ArgLocs;
1467 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1468 CCAssignFn *CCFn = CCAssignFnForNode(Op);
1470 X86::X86_64SRet SRetMethod = X86::InMemory;
1471 if (Is64Bit && IsStructRet)
1472 // FIXME: We can't figure out type of the sret structure for indirect
1473 // calls. We need to copy more information from CallSite to the ISD::CALL
1475 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1477 ClassifyX86_64SRetCallReturn(dyn_cast<Function>(G->getGlobal()));
1479 // UGLY HACK! For x86-64, some 128-bit aggregates are returns in a pair of
1480 // registers. Unfortunately, llvm does not support i128 yet so we pretend it's
1482 if (SRetMethod != X86::InMemory)
1483 X86_64AnalyzeSRetCallOperands(Op.Val, CCFn, CCInfo);
1485 CCInfo.AnalyzeCallOperands(Op.Val, CCFn);
1487 // Get a count of how many bytes are to be pushed on the stack.
1488 unsigned NumBytes = CCInfo.getNextStackOffset();
1489 if (CC == CallingConv::Fast)
1490 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1492 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1493 // arguments and the arguments after the retaddr has been pushed are aligned.
1494 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1495 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1496 (NumBytes & 7) == 0)
1501 // Lower arguments at fp - stackoffset + fpdiff.
1502 unsigned NumBytesCallerPushed =
1503 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1504 FPDiff = NumBytesCallerPushed - NumBytes;
1506 // Set the delta of movement of the returnaddr stackslot.
1507 // But only set if delta is greater than previous delta.
1508 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1509 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1512 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1514 SDOperand RetAddrFrIdx;
1516 // Adjust the Return address stack slot.
1518 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1519 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1520 // Load the "old" Return address.
1522 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1523 Chain = SDOperand(RetAddrFrIdx.Val, 1);
1527 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1528 SmallVector<std::pair<unsigned, SDOperand>, 8> TailCallClobberedVRegs;
1529 SmallVector<SDOperand, 8> MemOpChains;
1533 // Walk the register/memloc assignments, inserting copies/loads. For tail
1534 // calls, remember all arguments for later special lowering.
1535 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1536 CCValAssign &VA = ArgLocs[i];
1537 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1539 // Promote the value if needed.
1540 switch (VA.getLocInfo()) {
1541 default: assert(0 && "Unknown loc info!");
1542 case CCValAssign::Full: break;
1543 case CCValAssign::SExt:
1544 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1546 case CCValAssign::ZExt:
1547 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1549 case CCValAssign::AExt:
1550 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1554 if (VA.isRegLoc()) {
1555 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1558 assert(VA.isMemLoc());
1559 if (StackPtr.Val == 0)
1560 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1562 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1564 } else if (IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
1565 TailCallClobberedVRegs.push_back(std::make_pair(i,Arg));
1570 if (!MemOpChains.empty())
1571 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1572 &MemOpChains[0], MemOpChains.size());
1574 // Build a sequence of copy-to-reg nodes chained together with token chain
1575 // and flag operands which copy the outgoing args into registers.
1577 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1578 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1580 InFlag = Chain.getValue(1);
1583 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1585 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1586 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1587 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1589 InFlag = Chain.getValue(1);
1591 // If we are tail calling and generating PIC/GOT style code load the address
1592 // of the callee into ecx. The value in ecx is used as target of the tail
1593 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1594 // calls on PIC/GOT architectures. Normally we would just put the address of
1595 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1596 // restored (since ebx is callee saved) before jumping to the target@PLT.
1597 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1598 // Note: The actual moving to ecx is done further down.
1599 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1600 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1601 !G->getGlobal()->hasProtectedVisibility())
1602 Callee = LowerGlobalAddress(Callee, DAG);
1603 else if (isa<ExternalSymbolSDNode>(Callee))
1604 Callee = LowerExternalSymbol(Callee,DAG);
1607 if (Is64Bit && isVarArg) {
1608 // From AMD64 ABI document:
1609 // For calls that may call functions that use varargs or stdargs
1610 // (prototype-less calls or calls to functions containing ellipsis (...) in
1611 // the declaration) %al is used as hidden argument to specify the number
1612 // of SSE registers used. The contents of %al do not need to match exactly
1613 // the number of registers, but must be an ubound on the number of SSE
1614 // registers used and is in the range 0 - 8 inclusive.
1616 // Count the number of XMM registers allocated.
1617 static const unsigned XMMArgRegs[] = {
1618 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1619 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1621 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1623 Chain = DAG.getCopyToReg(Chain, X86::AL,
1624 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1625 InFlag = Chain.getValue(1);
1629 // For tail calls lower the arguments to the 'real' stack slot.
1631 SmallVector<SDOperand, 8> MemOpChains2;
1634 // Do not flag preceeding copytoreg stuff together with the following stuff.
1635 InFlag = SDOperand();
1637 Chain = CopyTailCallClobberedArgumentsToVRegs(Chain, TailCallClobberedVRegs,
1640 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1641 CCValAssign &VA = ArgLocs[i];
1642 if (!VA.isRegLoc()) {
1643 assert(VA.isMemLoc());
1644 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1645 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1646 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1647 // Create frame index.
1648 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1649 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1650 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1651 FIN = DAG.getFrameIndex(FI, MVT::i32);
1653 // Find virtual register for this argument.
1655 for (unsigned idx=0, e= TailCallClobberedVRegs.size(); idx < e; idx++)
1656 if (TailCallClobberedVRegs[idx].first==i) {
1657 Arg = TailCallClobberedVRegs[idx].second;
1661 assert(IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)==false ||
1662 (Found==true && "No corresponding Argument was found"));
1664 if (Flags & ISD::ParamFlags::ByVal) {
1665 // Copy relative to framepointer.
1666 MemOpChains2.push_back(CreateCopyOfByValArgument(Arg, FIN, Chain,
1669 // Store relative to framepointer.
1670 MemOpChains2.push_back(
1671 DAG.getStore(Chain, Arg, FIN,
1672 PseudoSourceValue::getFixedStack(), FI));
1677 if (!MemOpChains2.empty())
1678 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1679 &MemOpChains2[0], MemOpChains2.size());
1681 // Store the return address to the appropriate stack slot.
1683 // Calculate the new stack slot for the return address.
1684 int SlotSize = Is64Bit ? 8 : 4;
1685 int NewReturnAddrFI =
1686 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1687 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1688 SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1689 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1690 PseudoSourceValue::getFixedStack(), NewReturnAddrFI);
1694 // If the callee is a GlobalAddress node (quite common, every direct call is)
1695 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1696 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1697 // We should use extra load for direct calls to dllimported functions in
1699 if ((IsTailCall || !Is64Bit ||
1700 getTargetMachine().getCodeModel() != CodeModel::Large)
1701 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1702 getTargetMachine(), true))
1703 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1704 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1705 if (IsTailCall || !Is64Bit ||
1706 getTargetMachine().getCodeModel() != CodeModel::Large)
1707 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1708 } else if (IsTailCall) {
1709 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1711 Chain = DAG.getCopyToReg(Chain,
1712 DAG.getRegister(Opc, getPointerTy()),
1714 Callee = DAG.getRegister(Opc, getPointerTy());
1715 // Add register as live out.
1716 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1719 // Returns a chain & a flag for retval copy to use.
1720 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1721 SmallVector<SDOperand, 8> Ops;
1724 Ops.push_back(Chain);
1725 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1726 Ops.push_back(DAG.getIntPtrConstant(0));
1728 Ops.push_back(InFlag);
1729 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1730 InFlag = Chain.getValue(1);
1732 // Returns a chain & a flag for retval copy to use.
1733 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1737 Ops.push_back(Chain);
1738 Ops.push_back(Callee);
1741 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1743 // Add an implicit use GOT pointer in EBX.
1744 if (!IsTailCall && !Is64Bit &&
1745 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1746 Subtarget->isPICStyleGOT())
1747 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1749 // Add argument registers to the end of the list so that they are known live
1751 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1752 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1753 RegsToPass[i].second.getValueType()));
1756 Ops.push_back(InFlag);
1759 assert(InFlag.Val &&
1760 "Flag must be set. Depend on flag being set in LowerRET");
1761 Chain = DAG.getNode(X86ISD::TAILCALL,
1762 Op.Val->getVTList(), &Ops[0], Ops.size());
1764 return SDOperand(Chain.Val, Op.ResNo);
1767 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1768 InFlag = Chain.getValue(1);
1770 // Create the CALLSEQ_END node.
1771 unsigned NumBytesForCalleeToPush;
1772 if (IsCalleePop(Op))
1773 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1774 else if (!Is64Bit && IsStructRet)
1775 // If this is is a call to a struct-return function, the callee
1776 // pops the hidden struct pointer, so we have to push it back.
1777 // This is common for Darwin/X86, Linux & Mingw32 targets.
1778 NumBytesForCalleeToPush = 4;
1780 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1782 // Returns a flag for retval copy to use.
1783 Chain = DAG.getCALLSEQ_END(Chain,
1784 DAG.getIntPtrConstant(NumBytes),
1785 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1787 InFlag = Chain.getValue(1);
1789 // Handle result values, copying them out of physregs into vregs that we
1791 switch (SRetMethod) {
1793 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1795 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1797 MVT::i64, DAG), Op.ResNo);
1799 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1800 X86::XMM0, X86::XMM1,
1801 MVT::f64, DAG), Op.ResNo);
1803 return SDOperand(LowerCallResultToTwoX87Regs(Chain, InFlag, Op.Val, DAG),
1809 //===----------------------------------------------------------------------===//
1810 // Fast Calling Convention (tail call) implementation
1811 //===----------------------------------------------------------------------===//
1813 // Like std call, callee cleans arguments, convention except that ECX is
1814 // reserved for storing the tail called function address. Only 2 registers are
1815 // free for argument passing (inreg). Tail call optimization is performed
1817 // * tailcallopt is enabled
1818 // * caller/callee are fastcc
1819 // On X86_64 architecture with GOT-style position independent code only local
1820 // (within module) calls are supported at the moment.
1821 // To keep the stack aligned according to platform abi the function
1822 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1823 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1824 // If a tail called function callee has more arguments than the caller the
1825 // caller needs to make sure that there is room to move the RETADDR to. This is
1826 // achieved by reserving an area the size of the argument delta right after the
1827 // original REtADDR, but before the saved framepointer or the spilled registers
1828 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1840 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1841 /// for a 16 byte align requirement.
1842 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1843 SelectionDAG& DAG) {
1844 if (PerformTailCallOpt) {
1845 MachineFunction &MF = DAG.getMachineFunction();
1846 const TargetMachine &TM = MF.getTarget();
1847 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1848 unsigned StackAlignment = TFI.getStackAlignment();
1849 uint64_t AlignMask = StackAlignment - 1;
1850 int64_t Offset = StackSize;
1851 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1852 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1853 // Number smaller than 12 so just add the difference.
1854 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1856 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1857 Offset = ((~AlignMask) & Offset) + StackAlignment +
1858 (StackAlignment-SlotSize);
1865 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1866 /// following the call is a return. A function is eligible if caller/callee
1867 /// calling conventions match, currently only fastcc supports tail calls, and
1868 /// the function CALL is immediatly followed by a RET.
1869 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1871 SelectionDAG& DAG) const {
1872 if (!PerformTailCallOpt)
1875 // Check whether CALL node immediatly preceeds the RET node and whether the
1876 // return uses the result of the node or is a void return.
1877 unsigned NumOps = Ret.getNumOperands();
1879 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1880 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1882 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1883 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1884 MachineFunction &MF = DAG.getMachineFunction();
1885 unsigned CallerCC = MF.getFunction()->getCallingConv();
1886 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1887 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1888 SDOperand Callee = Call.getOperand(4);
1889 // On x86/32Bit PIC/GOT tail calls are supported.
1890 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1891 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1894 // Can only do local tail calls (in same module, hidden or protected) on
1895 // x86_64 PIC/GOT at the moment.
1896 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1897 return G->getGlobal()->hasHiddenVisibility()
1898 || G->getGlobal()->hasProtectedVisibility();
1905 //===----------------------------------------------------------------------===//
1906 // Other Lowering Hooks
1907 //===----------------------------------------------------------------------===//
1910 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1911 MachineFunction &MF = DAG.getMachineFunction();
1912 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1913 int ReturnAddrIndex = FuncInfo->getRAIndex();
1915 if (ReturnAddrIndex == 0) {
1916 // Set up a frame object for the return address.
1917 if (Subtarget->is64Bit())
1918 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1920 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1922 FuncInfo->setRAIndex(ReturnAddrIndex);
1925 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1930 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1931 /// specific condition code. It returns a false if it cannot do a direct
1932 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1934 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1935 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1936 SelectionDAG &DAG) {
1937 X86CC = X86::COND_INVALID;
1939 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1940 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1941 // X > -1 -> X == 0, jump !sign.
1942 RHS = DAG.getConstant(0, RHS.getValueType());
1943 X86CC = X86::COND_NS;
1945 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1946 // X < 0 -> X == 0, jump on sign.
1947 X86CC = X86::COND_S;
1949 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1951 RHS = DAG.getConstant(0, RHS.getValueType());
1952 X86CC = X86::COND_LE;
1957 switch (SetCCOpcode) {
1959 case ISD::SETEQ: X86CC = X86::COND_E; break;
1960 case ISD::SETGT: X86CC = X86::COND_G; break;
1961 case ISD::SETGE: X86CC = X86::COND_GE; break;
1962 case ISD::SETLT: X86CC = X86::COND_L; break;
1963 case ISD::SETLE: X86CC = X86::COND_LE; break;
1964 case ISD::SETNE: X86CC = X86::COND_NE; break;
1965 case ISD::SETULT: X86CC = X86::COND_B; break;
1966 case ISD::SETUGT: X86CC = X86::COND_A; break;
1967 case ISD::SETULE: X86CC = X86::COND_BE; break;
1968 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1971 // On a floating point condition, the flags are set as follows:
1973 // 0 | 0 | 0 | X > Y
1974 // 0 | 0 | 1 | X < Y
1975 // 1 | 0 | 0 | X == Y
1976 // 1 | 1 | 1 | unordered
1978 switch (SetCCOpcode) {
1981 case ISD::SETEQ: X86CC = X86::COND_E; break;
1982 case ISD::SETOLT: Flip = true; // Fallthrough
1984 case ISD::SETGT: X86CC = X86::COND_A; break;
1985 case ISD::SETOLE: Flip = true; // Fallthrough
1987 case ISD::SETGE: X86CC = X86::COND_AE; break;
1988 case ISD::SETUGT: Flip = true; // Fallthrough
1990 case ISD::SETLT: X86CC = X86::COND_B; break;
1991 case ISD::SETUGE: Flip = true; // Fallthrough
1993 case ISD::SETLE: X86CC = X86::COND_BE; break;
1995 case ISD::SETNE: X86CC = X86::COND_NE; break;
1996 case ISD::SETUO: X86CC = X86::COND_P; break;
1997 case ISD::SETO: X86CC = X86::COND_NP; break;
2000 std::swap(LHS, RHS);
2003 return X86CC != X86::COND_INVALID;
2006 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2007 /// code. Current x86 isa includes the following FP cmov instructions:
2008 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2009 static bool hasFPCMov(unsigned X86CC) {
2025 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2026 /// true if Op is undef or if its value falls within the specified range (L, H].
2027 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2028 if (Op.getOpcode() == ISD::UNDEF)
2031 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2032 return (Val >= Low && Val < Hi);
2035 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2036 /// true if Op is undef or if its value equal to the specified value.
2037 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2038 if (Op.getOpcode() == ISD::UNDEF)
2040 return cast<ConstantSDNode>(Op)->getValue() == Val;
2043 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2044 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2045 bool X86::isPSHUFDMask(SDNode *N) {
2046 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2048 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2051 // Check if the value doesn't reference the second vector.
2052 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2053 SDOperand Arg = N->getOperand(i);
2054 if (Arg.getOpcode() == ISD::UNDEF) continue;
2055 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2056 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2063 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2064 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2065 bool X86::isPSHUFHWMask(SDNode *N) {
2066 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2068 if (N->getNumOperands() != 8)
2071 // Lower quadword copied in order.
2072 for (unsigned i = 0; i != 4; ++i) {
2073 SDOperand Arg = N->getOperand(i);
2074 if (Arg.getOpcode() == ISD::UNDEF) continue;
2075 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2076 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2080 // Upper quadword shuffled.
2081 for (unsigned i = 4; i != 8; ++i) {
2082 SDOperand Arg = N->getOperand(i);
2083 if (Arg.getOpcode() == ISD::UNDEF) continue;
2084 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2085 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2086 if (Val < 4 || Val > 7)
2093 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2094 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2095 bool X86::isPSHUFLWMask(SDNode *N) {
2096 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2098 if (N->getNumOperands() != 8)
2101 // Upper quadword copied in order.
2102 for (unsigned i = 4; i != 8; ++i)
2103 if (!isUndefOrEqual(N->getOperand(i), i))
2106 // Lower quadword shuffled.
2107 for (unsigned i = 0; i != 4; ++i)
2108 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2114 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2115 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2116 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2117 if (NumElems != 2 && NumElems != 4) return false;
2119 unsigned Half = NumElems / 2;
2120 for (unsigned i = 0; i < Half; ++i)
2121 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2123 for (unsigned i = Half; i < NumElems; ++i)
2124 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2130 bool X86::isSHUFPMask(SDNode *N) {
2131 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2132 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2135 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2136 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2137 /// half elements to come from vector 1 (which would equal the dest.) and
2138 /// the upper half to come from vector 2.
2139 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2140 if (NumOps != 2 && NumOps != 4) return false;
2142 unsigned Half = NumOps / 2;
2143 for (unsigned i = 0; i < Half; ++i)
2144 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2146 for (unsigned i = Half; i < NumOps; ++i)
2147 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2152 static bool isCommutedSHUFP(SDNode *N) {
2153 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2154 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2157 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2158 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2159 bool X86::isMOVHLPSMask(SDNode *N) {
2160 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2162 if (N->getNumOperands() != 4)
2165 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2166 return isUndefOrEqual(N->getOperand(0), 6) &&
2167 isUndefOrEqual(N->getOperand(1), 7) &&
2168 isUndefOrEqual(N->getOperand(2), 2) &&
2169 isUndefOrEqual(N->getOperand(3), 3);
2172 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2173 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2175 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2176 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2178 if (N->getNumOperands() != 4)
2181 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2182 return isUndefOrEqual(N->getOperand(0), 2) &&
2183 isUndefOrEqual(N->getOperand(1), 3) &&
2184 isUndefOrEqual(N->getOperand(2), 2) &&
2185 isUndefOrEqual(N->getOperand(3), 3);
2188 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2189 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2190 bool X86::isMOVLPMask(SDNode *N) {
2191 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2193 unsigned NumElems = N->getNumOperands();
2194 if (NumElems != 2 && NumElems != 4)
2197 for (unsigned i = 0; i < NumElems/2; ++i)
2198 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2201 for (unsigned i = NumElems/2; i < NumElems; ++i)
2202 if (!isUndefOrEqual(N->getOperand(i), i))
2208 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2209 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2211 bool X86::isMOVHPMask(SDNode *N) {
2212 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2214 unsigned NumElems = N->getNumOperands();
2215 if (NumElems != 2 && NumElems != 4)
2218 for (unsigned i = 0; i < NumElems/2; ++i)
2219 if (!isUndefOrEqual(N->getOperand(i), i))
2222 for (unsigned i = 0; i < NumElems/2; ++i) {
2223 SDOperand Arg = N->getOperand(i + NumElems/2);
2224 if (!isUndefOrEqual(Arg, i + NumElems))
2231 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2232 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2233 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2234 bool V2IsSplat = false) {
2235 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2238 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2239 SDOperand BitI = Elts[i];
2240 SDOperand BitI1 = Elts[i+1];
2241 if (!isUndefOrEqual(BitI, j))
2244 if (isUndefOrEqual(BitI1, NumElts))
2247 if (!isUndefOrEqual(BitI1, j + NumElts))
2255 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2256 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2257 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2260 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2261 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2262 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2263 bool V2IsSplat = false) {
2264 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2267 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2268 SDOperand BitI = Elts[i];
2269 SDOperand BitI1 = Elts[i+1];
2270 if (!isUndefOrEqual(BitI, j + NumElts/2))
2273 if (isUndefOrEqual(BitI1, NumElts))
2276 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2284 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2285 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2286 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2289 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2290 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2292 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2293 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2295 unsigned NumElems = N->getNumOperands();
2296 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2299 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2300 SDOperand BitI = N->getOperand(i);
2301 SDOperand BitI1 = N->getOperand(i+1);
2303 if (!isUndefOrEqual(BitI, j))
2305 if (!isUndefOrEqual(BitI1, j))
2312 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2313 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2315 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2316 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2318 unsigned NumElems = N->getNumOperands();
2319 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2322 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2323 SDOperand BitI = N->getOperand(i);
2324 SDOperand BitI1 = N->getOperand(i + 1);
2326 if (!isUndefOrEqual(BitI, j))
2328 if (!isUndefOrEqual(BitI1, j))
2335 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2336 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2337 /// MOVSD, and MOVD, i.e. setting the lowest element.
2338 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2339 if (NumElts != 2 && NumElts != 4)
2342 if (!isUndefOrEqual(Elts[0], NumElts))
2345 for (unsigned i = 1; i < NumElts; ++i) {
2346 if (!isUndefOrEqual(Elts[i], i))
2353 bool X86::isMOVLMask(SDNode *N) {
2354 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2355 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2358 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2359 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2360 /// element of vector 2 and the other elements to come from vector 1 in order.
2361 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2362 bool V2IsSplat = false,
2363 bool V2IsUndef = false) {
2364 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2367 if (!isUndefOrEqual(Ops[0], 0))
2370 for (unsigned i = 1; i < NumOps; ++i) {
2371 SDOperand Arg = Ops[i];
2372 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2373 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2374 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2381 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2382 bool V2IsUndef = false) {
2383 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2384 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2385 V2IsSplat, V2IsUndef);
2388 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2389 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2390 bool X86::isMOVSHDUPMask(SDNode *N) {
2391 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2393 if (N->getNumOperands() != 4)
2396 // Expect 1, 1, 3, 3
2397 for (unsigned i = 0; i < 2; ++i) {
2398 SDOperand Arg = N->getOperand(i);
2399 if (Arg.getOpcode() == ISD::UNDEF) continue;
2400 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2401 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2402 if (Val != 1) return false;
2406 for (unsigned i = 2; i < 4; ++i) {
2407 SDOperand Arg = N->getOperand(i);
2408 if (Arg.getOpcode() == ISD::UNDEF) continue;
2409 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2410 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2411 if (Val != 3) return false;
2415 // Don't use movshdup if it can be done with a shufps.
2419 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2420 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2421 bool X86::isMOVSLDUPMask(SDNode *N) {
2422 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2424 if (N->getNumOperands() != 4)
2427 // Expect 0, 0, 2, 2
2428 for (unsigned i = 0; i < 2; ++i) {
2429 SDOperand Arg = N->getOperand(i);
2430 if (Arg.getOpcode() == ISD::UNDEF) continue;
2431 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2432 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2433 if (Val != 0) return false;
2437 for (unsigned i = 2; i < 4; ++i) {
2438 SDOperand Arg = N->getOperand(i);
2439 if (Arg.getOpcode() == ISD::UNDEF) continue;
2440 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2441 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2442 if (Val != 2) return false;
2446 // Don't use movshdup if it can be done with a shufps.
2450 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2451 /// specifies a identity operation on the LHS or RHS.
2452 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2453 unsigned NumElems = N->getNumOperands();
2454 for (unsigned i = 0; i < NumElems; ++i)
2455 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2460 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2461 /// a splat of a single element.
2462 static bool isSplatMask(SDNode *N) {
2463 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2465 // This is a splat operation if each element of the permute is the same, and
2466 // if the value doesn't reference the second vector.
2467 unsigned NumElems = N->getNumOperands();
2468 SDOperand ElementBase;
2470 for (; i != NumElems; ++i) {
2471 SDOperand Elt = N->getOperand(i);
2472 if (isa<ConstantSDNode>(Elt)) {
2478 if (!ElementBase.Val)
2481 for (; i != NumElems; ++i) {
2482 SDOperand Arg = N->getOperand(i);
2483 if (Arg.getOpcode() == ISD::UNDEF) continue;
2484 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2485 if (Arg != ElementBase) return false;
2488 // Make sure it is a splat of the first vector operand.
2489 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2492 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2493 /// a splat of a single element and it's a 2 or 4 element mask.
2494 bool X86::isSplatMask(SDNode *N) {
2495 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2497 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2498 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2500 return ::isSplatMask(N);
2503 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2504 /// specifies a splat of zero element.
2505 bool X86::isSplatLoMask(SDNode *N) {
2506 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2508 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2509 if (!isUndefOrEqual(N->getOperand(i), 0))
2514 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2515 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2517 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2518 unsigned NumOperands = N->getNumOperands();
2519 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2521 for (unsigned i = 0; i < NumOperands; ++i) {
2523 SDOperand Arg = N->getOperand(NumOperands-i-1);
2524 if (Arg.getOpcode() != ISD::UNDEF)
2525 Val = cast<ConstantSDNode>(Arg)->getValue();
2526 if (Val >= NumOperands) Val -= NumOperands;
2528 if (i != NumOperands - 1)
2535 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2536 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2538 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2540 // 8 nodes, but we only care about the last 4.
2541 for (unsigned i = 7; i >= 4; --i) {
2543 SDOperand Arg = N->getOperand(i);
2544 if (Arg.getOpcode() != ISD::UNDEF)
2545 Val = cast<ConstantSDNode>(Arg)->getValue();
2554 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2555 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2557 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2559 // 8 nodes, but we only care about the first 4.
2560 for (int i = 3; i >= 0; --i) {
2562 SDOperand Arg = N->getOperand(i);
2563 if (Arg.getOpcode() != ISD::UNDEF)
2564 Val = cast<ConstantSDNode>(Arg)->getValue();
2573 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2574 /// specifies a 8 element shuffle that can be broken into a pair of
2575 /// PSHUFHW and PSHUFLW.
2576 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2577 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2579 if (N->getNumOperands() != 8)
2582 // Lower quadword shuffled.
2583 for (unsigned i = 0; i != 4; ++i) {
2584 SDOperand Arg = N->getOperand(i);
2585 if (Arg.getOpcode() == ISD::UNDEF) continue;
2586 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2587 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2592 // Upper quadword shuffled.
2593 for (unsigned i = 4; i != 8; ++i) {
2594 SDOperand Arg = N->getOperand(i);
2595 if (Arg.getOpcode() == ISD::UNDEF) continue;
2596 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2597 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2598 if (Val < 4 || Val > 7)
2605 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2606 /// values in ther permute mask.
2607 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2608 SDOperand &V2, SDOperand &Mask,
2609 SelectionDAG &DAG) {
2610 MVT::ValueType VT = Op.getValueType();
2611 MVT::ValueType MaskVT = Mask.getValueType();
2612 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2613 unsigned NumElems = Mask.getNumOperands();
2614 SmallVector<SDOperand, 8> MaskVec;
2616 for (unsigned i = 0; i != NumElems; ++i) {
2617 SDOperand Arg = Mask.getOperand(i);
2618 if (Arg.getOpcode() == ISD::UNDEF) {
2619 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2622 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2623 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2625 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2627 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2631 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2632 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2635 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2636 /// the two vector operands have swapped position.
2638 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2639 MVT::ValueType MaskVT = Mask.getValueType();
2640 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2641 unsigned NumElems = Mask.getNumOperands();
2642 SmallVector<SDOperand, 8> MaskVec;
2643 for (unsigned i = 0; i != NumElems; ++i) {
2644 SDOperand Arg = Mask.getOperand(i);
2645 if (Arg.getOpcode() == ISD::UNDEF) {
2646 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2649 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2650 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2652 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2654 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2656 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2660 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2661 /// match movhlps. The lower half elements should come from upper half of
2662 /// V1 (and in order), and the upper half elements should come from the upper
2663 /// half of V2 (and in order).
2664 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2665 unsigned NumElems = Mask->getNumOperands();
2668 for (unsigned i = 0, e = 2; i != e; ++i)
2669 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2671 for (unsigned i = 2; i != 4; ++i)
2672 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2677 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2678 /// is promoted to a vector.
2679 static inline bool isScalarLoadToVector(SDNode *N) {
2680 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2681 N = N->getOperand(0).Val;
2682 return ISD::isNON_EXTLoad(N);
2687 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2688 /// match movlp{s|d}. The lower half elements should come from lower half of
2689 /// V1 (and in order), and the upper half elements should come from the upper
2690 /// half of V2 (and in order). And since V1 will become the source of the
2691 /// MOVLP, it must be either a vector load or a scalar load to vector.
2692 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2693 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2695 // Is V2 is a vector load, don't do this transformation. We will try to use
2696 // load folding shufps op.
2697 if (ISD::isNON_EXTLoad(V2))
2700 unsigned NumElems = Mask->getNumOperands();
2701 if (NumElems != 2 && NumElems != 4)
2703 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2704 if (!isUndefOrEqual(Mask->getOperand(i), i))
2706 for (unsigned i = NumElems/2; i != NumElems; ++i)
2707 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2712 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2714 static bool isSplatVector(SDNode *N) {
2715 if (N->getOpcode() != ISD::BUILD_VECTOR)
2718 SDOperand SplatValue = N->getOperand(0);
2719 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2720 if (N->getOperand(i) != SplatValue)
2725 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2727 static bool isUndefShuffle(SDNode *N) {
2728 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2731 SDOperand V1 = N->getOperand(0);
2732 SDOperand V2 = N->getOperand(1);
2733 SDOperand Mask = N->getOperand(2);
2734 unsigned NumElems = Mask.getNumOperands();
2735 for (unsigned i = 0; i != NumElems; ++i) {
2736 SDOperand Arg = Mask.getOperand(i);
2737 if (Arg.getOpcode() != ISD::UNDEF) {
2738 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2739 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2741 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2748 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2750 static inline bool isZeroNode(SDOperand Elt) {
2751 return ((isa<ConstantSDNode>(Elt) &&
2752 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2753 (isa<ConstantFPSDNode>(Elt) &&
2754 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2757 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2758 /// to an zero vector.
2759 static bool isZeroShuffle(SDNode *N) {
2760 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2763 SDOperand V1 = N->getOperand(0);
2764 SDOperand V2 = N->getOperand(1);
2765 SDOperand Mask = N->getOperand(2);
2766 unsigned NumElems = Mask.getNumOperands();
2767 for (unsigned i = 0; i != NumElems; ++i) {
2768 SDOperand Arg = Mask.getOperand(i);
2769 if (Arg.getOpcode() == ISD::UNDEF)
2772 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2773 if (Idx < NumElems) {
2774 unsigned Opc = V1.Val->getOpcode();
2775 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2777 if (Opc != ISD::BUILD_VECTOR ||
2778 !isZeroNode(V1.Val->getOperand(Idx)))
2780 } else if (Idx >= NumElems) {
2781 unsigned Opc = V2.Val->getOpcode();
2782 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2784 if (Opc != ISD::BUILD_VECTOR ||
2785 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2792 /// getZeroVector - Returns a vector of specified type with all zero elements.
2794 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2795 assert(MVT::isVector(VT) && "Expected a vector type");
2797 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2798 // type. This ensures they get CSE'd.
2799 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2801 if (MVT::getSizeInBits(VT) == 64) // MMX
2802 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2804 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2805 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2808 /// getOnesVector - Returns a vector of specified type with all bits set.
2810 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2811 assert(MVT::isVector(VT) && "Expected a vector type");
2813 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2814 // type. This ensures they get CSE'd.
2815 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2817 if (MVT::getSizeInBits(VT) == 64) // MMX
2818 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2820 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2821 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2825 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2826 /// that point to V2 points to its first element.
2827 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2828 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2830 bool Changed = false;
2831 SmallVector<SDOperand, 8> MaskVec;
2832 unsigned NumElems = Mask.getNumOperands();
2833 for (unsigned i = 0; i != NumElems; ++i) {
2834 SDOperand Arg = Mask.getOperand(i);
2835 if (Arg.getOpcode() != ISD::UNDEF) {
2836 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2837 if (Val > NumElems) {
2838 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2842 MaskVec.push_back(Arg);
2846 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2847 &MaskVec[0], MaskVec.size());
2851 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2852 /// operation of specified width.
2853 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2854 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2855 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2857 SmallVector<SDOperand, 8> MaskVec;
2858 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2859 for (unsigned i = 1; i != NumElems; ++i)
2860 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2861 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2864 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2865 /// of specified width.
2866 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2867 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2868 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2869 SmallVector<SDOperand, 8> MaskVec;
2870 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2871 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2872 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2874 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2877 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2878 /// of specified width.
2879 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2880 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2881 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2882 unsigned Half = NumElems/2;
2883 SmallVector<SDOperand, 8> MaskVec;
2884 for (unsigned i = 0; i != Half; ++i) {
2885 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2886 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2888 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2891 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2892 /// element #0 of a vector with the specified index, leaving the rest of the
2893 /// elements in place.
2894 static SDOperand getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2895 SelectionDAG &DAG) {
2896 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2897 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2898 SmallVector<SDOperand, 8> MaskVec;
2899 // Element #0 of the result gets the elt we are replacing.
2900 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2901 for (unsigned i = 1; i != NumElems; ++i)
2902 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2903 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2906 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2908 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2909 SDOperand V1 = Op.getOperand(0);
2910 SDOperand Mask = Op.getOperand(2);
2911 MVT::ValueType VT = Op.getValueType();
2912 unsigned NumElems = Mask.getNumOperands();
2913 Mask = getUnpacklMask(NumElems, DAG);
2914 while (NumElems != 4) {
2915 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2918 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2920 Mask = getZeroVector(MVT::v4i32, DAG);
2921 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2922 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2923 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2926 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2927 /// vector of zero or undef vector. This produces a shuffle where the low
2928 /// element of V2 is swizzled into the zero/undef vector, landing at element
2929 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2930 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, unsigned Idx,
2931 bool isZero, SelectionDAG &DAG) {
2932 MVT::ValueType VT = V2.getValueType();
2933 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2934 unsigned NumElems = MVT::getVectorNumElements(V2.getValueType());
2935 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2936 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2937 SmallVector<SDOperand, 16> MaskVec;
2938 for (unsigned i = 0; i != NumElems; ++i)
2939 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2940 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2942 MaskVec.push_back(DAG.getConstant(i, EVT));
2943 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2944 &MaskVec[0], MaskVec.size());
2945 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2948 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2950 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2951 unsigned NumNonZero, unsigned NumZero,
2952 SelectionDAG &DAG, TargetLowering &TLI) {
2958 for (unsigned i = 0; i < 16; ++i) {
2959 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2960 if (ThisIsNonZero && First) {
2962 V = getZeroVector(MVT::v8i16, DAG);
2964 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2969 SDOperand ThisElt(0, 0), LastElt(0, 0);
2970 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2971 if (LastIsNonZero) {
2972 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2974 if (ThisIsNonZero) {
2975 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2976 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2977 ThisElt, DAG.getConstant(8, MVT::i8));
2979 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2984 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2985 DAG.getIntPtrConstant(i/2));
2989 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2992 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2994 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2995 unsigned NumNonZero, unsigned NumZero,
2996 SelectionDAG &DAG, TargetLowering &TLI) {
3002 for (unsigned i = 0; i < 8; ++i) {
3003 bool isNonZero = (NonZeros & (1 << i)) != 0;
3007 V = getZeroVector(MVT::v8i16, DAG);
3009 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3012 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3013 DAG.getIntPtrConstant(i));
3021 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3022 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3023 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3024 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3025 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3026 // eliminated on x86-32 hosts.
3027 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3030 if (ISD::isBuildVectorAllOnes(Op.Val))
3031 return getOnesVector(Op.getValueType(), DAG);
3032 return getZeroVector(Op.getValueType(), DAG);
3035 MVT::ValueType VT = Op.getValueType();
3036 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3037 unsigned EVTBits = MVT::getSizeInBits(EVT);
3039 unsigned NumElems = Op.getNumOperands();
3040 unsigned NumZero = 0;
3041 unsigned NumNonZero = 0;
3042 unsigned NonZeros = 0;
3043 bool IsAllConstants = true;
3044 SmallSet<SDOperand, 8> Values;
3045 for (unsigned i = 0; i < NumElems; ++i) {
3046 SDOperand Elt = Op.getOperand(i);
3047 if (Elt.getOpcode() == ISD::UNDEF)
3050 if (Elt.getOpcode() != ISD::Constant &&
3051 Elt.getOpcode() != ISD::ConstantFP)
3052 IsAllConstants = false;
3053 if (isZeroNode(Elt))
3056 NonZeros |= (1 << i);
3061 if (NumNonZero == 0) {
3062 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3063 return DAG.getNode(ISD::UNDEF, VT);
3066 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3067 if (Values.size() == 1)
3070 // Special case for single non-zero element.
3071 if (NumNonZero == 1 && NumElems <= 4) {
3072 unsigned Idx = CountTrailingZeros_32(NonZeros);
3073 SDOperand Item = Op.getOperand(Idx);
3075 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3076 // the value are obviously zero, truncate the value to i32 and do the
3077 // insertion that way. Only do this if the value is non-constant or if the
3078 // value is a constant being inserted into element 0. It is cheaper to do
3079 // a constant pool load than it is to do a movd + shuffle.
3080 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3081 (!IsAllConstants || Idx == 0)) {
3082 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3083 // Handle MMX and SSE both.
3084 MVT::ValueType VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3085 MVT::ValueType VecElts = VT == MVT::v2i64 ? 4 : 2;
3087 // Truncate the value (which may itself be a constant) to i32, and
3088 // convert it to a vector with movd (S2V+shuffle to zero extend).
3089 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3090 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3091 Item = getShuffleVectorZeroOrUndef(Item, 0, true, DAG);
3093 // Now we have our 32-bit value zero extended in the low element of
3094 // a vector. If Idx != 0, swizzle it into place.
3097 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3098 getSwapEltZeroMask(VecElts, Idx, DAG)
3100 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3102 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3106 // If we have a constant or non-constant insertion into the low element of
3107 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3108 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3109 // depending on what the source datatype is. Because we can only get here
3110 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3112 // Don't do this for i64 values on x86-32.
3113 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3114 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3115 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3116 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3119 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3122 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3123 // is a non-constant being inserted into an element other than the low one,
3124 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3125 // movd/movss) to move this into the low element, then shuffle it into
3127 if (EVTBits == 32) {
3128 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3130 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3131 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3132 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3133 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3134 SmallVector<SDOperand, 8> MaskVec;
3135 for (unsigned i = 0; i < NumElems; i++)
3136 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3137 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3138 &MaskVec[0], MaskVec.size());
3139 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3140 DAG.getNode(ISD::UNDEF, VT), Mask);
3144 // A vector full of immediates; various special cases are already
3145 // handled, so this is best done with a single constant-pool load.
3149 // Let legalizer expand 2-wide build_vectors.
3153 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3154 if (EVTBits == 8 && NumElems == 16) {
3155 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3157 if (V.Val) return V;
3160 if (EVTBits == 16 && NumElems == 8) {
3161 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3163 if (V.Val) return V;
3166 // If element VT is == 32 bits, turn it into a number of shuffles.
3167 SmallVector<SDOperand, 8> V;
3169 if (NumElems == 4 && NumZero > 0) {
3170 for (unsigned i = 0; i < 4; ++i) {
3171 bool isZero = !(NonZeros & (1 << i));
3173 V[i] = getZeroVector(VT, DAG);
3175 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3178 for (unsigned i = 0; i < 2; ++i) {
3179 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3182 V[i] = V[i*2]; // Must be a zero vector.
3185 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3186 getMOVLMask(NumElems, DAG));
3189 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3190 getMOVLMask(NumElems, DAG));
3193 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3194 getUnpacklMask(NumElems, DAG));
3199 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3200 // clears the upper bits.
3201 // FIXME: we can do the same for v4f32 case when we know both parts of
3202 // the lower half come from scalar_to_vector (loadf32). We should do
3203 // that in post legalizer dag combiner with target specific hooks.
3204 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3206 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3207 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3208 SmallVector<SDOperand, 8> MaskVec;
3209 bool Reverse = (NonZeros & 0x3) == 2;
3210 for (unsigned i = 0; i < 2; ++i)
3212 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3214 MaskVec.push_back(DAG.getConstant(i, EVT));
3215 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3216 for (unsigned i = 0; i < 2; ++i)
3218 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3220 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3221 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3222 &MaskVec[0], MaskVec.size());
3223 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3226 if (Values.size() > 2) {
3227 // Expand into a number of unpckl*.
3229 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3230 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3231 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3232 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3233 for (unsigned i = 0; i < NumElems; ++i)
3234 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3236 while (NumElems != 0) {
3237 for (unsigned i = 0; i < NumElems; ++i)
3238 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3249 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3250 SDOperand PermMask, SelectionDAG &DAG,
3251 TargetLowering &TLI) {
3253 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3254 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3255 MVT::ValueType PtrVT = TLI.getPointerTy();
3256 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3257 PermMask.Val->op_end());
3259 // First record which half of which vector the low elements come from.
3260 SmallVector<unsigned, 4> LowQuad(4);
3261 for (unsigned i = 0; i < 4; ++i) {
3262 SDOperand Elt = MaskElts[i];
3263 if (Elt.getOpcode() == ISD::UNDEF)
3265 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3266 int QuadIdx = EltIdx / 4;
3269 int BestLowQuad = -1;
3270 unsigned MaxQuad = 1;
3271 for (unsigned i = 0; i < 4; ++i) {
3272 if (LowQuad[i] > MaxQuad) {
3274 MaxQuad = LowQuad[i];
3278 // Record which half of which vector the high elements come from.
3279 SmallVector<unsigned, 4> HighQuad(4);
3280 for (unsigned i = 4; i < 8; ++i) {
3281 SDOperand Elt = MaskElts[i];
3282 if (Elt.getOpcode() == ISD::UNDEF)
3284 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3285 int QuadIdx = EltIdx / 4;
3286 ++HighQuad[QuadIdx];
3288 int BestHighQuad = -1;
3290 for (unsigned i = 0; i < 4; ++i) {
3291 if (HighQuad[i] > MaxQuad) {
3293 MaxQuad = HighQuad[i];
3297 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3298 if (BestLowQuad != -1 || BestHighQuad != -1) {
3299 // First sort the 4 chunks in order using shufpd.
3300 SmallVector<SDOperand, 8> MaskVec;
3301 if (BestLowQuad != -1)
3302 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3304 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3305 if (BestHighQuad != -1)
3306 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3308 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3309 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3310 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3311 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3312 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3313 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3315 // Now sort high and low parts separately.
3316 BitVector InOrder(8);
3317 if (BestLowQuad != -1) {
3318 // Sort lower half in order using PSHUFLW.
3320 bool AnyOutOrder = false;
3321 for (unsigned i = 0; i != 4; ++i) {
3322 SDOperand Elt = MaskElts[i];
3323 if (Elt.getOpcode() == ISD::UNDEF) {
3324 MaskVec.push_back(Elt);
3327 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3330 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3331 // If this element is in the right place after this shuffle, then
3333 if ((int)(EltIdx / 4) == BestLowQuad)
3338 for (unsigned i = 4; i != 8; ++i)
3339 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3340 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3341 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3345 if (BestHighQuad != -1) {
3346 // Sort high half in order using PSHUFHW if possible.
3348 for (unsigned i = 0; i != 4; ++i)
3349 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3350 bool AnyOutOrder = false;
3351 for (unsigned i = 4; i != 8; ++i) {
3352 SDOperand Elt = MaskElts[i];
3353 if (Elt.getOpcode() == ISD::UNDEF) {
3354 MaskVec.push_back(Elt);
3357 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3360 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3361 // If this element is in the right place after this shuffle, then
3363 if ((int)(EltIdx / 4) == BestHighQuad)
3368 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3369 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3373 // The other elements are put in the right place using pextrw and pinsrw.
3374 for (unsigned i = 0; i != 8; ++i) {
3377 SDOperand Elt = MaskElts[i];
3378 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3381 SDOperand ExtOp = (EltIdx < 8)
3382 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3383 DAG.getConstant(EltIdx, PtrVT))
3384 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3385 DAG.getConstant(EltIdx - 8, PtrVT));
3386 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3387 DAG.getConstant(i, PtrVT));
3392 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3393 ///as few as possible.
3394 // First, let's find out how many elements are already in the right order.
3395 unsigned V1InOrder = 0;
3396 unsigned V1FromV1 = 0;
3397 unsigned V2InOrder = 0;
3398 unsigned V2FromV2 = 0;
3399 SmallVector<SDOperand, 8> V1Elts;
3400 SmallVector<SDOperand, 8> V2Elts;
3401 for (unsigned i = 0; i < 8; ++i) {
3402 SDOperand Elt = MaskElts[i];
3403 if (Elt.getOpcode() == ISD::UNDEF) {
3404 V1Elts.push_back(Elt);
3405 V2Elts.push_back(Elt);
3410 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3412 V1Elts.push_back(Elt);
3413 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3415 } else if (EltIdx == i+8) {
3416 V1Elts.push_back(Elt);
3417 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3419 } else if (EltIdx < 8) {
3420 V1Elts.push_back(Elt);
3423 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3428 if (V2InOrder > V1InOrder) {
3429 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3431 std::swap(V1Elts, V2Elts);
3432 std::swap(V1FromV1, V2FromV2);
3435 if ((V1FromV1 + V1InOrder) != 8) {
3436 // Some elements are from V2.
3438 // If there are elements that are from V1 but out of place,
3439 // then first sort them in place
3440 SmallVector<SDOperand, 8> MaskVec;
3441 for (unsigned i = 0; i < 8; ++i) {
3442 SDOperand Elt = V1Elts[i];
3443 if (Elt.getOpcode() == ISD::UNDEF) {
3444 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3447 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3449 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3451 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3453 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3454 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3458 for (unsigned i = 0; i < 8; ++i) {
3459 SDOperand Elt = V1Elts[i];
3460 if (Elt.getOpcode() == ISD::UNDEF)
3462 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3465 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3466 DAG.getConstant(EltIdx - 8, PtrVT));
3467 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3468 DAG.getConstant(i, PtrVT));
3472 // All elements are from V1.
3474 for (unsigned i = 0; i < 8; ++i) {
3475 SDOperand Elt = V1Elts[i];
3476 if (Elt.getOpcode() == ISD::UNDEF)
3478 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3479 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3480 DAG.getConstant(EltIdx, PtrVT));
3481 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3482 DAG.getConstant(i, PtrVT));
3488 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3489 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3490 /// done when every pair / quad of shuffle mask elements point to elements in
3491 /// the right sequence. e.g.
3492 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3494 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3496 SDOperand PermMask, SelectionDAG &DAG,
3497 TargetLowering &TLI) {
3498 unsigned NumElems = PermMask.getNumOperands();
3499 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3500 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3501 MVT::ValueType NewVT = MaskVT;
3503 case MVT::v4f32: NewVT = MVT::v2f64; break;
3504 case MVT::v4i32: NewVT = MVT::v2i64; break;
3505 case MVT::v8i16: NewVT = MVT::v4i32; break;
3506 case MVT::v16i8: NewVT = MVT::v4i32; break;
3507 default: assert(false && "Unexpected!");
3510 if (NewWidth == 2) {
3511 if (MVT::isInteger(VT))
3516 unsigned Scale = NumElems / NewWidth;
3517 SmallVector<SDOperand, 8> MaskVec;
3518 for (unsigned i = 0; i < NumElems; i += Scale) {
3519 unsigned StartIdx = ~0U;
3520 for (unsigned j = 0; j < Scale; ++j) {
3521 SDOperand Elt = PermMask.getOperand(i+j);
3522 if (Elt.getOpcode() == ISD::UNDEF)
3524 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3525 if (StartIdx == ~0U)
3526 StartIdx = EltIdx - (EltIdx % Scale);
3527 if (EltIdx != StartIdx + j)
3530 if (StartIdx == ~0U)
3531 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3533 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3536 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3537 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3538 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3539 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3540 &MaskVec[0], MaskVec.size()));
3544 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3545 SDOperand V1 = Op.getOperand(0);
3546 SDOperand V2 = Op.getOperand(1);
3547 SDOperand PermMask = Op.getOperand(2);
3548 MVT::ValueType VT = Op.getValueType();
3549 unsigned NumElems = PermMask.getNumOperands();
3550 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3551 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3552 bool V1IsSplat = false;
3553 bool V2IsSplat = false;
3555 if (isUndefShuffle(Op.Val))
3556 return DAG.getNode(ISD::UNDEF, VT);
3558 if (isZeroShuffle(Op.Val))
3559 return getZeroVector(VT, DAG);
3561 if (isIdentityMask(PermMask.Val))
3563 else if (isIdentityMask(PermMask.Val, true))
3566 if (isSplatMask(PermMask.Val)) {
3567 if (NumElems <= 4) return Op;
3568 // Promote it to a v4i32 splat.
3569 return PromoteSplat(Op, DAG);
3572 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3574 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3575 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3577 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3578 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3579 // FIXME: Figure out a cleaner way to do this.
3580 // Try to make use of movq to zero out the top part.
3581 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3582 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3584 SDOperand NewV1 = NewOp.getOperand(0);
3585 SDOperand NewV2 = NewOp.getOperand(1);
3586 SDOperand NewMask = NewOp.getOperand(2);
3587 if (isCommutedMOVL(NewMask.Val, true, false)) {
3588 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3589 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3590 NewV1, NewV2, getMOVLMask(2, DAG));
3591 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3594 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3595 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3596 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3597 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3601 if (X86::isMOVLMask(PermMask.Val))
3602 return (V1IsUndef) ? V2 : Op;
3604 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3605 X86::isMOVSLDUPMask(PermMask.Val) ||
3606 X86::isMOVHLPSMask(PermMask.Val) ||
3607 X86::isMOVHPMask(PermMask.Val) ||
3608 X86::isMOVLPMask(PermMask.Val))
3611 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3612 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3613 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3615 bool Commuted = false;
3616 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3617 // 1,1,1,1 -> v8i16 though.
3618 V1IsSplat = isSplatVector(V1.Val);
3619 V2IsSplat = isSplatVector(V2.Val);
3621 // Canonicalize the splat or undef, if present, to be on the RHS.
3622 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3623 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3624 std::swap(V1IsSplat, V2IsSplat);
3625 std::swap(V1IsUndef, V2IsUndef);
3629 // FIXME: Figure out a cleaner way to do this.
3630 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3631 if (V2IsUndef) return V1;
3632 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3634 // V2 is a splat, so the mask may be malformed. That is, it may point
3635 // to any V2 element. The instruction selectior won't like this. Get
3636 // a corrected mask and commute to form a proper MOVS{S|D}.
3637 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3638 if (NewMask.Val != PermMask.Val)
3639 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3644 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3645 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3646 X86::isUNPCKLMask(PermMask.Val) ||
3647 X86::isUNPCKHMask(PermMask.Val))
3651 // Normalize mask so all entries that point to V2 points to its first
3652 // element then try to match unpck{h|l} again. If match, return a
3653 // new vector_shuffle with the corrected mask.
3654 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3655 if (NewMask.Val != PermMask.Val) {
3656 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3657 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3658 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3659 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3660 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3661 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3666 // Normalize the node to match x86 shuffle ops if needed
3667 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3668 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3671 // Commute is back and try unpck* again.
3672 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3673 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3674 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3675 X86::isUNPCKLMask(PermMask.Val) ||
3676 X86::isUNPCKHMask(PermMask.Val))
3680 // If VT is integer, try PSHUF* first, then SHUFP*.
3681 if (MVT::isInteger(VT)) {
3682 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3683 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3684 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3685 X86::isPSHUFDMask(PermMask.Val)) ||
3686 X86::isPSHUFHWMask(PermMask.Val) ||
3687 X86::isPSHUFLWMask(PermMask.Val)) {
3688 if (V2.getOpcode() != ISD::UNDEF)
3689 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3690 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3694 if (X86::isSHUFPMask(PermMask.Val) &&
3695 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3698 // Floating point cases in the other order.
3699 if (X86::isSHUFPMask(PermMask.Val))
3701 if (X86::isPSHUFDMask(PermMask.Val) ||
3702 X86::isPSHUFHWMask(PermMask.Val) ||
3703 X86::isPSHUFLWMask(PermMask.Val)) {
3704 if (V2.getOpcode() != ISD::UNDEF)
3705 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3706 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3711 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3712 if (VT == MVT::v8i16) {
3713 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3718 // Handle all 4 wide cases with a number of shuffles.
3719 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3720 // Don't do this for MMX.
3721 MVT::ValueType MaskVT = PermMask.getValueType();
3722 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3723 SmallVector<std::pair<int, int>, 8> Locs;
3724 Locs.reserve(NumElems);
3725 SmallVector<SDOperand, 8> Mask1(NumElems,
3726 DAG.getNode(ISD::UNDEF, MaskEVT));
3727 SmallVector<SDOperand, 8> Mask2(NumElems,
3728 DAG.getNode(ISD::UNDEF, MaskEVT));
3731 // If no more than two elements come from either vector. This can be
3732 // implemented with two shuffles. First shuffle gather the elements.
3733 // The second shuffle, which takes the first shuffle as both of its
3734 // vector operands, put the elements into the right order.
3735 for (unsigned i = 0; i != NumElems; ++i) {
3736 SDOperand Elt = PermMask.getOperand(i);
3737 if (Elt.getOpcode() == ISD::UNDEF) {
3738 Locs[i] = std::make_pair(-1, -1);
3740 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3741 if (Val < NumElems) {
3742 Locs[i] = std::make_pair(0, NumLo);
3746 Locs[i] = std::make_pair(1, NumHi);
3747 if (2+NumHi < NumElems)
3748 Mask1[2+NumHi] = Elt;
3753 if (NumLo <= 2 && NumHi <= 2) {
3754 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3755 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3756 &Mask1[0], Mask1.size()));
3757 for (unsigned i = 0; i != NumElems; ++i) {
3758 if (Locs[i].first == -1)
3761 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3762 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3763 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3767 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3768 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3769 &Mask2[0], Mask2.size()));
3772 // Break it into (shuffle shuffle_hi, shuffle_lo).
3774 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3775 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3776 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3777 unsigned MaskIdx = 0;
3779 unsigned HiIdx = NumElems/2;
3780 for (unsigned i = 0; i != NumElems; ++i) {
3781 if (i == NumElems/2) {
3787 SDOperand Elt = PermMask.getOperand(i);
3788 if (Elt.getOpcode() == ISD::UNDEF) {
3789 Locs[i] = std::make_pair(-1, -1);
3790 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3791 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3792 (*MaskPtr)[LoIdx] = Elt;
3795 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3796 (*MaskPtr)[HiIdx] = Elt;
3801 SDOperand LoShuffle =
3802 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3803 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3804 &LoMask[0], LoMask.size()));
3805 SDOperand HiShuffle =
3806 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3807 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3808 &HiMask[0], HiMask.size()));
3809 SmallVector<SDOperand, 8> MaskOps;
3810 for (unsigned i = 0; i != NumElems; ++i) {
3811 if (Locs[i].first == -1) {
3812 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3814 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3815 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3818 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3819 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3820 &MaskOps[0], MaskOps.size()));
3827 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3828 SelectionDAG &DAG) {
3829 MVT::ValueType VT = Op.getValueType();
3830 if (MVT::getSizeInBits(VT) == 8) {
3831 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3832 Op.getOperand(0), Op.getOperand(1));
3833 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3834 DAG.getValueType(VT));
3835 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3836 } else if (MVT::getSizeInBits(VT) == 16) {
3837 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3838 Op.getOperand(0), Op.getOperand(1));
3839 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3840 DAG.getValueType(VT));
3841 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3848 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3849 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3852 if (Subtarget->hasSSE41())
3853 return LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3855 MVT::ValueType VT = Op.getValueType();
3856 // TODO: handle v16i8.
3857 if (MVT::getSizeInBits(VT) == 16) {
3858 SDOperand Vec = Op.getOperand(0);
3859 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3861 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3862 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3863 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3865 // Transform it so it match pextrw which produces a 32-bit result.
3866 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3867 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3868 Op.getOperand(0), Op.getOperand(1));
3869 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3870 DAG.getValueType(VT));
3871 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3872 } else if (MVT::getSizeInBits(VT) == 32) {
3873 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3876 // SHUFPS the element to the lowest double word, then movss.
3877 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3878 SmallVector<SDOperand, 8> IdxVec;
3880 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3882 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3884 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3886 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3887 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3888 &IdxVec[0], IdxVec.size());
3889 SDOperand Vec = Op.getOperand(0);
3890 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3891 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3892 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3893 DAG.getIntPtrConstant(0));
3894 } else if (MVT::getSizeInBits(VT) == 64) {
3895 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3896 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3897 // to match extract_elt for f64.
3898 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3902 // UNPCKHPD the element to the lowest double word, then movsd.
3903 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3904 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3905 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3906 SmallVector<SDOperand, 8> IdxVec;
3907 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3909 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3910 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3911 &IdxVec[0], IdxVec.size());
3912 SDOperand Vec = Op.getOperand(0);
3913 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3914 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3915 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3916 DAG.getIntPtrConstant(0));
3923 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3924 MVT::ValueType VT = Op.getValueType();
3925 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3927 SDOperand N0 = Op.getOperand(0);
3928 SDOperand N1 = Op.getOperand(1);
3929 SDOperand N2 = Op.getOperand(2);
3931 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3932 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3934 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3936 if (N1.getValueType() != MVT::i32)
3937 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3938 if (N2.getValueType() != MVT::i32)
3939 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3940 return DAG.getNode(Opc, VT, N0, N1, N2);
3941 } else if (EVT == MVT::f32) {
3942 // Bits [7:6] of the constant are the source select. This will always be
3943 // zero here. The DAG Combiner may combine an extract_elt index into these
3944 // bits. For example (insert (extract, 3), 2) could be matched by putting
3945 // the '3' into bits [7:6] of X86ISD::INSERTPS.
3946 // Bits [5:4] of the constant are the destination select. This is the
3947 // value of the incoming immediate.
3948 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
3949 // combine either bitwise AND or insert of float 0.0 to set these bits.
3950 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3951 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3957 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3958 MVT::ValueType VT = Op.getValueType();
3959 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3961 if (Subtarget->hasSSE41())
3962 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3967 SDOperand N0 = Op.getOperand(0);
3968 SDOperand N1 = Op.getOperand(1);
3969 SDOperand N2 = Op.getOperand(2);
3971 if (MVT::getSizeInBits(EVT) == 16) {
3972 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3973 // as its second argument.
3974 if (N1.getValueType() != MVT::i32)
3975 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3976 if (N2.getValueType() != MVT::i32)
3977 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3978 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3984 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3985 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3986 MVT::ValueType VT = MVT::v2i32;
3987 switch (Op.getValueType()) {
3994 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
3995 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
3998 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3999 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4000 // one of the above mentioned nodes. It has to be wrapped because otherwise
4001 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4002 // be used to form addressing mode. These wrapped nodes will be selected
4005 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
4006 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4007 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
4009 CP->getAlignment());
4010 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4011 // With PIC, the address is actually $g + Offset.
4012 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4013 !Subtarget->isPICStyleRIPRel()) {
4014 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4015 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4023 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4024 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4025 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4026 // If it's a debug information descriptor, don't mess with it.
4027 if (DAG.isVerifiedDebugInfoDesc(Op))
4029 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4030 // With PIC, the address is actually $g + Offset.
4031 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4032 !Subtarget->isPICStyleRIPRel()) {
4033 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4034 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4038 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4039 // load the value at address GV, not the value of GV itself. This means that
4040 // the GlobalAddress must be in the base or index register of the address, not
4041 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4042 // The same applies for external symbols during PIC codegen
4043 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4044 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4045 PseudoSourceValue::getGOT(), 0);
4050 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
4052 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4053 const MVT::ValueType PtrVT) {
4055 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4056 DAG.getNode(X86ISD::GlobalBaseReg,
4058 InFlag = Chain.getValue(1);
4060 // emit leal symbol@TLSGD(,%ebx,1), %eax
4061 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4062 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4063 GA->getValueType(0),
4065 SDOperand Ops[] = { Chain, TGA, InFlag };
4066 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4067 InFlag = Result.getValue(2);
4068 Chain = Result.getValue(1);
4070 // call ___tls_get_addr. This function receives its argument in
4071 // the register EAX.
4072 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4073 InFlag = Chain.getValue(1);
4075 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4076 SDOperand Ops1[] = { Chain,
4077 DAG.getTargetExternalSymbol("___tls_get_addr",
4079 DAG.getRegister(X86::EAX, PtrVT),
4080 DAG.getRegister(X86::EBX, PtrVT),
4082 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4083 InFlag = Chain.getValue(1);
4085 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4088 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4089 // "local exec" model.
4091 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4092 const MVT::ValueType PtrVT) {
4093 // Get the Thread Pointer
4094 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4095 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4097 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4098 GA->getValueType(0),
4100 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4102 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4103 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4104 PseudoSourceValue::getGOT(), 0);
4106 // The address of the thread local variable is the add of the thread
4107 // pointer with the offset of the variable.
4108 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4112 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4113 // TODO: implement the "local dynamic" model
4114 // TODO: implement the "initial exec"model for pic executables
4115 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4116 "TLS not implemented for non-ELF and 64-bit targets");
4117 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4118 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4119 // otherwise use the "Local Exec"TLS Model
4120 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4121 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4123 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4127 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4128 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4129 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4130 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4131 // With PIC, the address is actually $g + Offset.
4132 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4133 !Subtarget->isPICStyleRIPRel()) {
4134 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4135 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4142 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4143 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4144 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4145 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4146 // With PIC, the address is actually $g + Offset.
4147 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4148 !Subtarget->isPICStyleRIPRel()) {
4149 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4150 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4157 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4158 /// take a 2 x i32 value to shift plus a shift amount.
4159 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4160 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4161 MVT::ValueType VT = Op.getValueType();
4162 unsigned VTBits = MVT::getSizeInBits(VT);
4163 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4164 SDOperand ShOpLo = Op.getOperand(0);
4165 SDOperand ShOpHi = Op.getOperand(1);
4166 SDOperand ShAmt = Op.getOperand(2);
4167 SDOperand Tmp1 = isSRA ?
4168 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4169 DAG.getConstant(0, VT);
4171 SDOperand Tmp2, Tmp3;
4172 if (Op.getOpcode() == ISD::SHL_PARTS) {
4173 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4174 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4176 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4177 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4180 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4181 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4182 DAG.getConstant(VTBits, MVT::i8));
4183 SDOperand Cond = DAG.getNode(X86ISD::CMP, VT,
4184 AndNode, DAG.getConstant(0, MVT::i8));
4187 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4188 VTs = DAG.getNodeValueTypes(VT, MVT::Flag);
4189 SmallVector<SDOperand, 4> Ops;
4190 if (Op.getOpcode() == ISD::SHL_PARTS) {
4191 Ops.push_back(Tmp2);
4192 Ops.push_back(Tmp3);
4194 Ops.push_back(Cond);
4195 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4198 Ops.push_back(Tmp3);
4199 Ops.push_back(Tmp1);
4201 Ops.push_back(Cond);
4202 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4204 Ops.push_back(Tmp2);
4205 Ops.push_back(Tmp3);
4207 Ops.push_back(Cond);
4208 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4211 Ops.push_back(Tmp3);
4212 Ops.push_back(Tmp1);
4214 Ops.push_back(Cond);
4215 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4218 VTs = DAG.getNodeValueTypes(VT, VT);
4222 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4225 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4226 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4227 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
4228 "Unknown SINT_TO_FP to lower!");
4230 // These are really Legal; caller falls through into that case.
4231 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4233 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4234 Subtarget->is64Bit())
4237 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4238 MachineFunction &MF = DAG.getMachineFunction();
4239 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4240 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4241 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4243 PseudoSourceValue::getFixedStack(),
4248 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4250 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4252 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4253 SmallVector<SDOperand, 8> Ops;
4254 Ops.push_back(Chain);
4255 Ops.push_back(StackSlot);
4256 Ops.push_back(DAG.getValueType(SrcVT));
4257 SDOperand Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4258 Tys, &Ops[0], Ops.size());
4261 Chain = Result.getValue(1);
4262 SDOperand InFlag = Result.getValue(2);
4264 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4265 // shouldn't be necessary except that RFP cannot be live across
4266 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4267 MachineFunction &MF = DAG.getMachineFunction();
4268 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4269 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4270 Tys = DAG.getVTList(MVT::Other);
4271 SmallVector<SDOperand, 8> Ops;
4272 Ops.push_back(Chain);
4273 Ops.push_back(Result);
4274 Ops.push_back(StackSlot);
4275 Ops.push_back(DAG.getValueType(Op.getValueType()));
4276 Ops.push_back(InFlag);
4277 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4278 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4279 PseudoSourceValue::getFixedStack(), SSFI);
4285 std::pair<SDOperand,SDOperand> X86TargetLowering::
4286 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4287 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4288 "Unknown FP_TO_SINT to lower!");
4290 // These are really Legal.
4291 if (Op.getValueType() == MVT::i32 &&
4292 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4293 return std::make_pair(SDOperand(), SDOperand());
4294 if (Subtarget->is64Bit() &&
4295 Op.getValueType() == MVT::i64 &&
4296 Op.getOperand(0).getValueType() != MVT::f80)
4297 return std::make_pair(SDOperand(), SDOperand());
4299 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4301 MachineFunction &MF = DAG.getMachineFunction();
4302 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4303 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4304 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4306 switch (Op.getValueType()) {
4307 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4308 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4309 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4310 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4313 SDOperand Chain = DAG.getEntryNode();
4314 SDOperand Value = Op.getOperand(0);
4315 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4316 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4317 Chain = DAG.getStore(Chain, Value, StackSlot,
4318 PseudoSourceValue::getFixedStack(), SSFI);
4319 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4321 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4323 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4324 Chain = Value.getValue(1);
4325 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4326 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4329 // Build the FP_TO_INT*_IN_MEM
4330 SDOperand Ops[] = { Chain, Value, StackSlot };
4331 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4333 return std::make_pair(FIST, StackSlot);
4336 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4337 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4338 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4339 if (FIST.Val == 0) return SDOperand();
4342 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4345 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4346 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4347 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4348 if (FIST.Val == 0) return 0;
4350 // Return an i64 load from the stack slot.
4351 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4353 // Use a MERGE_VALUES node to drop the chain result value.
4354 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4357 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4358 MVT::ValueType VT = Op.getValueType();
4359 MVT::ValueType EltVT = VT;
4360 if (MVT::isVector(VT))
4361 EltVT = MVT::getVectorElementType(VT);
4362 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4363 std::vector<Constant*> CV;
4364 if (EltVT == MVT::f64) {
4365 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4369 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4375 Constant *C = ConstantVector::get(CV);
4376 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4377 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4378 PseudoSourceValue::getConstantPool(), 0,
4380 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4383 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4384 MVT::ValueType VT = Op.getValueType();
4385 MVT::ValueType EltVT = VT;
4386 unsigned EltNum = 1;
4387 if (MVT::isVector(VT)) {
4388 EltVT = MVT::getVectorElementType(VT);
4389 EltNum = MVT::getVectorNumElements(VT);
4391 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4392 std::vector<Constant*> CV;
4393 if (EltVT == MVT::f64) {
4394 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4398 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4404 Constant *C = ConstantVector::get(CV);
4405 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4406 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4407 PseudoSourceValue::getConstantPool(), 0,
4409 if (MVT::isVector(VT)) {
4410 return DAG.getNode(ISD::BIT_CONVERT, VT,
4411 DAG.getNode(ISD::XOR, MVT::v2i64,
4412 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4413 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4415 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4419 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4420 SDOperand Op0 = Op.getOperand(0);
4421 SDOperand Op1 = Op.getOperand(1);
4422 MVT::ValueType VT = Op.getValueType();
4423 MVT::ValueType SrcVT = Op1.getValueType();
4424 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4426 // If second operand is smaller, extend it first.
4427 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4428 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4430 SrcTy = MVT::getTypeForValueType(SrcVT);
4432 // And if it is bigger, shrink it first.
4433 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4434 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4436 SrcTy = MVT::getTypeForValueType(SrcVT);
4439 // At this point the operands and the result should have the same
4440 // type, and that won't be f80 since that is not custom lowered.
4442 // First get the sign bit of second operand.
4443 std::vector<Constant*> CV;
4444 if (SrcVT == MVT::f64) {
4445 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4446 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4448 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4449 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4450 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4451 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4453 Constant *C = ConstantVector::get(CV);
4454 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4455 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4456 PseudoSourceValue::getConstantPool(), 0,
4458 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4460 // Shift sign bit right or left if the two operands have different types.
4461 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4462 // Op0 is MVT::f32, Op1 is MVT::f64.
4463 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4464 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4465 DAG.getConstant(32, MVT::i32));
4466 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4467 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4468 DAG.getIntPtrConstant(0));
4471 // Clear first operand sign bit.
4473 if (VT == MVT::f64) {
4474 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4475 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4477 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4478 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4479 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4480 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4482 C = ConstantVector::get(CV);
4483 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4484 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4485 PseudoSourceValue::getConstantPool(), 0,
4487 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4489 // Or the value with the sign bit.
4490 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4493 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4494 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4496 SDOperand Op0 = Op.getOperand(0);
4497 SDOperand Op1 = Op.getOperand(1);
4498 SDOperand CC = Op.getOperand(2);
4499 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4500 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4503 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4505 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4506 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4507 DAG.getConstant(X86CC, MVT::i8), Cond);
4510 assert(isFP && "Illegal integer SetCC!");
4512 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4513 switch (SetCCOpcode) {
4514 default: assert(false && "Illegal floating point SetCC!");
4515 case ISD::SETOEQ: { // !PF & ZF
4516 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4517 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4518 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4519 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4520 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4522 case ISD::SETUNE: { // PF | !ZF
4523 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4524 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4525 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4526 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4527 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4533 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4534 bool addTest = true;
4535 SDOperand Cond = Op.getOperand(0);
4538 if (Cond.getOpcode() == ISD::SETCC)
4539 Cond = LowerSETCC(Cond, DAG);
4541 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4542 // setting operand in place of the X86ISD::SETCC.
4543 if (Cond.getOpcode() == X86ISD::SETCC) {
4544 CC = Cond.getOperand(0);
4546 SDOperand Cmp = Cond.getOperand(1);
4547 unsigned Opc = Cmp.getOpcode();
4548 MVT::ValueType VT = Op.getValueType();
4550 bool IllegalFPCMov = false;
4551 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4552 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4553 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4555 if ((Opc == X86ISD::CMP ||
4556 Opc == X86ISD::COMI ||
4557 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4564 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4565 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4568 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4570 SmallVector<SDOperand, 4> Ops;
4571 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4572 // condition is true.
4573 Ops.push_back(Op.getOperand(2));
4574 Ops.push_back(Op.getOperand(1));
4576 Ops.push_back(Cond);
4577 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4580 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4581 bool addTest = true;
4582 SDOperand Chain = Op.getOperand(0);
4583 SDOperand Cond = Op.getOperand(1);
4584 SDOperand Dest = Op.getOperand(2);
4587 if (Cond.getOpcode() == ISD::SETCC)
4588 Cond = LowerSETCC(Cond, DAG);
4590 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4591 // setting operand in place of the X86ISD::SETCC.
4592 if (Cond.getOpcode() == X86ISD::SETCC) {
4593 CC = Cond.getOperand(0);
4595 SDOperand Cmp = Cond.getOperand(1);
4596 unsigned Opc = Cmp.getOpcode();
4597 if (Opc == X86ISD::CMP ||
4598 Opc == X86ISD::COMI ||
4599 Opc == X86ISD::UCOMI) {
4606 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4607 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4609 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4610 Chain, Op.getOperand(2), CC, Cond);
4614 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4615 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4616 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4617 // that the guard pages used by the OS virtual memory manager are allocated in
4618 // correct sequence.
4620 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4621 SelectionDAG &DAG) {
4622 assert(Subtarget->isTargetCygMing() &&
4623 "This should be used only on Cygwin/Mingw targets");
4626 SDOperand Chain = Op.getOperand(0);
4627 SDOperand Size = Op.getOperand(1);
4628 // FIXME: Ensure alignment here
4632 MVT::ValueType IntPtr = getPointerTy();
4633 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4635 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4636 Flag = Chain.getValue(1);
4638 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4639 SDOperand Ops[] = { Chain,
4640 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4641 DAG.getRegister(X86::EAX, IntPtr),
4643 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4644 Flag = Chain.getValue(1);
4646 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4648 std::vector<MVT::ValueType> Tys;
4649 Tys.push_back(SPTy);
4650 Tys.push_back(MVT::Other);
4651 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4652 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4655 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4656 SDOperand InFlag(0, 0);
4657 SDOperand Chain = Op.getOperand(0);
4659 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4660 if (Align == 0) Align = 1;
4662 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4663 // If not DWORD aligned or size is more than the threshold, call memset.
4664 // The libc version is likely to be faster for these cases. It can use the
4665 // address value and run time information about the CPU.
4666 if ((Align & 3) != 0 ||
4667 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4668 MVT::ValueType IntPtr = getPointerTy();
4669 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4670 TargetLowering::ArgListTy Args;
4671 TargetLowering::ArgListEntry Entry;
4672 Entry.Node = Op.getOperand(1);
4673 Entry.Ty = IntPtrTy;
4674 Args.push_back(Entry);
4675 // Extend the unsigned i8 argument to be an int value for the call.
4676 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4677 Entry.Ty = IntPtrTy;
4678 Args.push_back(Entry);
4679 Entry.Node = Op.getOperand(3);
4680 Args.push_back(Entry);
4681 std::pair<SDOperand,SDOperand> CallResult =
4682 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4683 false, DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4684 return CallResult.second;
4689 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4690 unsigned BytesLeft = 0;
4691 bool TwoRepStos = false;
4694 uint64_t Val = ValC->getValue() & 255;
4696 // If the value is a constant, then we can potentially use larger sets.
4697 switch (Align & 3) {
4698 case 2: // WORD aligned
4701 Val = (Val << 8) | Val;
4703 case 0: // DWORD aligned
4706 Val = (Val << 8) | Val;
4707 Val = (Val << 16) | Val;
4708 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4711 Val = (Val << 32) | Val;
4714 default: // Byte aligned
4717 Count = Op.getOperand(3);
4721 if (AVT > MVT::i8) {
4723 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4724 Count = DAG.getIntPtrConstant(I->getValue() / UBytes);
4725 BytesLeft = I->getValue() % UBytes;
4727 assert(AVT >= MVT::i32 &&
4728 "Do not use rep;stos if not at least DWORD aligned");
4729 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4730 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4735 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4737 InFlag = Chain.getValue(1);
4740 Count = Op.getOperand(3);
4741 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4742 InFlag = Chain.getValue(1);
4745 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4747 InFlag = Chain.getValue(1);
4748 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4749 Op.getOperand(1), InFlag);
4750 InFlag = Chain.getValue(1);
4752 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4753 SmallVector<SDOperand, 8> Ops;
4754 Ops.push_back(Chain);
4755 Ops.push_back(DAG.getValueType(AVT));
4756 Ops.push_back(InFlag);
4757 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4760 InFlag = Chain.getValue(1);
4761 Count = Op.getOperand(3);
4762 MVT::ValueType CVT = Count.getValueType();
4763 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4764 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4765 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4767 InFlag = Chain.getValue(1);
4768 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4770 Ops.push_back(Chain);
4771 Ops.push_back(DAG.getValueType(MVT::i8));
4772 Ops.push_back(InFlag);
4773 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4774 } else if (BytesLeft) {
4775 // Issue stores for the last 1 - 7 bytes.
4777 unsigned Val = ValC->getValue() & 255;
4778 unsigned Offset = I->getValue() - BytesLeft;
4779 SDOperand DstAddr = Op.getOperand(1);
4780 MVT::ValueType AddrVT = DstAddr.getValueType();
4781 if (BytesLeft >= 4) {
4782 Val = (Val << 8) | Val;
4783 Val = (Val << 16) | Val;
4784 Value = DAG.getConstant(Val, MVT::i32);
4785 Chain = DAG.getStore(Chain, Value,
4786 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4787 DAG.getConstant(Offset, AddrVT)),
4792 if (BytesLeft >= 2) {
4793 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4794 Chain = DAG.getStore(Chain, Value,
4795 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4796 DAG.getConstant(Offset, AddrVT)),
4801 if (BytesLeft == 1) {
4802 Value = DAG.getConstant(Val, MVT::i8);
4803 Chain = DAG.getStore(Chain, Value,
4804 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4805 DAG.getConstant(Offset, AddrVT)),
4813 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4818 SelectionDAG &DAG) {
4820 unsigned BytesLeft = 0;
4821 switch (Align & 3) {
4822 case 2: // WORD aligned
4825 case 0: // DWORD aligned
4827 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4830 default: // Byte aligned
4835 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4836 SDOperand Count = DAG.getIntPtrConstant(Size / UBytes);
4837 BytesLeft = Size % UBytes;
4839 SDOperand InFlag(0, 0);
4840 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4842 InFlag = Chain.getValue(1);
4843 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4845 InFlag = Chain.getValue(1);
4846 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4848 InFlag = Chain.getValue(1);
4850 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4851 SmallVector<SDOperand, 8> Ops;
4852 Ops.push_back(Chain);
4853 Ops.push_back(DAG.getValueType(AVT));
4854 Ops.push_back(InFlag);
4855 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4858 // Issue loads and stores for the last 1 - 7 bytes.
4859 unsigned Offset = Size - BytesLeft;
4860 SDOperand DstAddr = Dest;
4861 MVT::ValueType DstVT = DstAddr.getValueType();
4862 SDOperand SrcAddr = Source;
4863 MVT::ValueType SrcVT = SrcAddr.getValueType();
4865 if (BytesLeft >= 4) {
4866 Value = DAG.getLoad(MVT::i32, Chain,
4867 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4868 DAG.getConstant(Offset, SrcVT)),
4870 Chain = Value.getValue(1);
4871 Chain = DAG.getStore(Chain, Value,
4872 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4873 DAG.getConstant(Offset, DstVT)),
4878 if (BytesLeft >= 2) {
4879 Value = DAG.getLoad(MVT::i16, Chain,
4880 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4881 DAG.getConstant(Offset, SrcVT)),
4883 Chain = Value.getValue(1);
4884 Chain = DAG.getStore(Chain, Value,
4885 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4886 DAG.getConstant(Offset, DstVT)),
4892 if (BytesLeft == 1) {
4893 Value = DAG.getLoad(MVT::i8, Chain,
4894 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4895 DAG.getConstant(Offset, SrcVT)),
4897 Chain = Value.getValue(1);
4898 Chain = DAG.getStore(Chain, Value,
4899 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4900 DAG.getConstant(Offset, DstVT)),
4908 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4909 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4910 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4911 SDOperand TheChain = N->getOperand(0);
4912 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4913 if (Subtarget->is64Bit()) {
4914 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4915 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4916 MVT::i64, rax.getValue(2));
4917 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4918 DAG.getConstant(32, MVT::i8));
4920 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4923 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4924 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4927 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4928 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4929 MVT::i32, eax.getValue(2));
4930 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4931 SDOperand Ops[] = { eax, edx };
4932 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4934 // Use a MERGE_VALUES to return the value and chain.
4935 Ops[1] = edx.getValue(1);
4936 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4937 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4940 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4941 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4943 if (!Subtarget->is64Bit()) {
4944 // vastart just stores the address of the VarArgsFrameIndex slot into the
4945 // memory location argument.
4946 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4947 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4951 // gp_offset (0 - 6 * 8)
4952 // fp_offset (48 - 48 + 8 * 16)
4953 // overflow_arg_area (point to parameters coming in memory).
4955 SmallVector<SDOperand, 8> MemOps;
4956 SDOperand FIN = Op.getOperand(1);
4958 SDOperand Store = DAG.getStore(Op.getOperand(0),
4959 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4961 MemOps.push_back(Store);
4964 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4965 Store = DAG.getStore(Op.getOperand(0),
4966 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4968 MemOps.push_back(Store);
4970 // Store ptr to overflow_arg_area
4971 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4972 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4973 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4974 MemOps.push_back(Store);
4976 // Store ptr to reg_save_area.
4977 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4978 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4979 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4980 MemOps.push_back(Store);
4981 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4984 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4985 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4986 SDOperand Chain = Op.getOperand(0);
4987 SDOperand DstPtr = Op.getOperand(1);
4988 SDOperand SrcPtr = Op.getOperand(2);
4989 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4990 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4992 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr, SrcSV, 0);
4993 Chain = SrcPtr.getValue(1);
4994 for (unsigned i = 0; i < 3; ++i) {
4995 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr, SrcSV, 0);
4996 Chain = Val.getValue(1);
4997 Chain = DAG.getStore(Chain, Val, DstPtr, DstSV, 0);
5000 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
5001 DAG.getIntPtrConstant(8));
5002 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
5003 DAG.getIntPtrConstant(8));
5009 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5010 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5012 default: return SDOperand(); // Don't custom lower most intrinsics.
5013 // Comparison intrinsics.
5014 case Intrinsic::x86_sse_comieq_ss:
5015 case Intrinsic::x86_sse_comilt_ss:
5016 case Intrinsic::x86_sse_comile_ss:
5017 case Intrinsic::x86_sse_comigt_ss:
5018 case Intrinsic::x86_sse_comige_ss:
5019 case Intrinsic::x86_sse_comineq_ss:
5020 case Intrinsic::x86_sse_ucomieq_ss:
5021 case Intrinsic::x86_sse_ucomilt_ss:
5022 case Intrinsic::x86_sse_ucomile_ss:
5023 case Intrinsic::x86_sse_ucomigt_ss:
5024 case Intrinsic::x86_sse_ucomige_ss:
5025 case Intrinsic::x86_sse_ucomineq_ss:
5026 case Intrinsic::x86_sse2_comieq_sd:
5027 case Intrinsic::x86_sse2_comilt_sd:
5028 case Intrinsic::x86_sse2_comile_sd:
5029 case Intrinsic::x86_sse2_comigt_sd:
5030 case Intrinsic::x86_sse2_comige_sd:
5031 case Intrinsic::x86_sse2_comineq_sd:
5032 case Intrinsic::x86_sse2_ucomieq_sd:
5033 case Intrinsic::x86_sse2_ucomilt_sd:
5034 case Intrinsic::x86_sse2_ucomile_sd:
5035 case Intrinsic::x86_sse2_ucomigt_sd:
5036 case Intrinsic::x86_sse2_ucomige_sd:
5037 case Intrinsic::x86_sse2_ucomineq_sd: {
5039 ISD::CondCode CC = ISD::SETCC_INVALID;
5042 case Intrinsic::x86_sse_comieq_ss:
5043 case Intrinsic::x86_sse2_comieq_sd:
5047 case Intrinsic::x86_sse_comilt_ss:
5048 case Intrinsic::x86_sse2_comilt_sd:
5052 case Intrinsic::x86_sse_comile_ss:
5053 case Intrinsic::x86_sse2_comile_sd:
5057 case Intrinsic::x86_sse_comigt_ss:
5058 case Intrinsic::x86_sse2_comigt_sd:
5062 case Intrinsic::x86_sse_comige_ss:
5063 case Intrinsic::x86_sse2_comige_sd:
5067 case Intrinsic::x86_sse_comineq_ss:
5068 case Intrinsic::x86_sse2_comineq_sd:
5072 case Intrinsic::x86_sse_ucomieq_ss:
5073 case Intrinsic::x86_sse2_ucomieq_sd:
5074 Opc = X86ISD::UCOMI;
5077 case Intrinsic::x86_sse_ucomilt_ss:
5078 case Intrinsic::x86_sse2_ucomilt_sd:
5079 Opc = X86ISD::UCOMI;
5082 case Intrinsic::x86_sse_ucomile_ss:
5083 case Intrinsic::x86_sse2_ucomile_sd:
5084 Opc = X86ISD::UCOMI;
5087 case Intrinsic::x86_sse_ucomigt_ss:
5088 case Intrinsic::x86_sse2_ucomigt_sd:
5089 Opc = X86ISD::UCOMI;
5092 case Intrinsic::x86_sse_ucomige_ss:
5093 case Intrinsic::x86_sse2_ucomige_sd:
5094 Opc = X86ISD::UCOMI;
5097 case Intrinsic::x86_sse_ucomineq_ss:
5098 case Intrinsic::x86_sse2_ucomineq_sd:
5099 Opc = X86ISD::UCOMI;
5105 SDOperand LHS = Op.getOperand(1);
5106 SDOperand RHS = Op.getOperand(2);
5107 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5109 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5110 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5111 DAG.getConstant(X86CC, MVT::i8), Cond);
5112 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5117 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5118 // Depths > 0 not supported yet!
5119 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5122 // Just load the return address
5123 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5124 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5127 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5128 // Depths > 0 not supported yet!
5129 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5132 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5133 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5134 DAG.getIntPtrConstant(4));
5137 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5138 SelectionDAG &DAG) {
5139 // Is not yet supported on x86-64
5140 if (Subtarget->is64Bit())
5143 return DAG.getIntPtrConstant(8);
5146 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5148 assert(!Subtarget->is64Bit() &&
5149 "Lowering of eh_return builtin is not supported yet on x86-64");
5151 MachineFunction &MF = DAG.getMachineFunction();
5152 SDOperand Chain = Op.getOperand(0);
5153 SDOperand Offset = Op.getOperand(1);
5154 SDOperand Handler = Op.getOperand(2);
5156 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5159 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5160 DAG.getIntPtrConstant(-4UL));
5161 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5162 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5163 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5164 MF.getRegInfo().addLiveOut(X86::ECX);
5166 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5167 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5170 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5171 SelectionDAG &DAG) {
5172 SDOperand Root = Op.getOperand(0);
5173 SDOperand Trmp = Op.getOperand(1); // trampoline
5174 SDOperand FPtr = Op.getOperand(2); // nested function
5175 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5177 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5179 const X86InstrInfo *TII =
5180 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5182 if (Subtarget->is64Bit()) {
5183 SDOperand OutChains[6];
5185 // Large code-model.
5187 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5188 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5190 const unsigned char N86R10 =
5191 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5192 const unsigned char N86R11 =
5193 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5195 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5197 // Load the pointer to the nested function into R11.
5198 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5199 SDOperand Addr = Trmp;
5200 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5203 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5204 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5206 // Load the 'nest' parameter value into R10.
5207 // R10 is specified in X86CallingConv.td
5208 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5209 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5210 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5213 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5214 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5216 // Jump to the nested function.
5217 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5218 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5219 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5222 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5223 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5224 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5228 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5229 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5231 const Function *Func =
5232 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5233 unsigned CC = Func->getCallingConv();
5238 assert(0 && "Unsupported calling convention");
5239 case CallingConv::C:
5240 case CallingConv::X86_StdCall: {
5241 // Pass 'nest' parameter in ECX.
5242 // Must be kept in sync with X86CallingConv.td
5245 // Check that ECX wasn't needed by an 'inreg' parameter.
5246 const FunctionType *FTy = Func->getFunctionType();
5247 const ParamAttrsList *Attrs = Func->getParamAttrs();
5249 if (Attrs && !Func->isVarArg()) {
5250 unsigned InRegCount = 0;
5253 for (FunctionType::param_iterator I = FTy->param_begin(),
5254 E = FTy->param_end(); I != E; ++I, ++Idx)
5255 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5256 // FIXME: should only count parameters that are lowered to integers.
5257 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5259 if (InRegCount > 2) {
5260 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5266 case CallingConv::X86_FastCall:
5267 // Pass 'nest' parameter in EAX.
5268 // Must be kept in sync with X86CallingConv.td
5273 SDOperand OutChains[4];
5274 SDOperand Addr, Disp;
5276 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5277 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5279 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5280 const unsigned char N86Reg =
5281 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5282 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5285 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5286 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5288 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5289 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5290 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5291 TrmpAddr, 5, false, 1);
5293 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5294 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5297 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5298 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5302 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5304 The rounding mode is in bits 11:10 of FPSR, and has the following
5311 FLT_ROUNDS, on the other hand, expects the following:
5318 To perform the conversion, we do:
5319 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5322 MachineFunction &MF = DAG.getMachineFunction();
5323 const TargetMachine &TM = MF.getTarget();
5324 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5325 unsigned StackAlignment = TFI.getStackAlignment();
5326 MVT::ValueType VT = Op.getValueType();
5328 // Save FP Control Word to stack slot
5329 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5330 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5332 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5333 DAG.getEntryNode(), StackSlot);
5335 // Load FP Control Word from stack slot
5336 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5338 // Transform as necessary
5340 DAG.getNode(ISD::SRL, MVT::i16,
5341 DAG.getNode(ISD::AND, MVT::i16,
5342 CWD, DAG.getConstant(0x800, MVT::i16)),
5343 DAG.getConstant(11, MVT::i8));
5345 DAG.getNode(ISD::SRL, MVT::i16,
5346 DAG.getNode(ISD::AND, MVT::i16,
5347 CWD, DAG.getConstant(0x400, MVT::i16)),
5348 DAG.getConstant(9, MVT::i8));
5351 DAG.getNode(ISD::AND, MVT::i16,
5352 DAG.getNode(ISD::ADD, MVT::i16,
5353 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5354 DAG.getConstant(1, MVT::i16)),
5355 DAG.getConstant(3, MVT::i16));
5358 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5359 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5362 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5363 MVT::ValueType VT = Op.getValueType();
5364 MVT::ValueType OpVT = VT;
5365 unsigned NumBits = MVT::getSizeInBits(VT);
5367 Op = Op.getOperand(0);
5368 if (VT == MVT::i8) {
5369 // Zero extend to i32 since there is not an i8 bsr.
5371 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5374 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5375 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5376 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5378 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5379 SmallVector<SDOperand, 4> Ops;
5381 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5382 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5383 Ops.push_back(Op.getValue(1));
5384 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5386 // Finally xor with NumBits-1.
5387 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5390 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5394 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5395 MVT::ValueType VT = Op.getValueType();
5396 MVT::ValueType OpVT = VT;
5397 unsigned NumBits = MVT::getSizeInBits(VT);
5399 Op = Op.getOperand(0);
5400 if (VT == MVT::i8) {
5402 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5405 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5406 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5407 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5409 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5410 SmallVector<SDOperand, 4> Ops;
5412 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5413 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5414 Ops.push_back(Op.getValue(1));
5415 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5418 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5422 SDOperand X86TargetLowering::LowerLCS(SDOperand Op, SelectionDAG &DAG) {
5423 MVT::ValueType T = cast<AtomicSDNode>(Op.Val)->getVT();
5427 case MVT::i8: Reg = X86::AL; size = 1; break;
5428 case MVT::i16: Reg = X86::AX; size = 2; break;
5429 case MVT::i32: Reg = X86::EAX; size = 4; break;
5431 if (Subtarget->is64Bit()) {
5432 Reg = X86::RAX; size = 8;
5433 } else //Should go away when LowerType stuff lands
5434 return SDOperand(ExpandATOMIC_LCS(Op.Val, DAG), 0);
5437 SDOperand cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5438 Op.getOperand(3), SDOperand());
5439 SDOperand Ops[] = { cpIn.getValue(0),
5442 DAG.getTargetConstant(size, MVT::i8),
5444 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5445 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5447 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5451 SDNode* X86TargetLowering::ExpandATOMIC_LCS(SDNode* Op, SelectionDAG &DAG) {
5452 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5453 assert (T == MVT::i64 && "Only know how to expand i64 CAS");
5454 SDOperand cpInL, cpInH;
5455 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5456 DAG.getConstant(0, MVT::i32));
5457 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5458 DAG.getConstant(1, MVT::i32));
5459 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5460 cpInL, SDOperand());
5461 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5462 cpInH, cpInL.getValue(1));
5463 SDOperand swapInL, swapInH;
5464 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5465 DAG.getConstant(0, MVT::i32));
5466 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5467 DAG.getConstant(1, MVT::i32));
5468 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5469 swapInL, cpInH.getValue(1));
5470 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5471 swapInH, swapInL.getValue(1));
5472 SDOperand Ops[] = { swapInH.getValue(0),
5474 swapInH.getValue(1)};
5475 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5476 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5477 SDOperand cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5478 Result.getValue(1));
5479 SDOperand cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5480 cpOutL.getValue(2));
5481 SDOperand OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5482 SDOperand ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5483 Tys = DAG.getVTList(MVT::i64, MVT::Other);
5484 return DAG.getNode(ISD::MERGE_VALUES, Tys, ResultVal, cpOutH.getValue(1)).Val;
5487 /// LowerOperation - Provide custom lowering hooks for some operations.
5489 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5490 switch (Op.getOpcode()) {
5491 default: assert(0 && "Should not custom lower this!");
5492 case ISD::ATOMIC_LCS: return LowerLCS(Op,DAG);
5493 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5494 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5495 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5496 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5497 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5498 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5499 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5500 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5501 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5502 case ISD::SHL_PARTS:
5503 case ISD::SRA_PARTS:
5504 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5505 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5506 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5507 case ISD::FABS: return LowerFABS(Op, DAG);
5508 case ISD::FNEG: return LowerFNEG(Op, DAG);
5509 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5510 case ISD::SETCC: return LowerSETCC(Op, DAG);
5511 case ISD::SELECT: return LowerSELECT(Op, DAG);
5512 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5513 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5514 case ISD::CALL: return LowerCALL(Op, DAG);
5515 case ISD::RET: return LowerRET(Op, DAG);
5516 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5517 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5518 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
5519 case ISD::VASTART: return LowerVASTART(Op, DAG);
5520 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5521 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5522 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5523 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5524 case ISD::FRAME_TO_ARGS_OFFSET:
5525 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5526 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5527 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5528 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5529 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5530 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5531 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5533 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5534 case ISD::READCYCLECOUNTER:
5535 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5539 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5540 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5541 switch (N->getOpcode()) {
5542 default: assert(0 && "Should not custom lower this!");
5543 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5544 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5545 case ISD::ATOMIC_LCS: return ExpandATOMIC_LCS(N, DAG);
5549 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5551 default: return NULL;
5552 case X86ISD::BSF: return "X86ISD::BSF";
5553 case X86ISD::BSR: return "X86ISD::BSR";
5554 case X86ISD::SHLD: return "X86ISD::SHLD";
5555 case X86ISD::SHRD: return "X86ISD::SHRD";
5556 case X86ISD::FAND: return "X86ISD::FAND";
5557 case X86ISD::FOR: return "X86ISD::FOR";
5558 case X86ISD::FXOR: return "X86ISD::FXOR";
5559 case X86ISD::FSRL: return "X86ISD::FSRL";
5560 case X86ISD::FILD: return "X86ISD::FILD";
5561 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5562 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5563 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5564 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5565 case X86ISD::FLD: return "X86ISD::FLD";
5566 case X86ISD::FST: return "X86ISD::FST";
5567 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5568 case X86ISD::FP_GET_RESULT2: return "X86ISD::FP_GET_RESULT2";
5569 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5570 case X86ISD::CALL: return "X86ISD::CALL";
5571 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5572 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5573 case X86ISD::CMP: return "X86ISD::CMP";
5574 case X86ISD::COMI: return "X86ISD::COMI";
5575 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5576 case X86ISD::SETCC: return "X86ISD::SETCC";
5577 case X86ISD::CMOV: return "X86ISD::CMOV";
5578 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5579 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5580 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5581 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5582 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5583 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5584 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5585 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5586 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5587 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5588 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5589 case X86ISD::FMAX: return "X86ISD::FMAX";
5590 case X86ISD::FMIN: return "X86ISD::FMIN";
5591 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5592 case X86ISD::FRCP: return "X86ISD::FRCP";
5593 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5594 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5595 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5596 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5597 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5598 case X86ISD::LCMPXCHG_DAG: return "x86ISD::LCMPXCHG_DAG";
5599 case X86ISD::LCMPXCHG8_DAG: return "x86ISD::LCMPXCHG8_DAG";
5603 // isLegalAddressingMode - Return true if the addressing mode represented
5604 // by AM is legal for this target, for a load/store of the specified type.
5605 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5606 const Type *Ty) const {
5607 // X86 supports extremely general addressing modes.
5609 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5610 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5614 // We can only fold this if we don't need an extra load.
5615 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5618 // X86-64 only supports addr of globals in small code model.
5619 if (Subtarget->is64Bit()) {
5620 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5622 // If lower 4G is not available, then we must use rip-relative addressing.
5623 if (AM.BaseOffs || AM.Scale > 1)
5634 // These scales always work.
5639 // These scales are formed with basereg+scalereg. Only accept if there is
5644 default: // Other stuff never works.
5652 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5653 if (!Ty1->isInteger() || !Ty2->isInteger())
5655 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5656 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5657 if (NumBits1 <= NumBits2)
5659 return Subtarget->is64Bit() || NumBits1 < 64;
5662 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5663 MVT::ValueType VT2) const {
5664 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5666 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5667 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5668 if (NumBits1 <= NumBits2)
5670 return Subtarget->is64Bit() || NumBits1 < 64;
5673 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5674 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5675 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5676 /// are assumed to be legal.
5678 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5679 // Only do shuffles on 128-bit vector types for now.
5680 if (MVT::getSizeInBits(VT) == 64) return false;
5681 return (Mask.Val->getNumOperands() <= 4 ||
5682 isIdentityMask(Mask.Val) ||
5683 isIdentityMask(Mask.Val, true) ||
5684 isSplatMask(Mask.Val) ||
5685 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5686 X86::isUNPCKLMask(Mask.Val) ||
5687 X86::isUNPCKHMask(Mask.Val) ||
5688 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5689 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5692 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5694 SelectionDAG &DAG) const {
5695 unsigned NumElts = BVOps.size();
5696 // Only do shuffles on 128-bit vector types for now.
5697 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5698 if (NumElts == 2) return true;
5700 return (isMOVLMask(&BVOps[0], 4) ||
5701 isCommutedMOVL(&BVOps[0], 4, true) ||
5702 isSHUFPMask(&BVOps[0], 4) ||
5703 isCommutedSHUFP(&BVOps[0], 4));
5708 //===----------------------------------------------------------------------===//
5709 // X86 Scheduler Hooks
5710 //===----------------------------------------------------------------------===//
5713 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5714 MachineBasicBlock *BB) {
5715 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5716 switch (MI->getOpcode()) {
5717 default: assert(false && "Unexpected instr type to insert");
5718 case X86::CMOV_FR32:
5719 case X86::CMOV_FR64:
5720 case X86::CMOV_V4F32:
5721 case X86::CMOV_V2F64:
5722 case X86::CMOV_V2I64: {
5723 // To "insert" a SELECT_CC instruction, we actually have to insert the
5724 // diamond control-flow pattern. The incoming instruction knows the
5725 // destination vreg to set, the condition code register to branch on, the
5726 // true/false values to select between, and a branch opcode to use.
5727 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5728 ilist<MachineBasicBlock>::iterator It = BB;
5734 // cmpTY ccX, r1, r2
5736 // fallthrough --> copy0MBB
5737 MachineBasicBlock *thisMBB = BB;
5738 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5739 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5741 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5742 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5743 MachineFunction *F = BB->getParent();
5744 F->getBasicBlockList().insert(It, copy0MBB);
5745 F->getBasicBlockList().insert(It, sinkMBB);
5746 // Update machine-CFG edges by first adding all successors of the current
5747 // block to the new block which will contain the Phi node for the select.
5748 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5749 e = BB->succ_end(); i != e; ++i)
5750 sinkMBB->addSuccessor(*i);
5751 // Next, remove all successors of the current block, and add the true
5752 // and fallthrough blocks as its successors.
5753 while(!BB->succ_empty())
5754 BB->removeSuccessor(BB->succ_begin());
5755 BB->addSuccessor(copy0MBB);
5756 BB->addSuccessor(sinkMBB);
5759 // %FalseValue = ...
5760 // # fallthrough to sinkMBB
5763 // Update machine-CFG edges
5764 BB->addSuccessor(sinkMBB);
5767 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5770 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5771 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5772 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5774 delete MI; // The pseudo instruction is gone now.
5778 case X86::FP32_TO_INT16_IN_MEM:
5779 case X86::FP32_TO_INT32_IN_MEM:
5780 case X86::FP32_TO_INT64_IN_MEM:
5781 case X86::FP64_TO_INT16_IN_MEM:
5782 case X86::FP64_TO_INT32_IN_MEM:
5783 case X86::FP64_TO_INT64_IN_MEM:
5784 case X86::FP80_TO_INT16_IN_MEM:
5785 case X86::FP80_TO_INT32_IN_MEM:
5786 case X86::FP80_TO_INT64_IN_MEM: {
5787 // Change the floating point control register to use "round towards zero"
5788 // mode when truncating to an integer value.
5789 MachineFunction *F = BB->getParent();
5790 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5791 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5793 // Load the old value of the high byte of the control word...
5795 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5796 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5798 // Set the high part to be round to zero...
5799 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5802 // Reload the modified control word now...
5803 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5805 // Restore the memory image of control word to original value
5806 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5809 // Get the X86 opcode to use.
5811 switch (MI->getOpcode()) {
5812 default: assert(0 && "illegal opcode!");
5813 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5814 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5815 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5816 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5817 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5818 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5819 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5820 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5821 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5825 MachineOperand &Op = MI->getOperand(0);
5826 if (Op.isRegister()) {
5827 AM.BaseType = X86AddressMode::RegBase;
5828 AM.Base.Reg = Op.getReg();
5830 AM.BaseType = X86AddressMode::FrameIndexBase;
5831 AM.Base.FrameIndex = Op.getIndex();
5833 Op = MI->getOperand(1);
5834 if (Op.isImmediate())
5835 AM.Scale = Op.getImm();
5836 Op = MI->getOperand(2);
5837 if (Op.isImmediate())
5838 AM.IndexReg = Op.getImm();
5839 Op = MI->getOperand(3);
5840 if (Op.isGlobalAddress()) {
5841 AM.GV = Op.getGlobal();
5843 AM.Disp = Op.getImm();
5845 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5846 .addReg(MI->getOperand(4).getReg());
5848 // Reload the original control word now.
5849 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5851 delete MI; // The pseudo instruction is gone now.
5857 //===----------------------------------------------------------------------===//
5858 // X86 Optimization Hooks
5859 //===----------------------------------------------------------------------===//
5861 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5865 const SelectionDAG &DAG,
5866 unsigned Depth) const {
5867 unsigned Opc = Op.getOpcode();
5868 assert((Opc >= ISD::BUILTIN_OP_END ||
5869 Opc == ISD::INTRINSIC_WO_CHAIN ||
5870 Opc == ISD::INTRINSIC_W_CHAIN ||
5871 Opc == ISD::INTRINSIC_VOID) &&
5872 "Should use MaskedValueIsZero if you don't know whether Op"
5873 " is a target node!");
5875 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
5879 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
5880 Mask.getBitWidth() - 1);
5885 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5886 /// element of the result of the vector shuffle.
5887 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5888 MVT::ValueType VT = N->getValueType(0);
5889 SDOperand PermMask = N->getOperand(2);
5890 unsigned NumElems = PermMask.getNumOperands();
5891 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5893 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5895 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5896 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5897 SDOperand Idx = PermMask.getOperand(i);
5898 if (Idx.getOpcode() == ISD::UNDEF)
5899 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5900 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5905 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5906 /// node is a GlobalAddress + an offset.
5907 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5908 unsigned Opc = N->getOpcode();
5909 if (Opc == X86ISD::Wrapper) {
5910 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5911 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5914 } else if (Opc == ISD::ADD) {
5915 SDOperand N1 = N->getOperand(0);
5916 SDOperand N2 = N->getOperand(1);
5917 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5918 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5920 Offset += V->getSignExtended();
5923 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5924 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5926 Offset += V->getSignExtended();
5934 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5936 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5937 MachineFrameInfo *MFI) {
5938 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5941 SDOperand Loc = N->getOperand(1);
5942 SDOperand BaseLoc = Base->getOperand(1);
5943 if (Loc.getOpcode() == ISD::FrameIndex) {
5944 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5946 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5947 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5948 int FS = MFI->getObjectSize(FI);
5949 int BFS = MFI->getObjectSize(BFI);
5950 if (FS != BFS || FS != Size) return false;
5951 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5953 GlobalValue *GV1 = NULL;
5954 GlobalValue *GV2 = NULL;
5955 int64_t Offset1 = 0;
5956 int64_t Offset2 = 0;
5957 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5958 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5959 if (isGA1 && isGA2 && GV1 == GV2)
5960 return Offset1 == (Offset2 + Dist*Size);
5966 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5967 const X86Subtarget *Subtarget) {
5970 if (isGAPlusOffset(Base, GV, Offset))
5971 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5972 // DAG combine handles the stack object case.
5977 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5978 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5979 /// if the load addresses are consecutive, non-overlapping, and in the right
5981 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5982 const X86Subtarget *Subtarget) {
5983 MachineFunction &MF = DAG.getMachineFunction();
5984 MachineFrameInfo *MFI = MF.getFrameInfo();
5985 MVT::ValueType VT = N->getValueType(0);
5986 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5987 SDOperand PermMask = N->getOperand(2);
5988 int NumElems = (int)PermMask.getNumOperands();
5989 SDNode *Base = NULL;
5990 for (int i = 0; i < NumElems; ++i) {
5991 SDOperand Idx = PermMask.getOperand(i);
5992 if (Idx.getOpcode() == ISD::UNDEF) {
5993 if (!Base) return SDOperand();
5996 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5997 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
6001 else if (!isConsecutiveLoad(Arg.Val, Base,
6002 i, MVT::getSizeInBits(EVT)/8,MFI))
6007 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
6008 LoadSDNode *LD = cast<LoadSDNode>(Base);
6010 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6011 LD->getSrcValueOffset(), LD->isVolatile());
6013 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6014 LD->getSrcValueOffset(), LD->isVolatile(),
6015 LD->getAlignment());
6019 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6020 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6021 const X86Subtarget *Subtarget) {
6022 SDOperand Cond = N->getOperand(0);
6024 // If we have SSE[12] support, try to form min/max nodes.
6025 if (Subtarget->hasSSE2() &&
6026 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6027 if (Cond.getOpcode() == ISD::SETCC) {
6028 // Get the LHS/RHS of the select.
6029 SDOperand LHS = N->getOperand(1);
6030 SDOperand RHS = N->getOperand(2);
6031 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6033 unsigned Opcode = 0;
6034 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6037 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6040 if (!UnsafeFPMath) break;
6042 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6044 Opcode = X86ISD::FMIN;
6047 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6050 if (!UnsafeFPMath) break;
6052 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6054 Opcode = X86ISD::FMAX;
6057 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6060 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6063 if (!UnsafeFPMath) break;
6065 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6067 Opcode = X86ISD::FMIN;
6070 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6073 if (!UnsafeFPMath) break;
6075 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6077 Opcode = X86ISD::FMAX;
6083 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6091 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6092 static SDOperand PerformSTORECombine(StoreSDNode *St, SelectionDAG &DAG,
6093 const X86Subtarget *Subtarget) {
6094 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
6095 // the FP state in cases where an emms may be missing.
6096 // A preferable solution to the general problem is to figure out the right
6097 // places to insert EMMS. This qualifies as a quick hack.
6098 if (MVT::isVector(St->getValue().getValueType()) &&
6099 MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
6100 isa<LoadSDNode>(St->getValue()) &&
6101 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6102 St->getChain().hasOneUse() && !St->isVolatile()) {
6103 SDNode* LdVal = St->getValue().Val;
6105 int TokenFactorIndex = -1;
6106 SmallVector<SDOperand, 8> Ops;
6107 SDNode* ChainVal = St->getChain().Val;
6108 // Must be a store of a load. We currently handle two cases: the load
6109 // is a direct child, and it's under an intervening TokenFactor. It is
6110 // possible to dig deeper under nested TokenFactors.
6111 if (ChainVal == LdVal)
6112 Ld = cast<LoadSDNode>(St->getChain());
6113 else if (St->getValue().hasOneUse() &&
6114 ChainVal->getOpcode() == ISD::TokenFactor) {
6115 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6116 if (ChainVal->getOperand(i).Val == LdVal) {
6117 TokenFactorIndex = i;
6118 Ld = cast<LoadSDNode>(St->getValue());
6120 Ops.push_back(ChainVal->getOperand(i));
6124 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6125 if (Subtarget->is64Bit()) {
6126 SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6127 Ld->getBasePtr(), Ld->getSrcValue(),
6128 Ld->getSrcValueOffset(), Ld->isVolatile(),
6129 Ld->getAlignment());
6130 SDOperand NewChain = NewLd.getValue(1);
6131 if (TokenFactorIndex != -1) {
6132 Ops.push_back(NewLd);
6133 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6136 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6137 St->getSrcValue(), St->getSrcValueOffset(),
6138 St->isVolatile(), St->getAlignment());
6141 // Otherwise, lower to two 32-bit copies.
6142 SDOperand LoAddr = Ld->getBasePtr();
6143 SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6144 DAG.getConstant(MVT::i32, 4));
6146 SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6147 Ld->getSrcValue(), Ld->getSrcValueOffset(),
6148 Ld->isVolatile(), Ld->getAlignment());
6149 SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6150 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6152 MinAlign(Ld->getAlignment(), 4));
6154 SDOperand NewChain = LoLd.getValue(1);
6155 if (TokenFactorIndex != -1) {
6156 Ops.push_back(LoLd);
6157 Ops.push_back(HiLd);
6158 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6162 LoAddr = St->getBasePtr();
6163 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6164 DAG.getConstant(MVT::i32, 4));
6166 SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6167 St->getSrcValue(), St->getSrcValueOffset(),
6168 St->isVolatile(), St->getAlignment());
6169 SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6170 St->getSrcValue(), St->getSrcValueOffset()+4,
6172 MinAlign(St->getAlignment(), 4));
6173 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6179 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6180 /// X86ISD::FXOR nodes.
6181 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6182 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6183 // F[X]OR(0.0, x) -> x
6184 // F[X]OR(x, 0.0) -> x
6185 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6186 if (C->getValueAPF().isPosZero())
6187 return N->getOperand(1);
6188 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6189 if (C->getValueAPF().isPosZero())
6190 return N->getOperand(0);
6194 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6195 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6196 // FAND(0.0, x) -> 0.0
6197 // FAND(x, 0.0) -> 0.0
6198 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6199 if (C->getValueAPF().isPosZero())
6200 return N->getOperand(0);
6201 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6202 if (C->getValueAPF().isPosZero())
6203 return N->getOperand(1);
6208 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6209 DAGCombinerInfo &DCI) const {
6210 SelectionDAG &DAG = DCI.DAG;
6211 switch (N->getOpcode()) {
6213 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
6214 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6216 return PerformSTORECombine(cast<StoreSDNode>(N), DAG, Subtarget);
6218 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6219 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6225 //===----------------------------------------------------------------------===//
6226 // X86 Inline Assembly Support
6227 //===----------------------------------------------------------------------===//
6229 /// getConstraintType - Given a constraint letter, return the type of
6230 /// constraint it is for this target.
6231 X86TargetLowering::ConstraintType
6232 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6233 if (Constraint.size() == 1) {
6234 switch (Constraint[0]) {
6243 return C_RegisterClass;
6248 return TargetLowering::getConstraintType(Constraint);
6251 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6252 /// with another that has more specific requirements based on the type of the
6253 /// corresponding operand.
6254 void X86TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT,
6255 std::string& s) const {
6256 if (MVT::isFloatingPoint(ConstraintVT)) {
6257 if (Subtarget->hasSSE2())
6259 else if (Subtarget->hasSSE1())
6264 return TargetLowering::lowerXConstraint(ConstraintVT, s);
6267 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6268 /// vector. If it is invalid, don't add anything to Ops.
6269 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6271 std::vector<SDOperand>&Ops,
6272 SelectionDAG &DAG) {
6273 SDOperand Result(0, 0);
6275 switch (Constraint) {
6278 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6279 if (C->getValue() <= 31) {
6280 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6286 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6287 if (C->getValue() <= 255) {
6288 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6294 // Literal immediates are always ok.
6295 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6296 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6300 // If we are in non-pic codegen mode, we allow the address of a global (with
6301 // an optional displacement) to be used with 'i'.
6302 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6305 // Match either (GA) or (GA+C)
6307 Offset = GA->getOffset();
6308 } else if (Op.getOpcode() == ISD::ADD) {
6309 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6310 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6312 Offset = GA->getOffset()+C->getValue();
6314 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6315 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6317 Offset = GA->getOffset()+C->getValue();
6324 // If addressing this global requires a load (e.g. in PIC mode), we can't
6326 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6330 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6336 // Otherwise, not valid for this mode.
6342 Ops.push_back(Result);
6345 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6348 std::vector<unsigned> X86TargetLowering::
6349 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6350 MVT::ValueType VT) const {
6351 if (Constraint.size() == 1) {
6352 // FIXME: not handling fp-stack yet!
6353 switch (Constraint[0]) { // GCC X86 Constraint Letters
6354 default: break; // Unknown constraint letter
6355 case 'A': // EAX/EDX
6356 if (VT == MVT::i32 || VT == MVT::i64)
6357 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6359 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6362 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6363 else if (VT == MVT::i16)
6364 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6365 else if (VT == MVT::i8)
6366 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6367 else if (VT == MVT::i64)
6368 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6373 return std::vector<unsigned>();
6376 std::pair<unsigned, const TargetRegisterClass*>
6377 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6378 MVT::ValueType VT) const {
6379 // First, see if this is a constraint that directly corresponds to an LLVM
6381 if (Constraint.size() == 1) {
6382 // GCC Constraint Letters
6383 switch (Constraint[0]) {
6385 case 'r': // GENERAL_REGS
6386 case 'R': // LEGACY_REGS
6387 case 'l': // INDEX_REGS
6388 if (VT == MVT::i64 && Subtarget->is64Bit())
6389 return std::make_pair(0U, X86::GR64RegisterClass);
6391 return std::make_pair(0U, X86::GR32RegisterClass);
6392 else if (VT == MVT::i16)
6393 return std::make_pair(0U, X86::GR16RegisterClass);
6394 else if (VT == MVT::i8)
6395 return std::make_pair(0U, X86::GR8RegisterClass);
6397 case 'y': // MMX_REGS if MMX allowed.
6398 if (!Subtarget->hasMMX()) break;
6399 return std::make_pair(0U, X86::VR64RegisterClass);
6401 case 'Y': // SSE_REGS if SSE2 allowed
6402 if (!Subtarget->hasSSE2()) break;
6404 case 'x': // SSE_REGS if SSE1 allowed
6405 if (!Subtarget->hasSSE1()) break;
6409 // Scalar SSE types.
6412 return std::make_pair(0U, X86::FR32RegisterClass);
6415 return std::make_pair(0U, X86::FR64RegisterClass);
6423 return std::make_pair(0U, X86::VR128RegisterClass);
6429 // Use the default implementation in TargetLowering to convert the register
6430 // constraint into a member of a register class.
6431 std::pair<unsigned, const TargetRegisterClass*> Res;
6432 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6434 // Not found as a standard register?
6435 if (Res.second == 0) {
6436 // GCC calls "st(0)" just plain "st".
6437 if (StringsEqualNoCase("{st}", Constraint)) {
6438 Res.first = X86::ST0;
6439 Res.second = X86::RFP80RegisterClass;
6445 // Otherwise, check to see if this is a register class of the wrong value
6446 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6447 // turn into {ax},{dx}.
6448 if (Res.second->hasType(VT))
6449 return Res; // Correct type already, nothing to do.
6451 // All of the single-register GCC register classes map their values onto
6452 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6453 // really want an 8-bit or 32-bit register, map to the appropriate register
6454 // class and return the appropriate register.
6455 if (Res.second != X86::GR16RegisterClass)
6458 if (VT == MVT::i8) {
6459 unsigned DestReg = 0;
6460 switch (Res.first) {
6462 case X86::AX: DestReg = X86::AL; break;
6463 case X86::DX: DestReg = X86::DL; break;
6464 case X86::CX: DestReg = X86::CL; break;
6465 case X86::BX: DestReg = X86::BL; break;
6468 Res.first = DestReg;
6469 Res.second = Res.second = X86::GR8RegisterClass;
6471 } else if (VT == MVT::i32) {
6472 unsigned DestReg = 0;
6473 switch (Res.first) {
6475 case X86::AX: DestReg = X86::EAX; break;
6476 case X86::DX: DestReg = X86::EDX; break;
6477 case X86::CX: DestReg = X86::ECX; break;
6478 case X86::BX: DestReg = X86::EBX; break;
6479 case X86::SI: DestReg = X86::ESI; break;
6480 case X86::DI: DestReg = X86::EDI; break;
6481 case X86::BP: DestReg = X86::EBP; break;
6482 case X86::SP: DestReg = X86::ESP; break;
6485 Res.first = DestReg;
6486 Res.second = Res.second = X86::GR32RegisterClass;
6488 } else if (VT == MVT::i64) {
6489 unsigned DestReg = 0;
6490 switch (Res.first) {
6492 case X86::AX: DestReg = X86::RAX; break;
6493 case X86::DX: DestReg = X86::RDX; break;
6494 case X86::CX: DestReg = X86::RCX; break;
6495 case X86::BX: DestReg = X86::RBX; break;
6496 case X86::SI: DestReg = X86::RSI; break;
6497 case X86::DI: DestReg = X86::RDI; break;
6498 case X86::BP: DestReg = X86::RBP; break;
6499 case X86::SP: DestReg = X86::RSP; break;
6502 Res.first = DestReg;
6503 Res.second = Res.second = X86::GR64RegisterClass;