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_ST0, 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);
920 SDOperand GROps[] = { Chain, InFlag };
921 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_ST0, Tys, GROps, 2);
922 Chain = RetVal.getValue(1);
923 InFlag = RetVal.getValue(2);
925 // If we want the result in an SSE register, use an FP_TRUNCATE to get it
927 if (GetResultTy != RVLocs[0].getValVT())
928 RetVal = DAG.getNode(ISD::FP_ROUND, RVLocs[0].getValVT(), RetVal,
929 // This truncation won't change the value.
930 DAG.getIntPtrConstant(1));
932 ResultVals.push_back(RetVal);
935 // Merge everything together with a MERGE_VALUES node.
936 ResultVals.push_back(Chain);
937 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
938 &ResultVals[0], ResultVals.size()).Val;
941 /// LowerCallResultToTwo64BitRegs - Lower the result values of an x86-64
942 /// ISD::CALL where the results are known to be in two 64-bit registers,
943 /// e.g. XMM0 and XMM1. This simplify store the two values back to the
944 /// fixed stack slot allocated for StructRet.
945 SDNode *X86TargetLowering::
946 LowerCallResultToTwo64BitRegs(SDOperand Chain, SDOperand InFlag,
947 SDNode *TheCall, unsigned Reg1, unsigned Reg2,
948 MVT::ValueType VT, SelectionDAG &DAG) {
949 SDOperand RetVal1 = DAG.getCopyFromReg(Chain, Reg1, VT, InFlag);
950 Chain = RetVal1.getValue(1);
951 InFlag = RetVal1.getValue(2);
952 SDOperand RetVal2 = DAG.getCopyFromReg(Chain, Reg2, VT, InFlag);
953 Chain = RetVal2.getValue(1);
954 InFlag = RetVal2.getValue(2);
955 SDOperand FIN = TheCall->getOperand(5);
956 Chain = DAG.getStore(Chain, RetVal1, FIN, NULL, 0);
957 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
958 Chain = DAG.getStore(Chain, RetVal2, FIN, NULL, 0);
962 /// LowerCallResultToTwoX87Regs - Lower the result values of an x86-64 ISD::CALL
963 /// where the results are known to be in ST0 and ST1.
964 SDNode *X86TargetLowering::
965 LowerCallResultToTwoX87Regs(SDOperand Chain, SDOperand InFlag,
966 SDNode *TheCall, SelectionDAG &DAG) {
967 SmallVector<SDOperand, 8> ResultVals;
968 const MVT::ValueType VTs[] = { MVT::f80, MVT::f80, MVT::Other, MVT::Flag };
969 SDVTList Tys = DAG.getVTList(VTs, 4);
970 SDOperand Ops[] = { Chain, InFlag };
971 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_ST0_ST1, Tys, Ops, 2);
972 Chain = RetVal.getValue(2);
973 SDOperand FIN = TheCall->getOperand(5);
974 Chain = DAG.getStore(Chain, RetVal.getValue(1), FIN, NULL, 0);
975 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(16));
976 Chain = DAG.getStore(Chain, RetVal, FIN, NULL, 0);
980 //===----------------------------------------------------------------------===//
981 // C & StdCall & Fast Calling Convention implementation
982 //===----------------------------------------------------------------------===//
983 // StdCall calling convention seems to be standard for many Windows' API
984 // routines and around. It differs from C calling convention just a little:
985 // callee should clean up the stack, not caller. Symbols should be also
986 // decorated in some fancy way :) It doesn't support any vector arguments.
987 // For info on fast calling convention see Fast Calling Convention (tail call)
988 // implementation LowerX86_32FastCCCallTo.
990 /// AddLiveIn - This helper function adds the specified physical register to the
991 /// MachineFunction as a live in value. It also creates a corresponding virtual
993 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
994 const TargetRegisterClass *RC) {
995 assert(RC->contains(PReg) && "Not the correct regclass!");
996 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
997 MF.getRegInfo().addLiveIn(PReg, VReg);
1001 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1003 static bool CallIsStructReturn(SDOperand Op) {
1004 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1008 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(6));
1009 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1012 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1013 /// return semantics.
1014 static bool ArgsAreStructReturn(SDOperand Op) {
1015 unsigned NumArgs = Op.Val->getNumValues() - 1;
1019 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(3));
1020 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1023 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires the
1024 /// callee to pop its own arguments. Callee pop is necessary to support tail
1026 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1027 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1031 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1034 case CallingConv::X86_StdCall:
1035 return !Subtarget->is64Bit();
1036 case CallingConv::X86_FastCall:
1037 return !Subtarget->is64Bit();
1038 case CallingConv::Fast:
1039 return PerformTailCallOpt;
1043 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1044 /// FORMAL_ARGUMENTS node.
1045 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1046 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1048 if (Subtarget->is64Bit()) {
1049 if (CC == CallingConv::Fast && PerformTailCallOpt)
1050 return CC_X86_64_TailCall;
1055 if (CC == CallingConv::X86_FastCall)
1056 return CC_X86_32_FastCall;
1057 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1058 return CC_X86_32_TailCall;
1063 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1064 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1066 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1067 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1068 if (CC == CallingConv::X86_FastCall)
1070 else if (CC == CallingConv::X86_StdCall)
1075 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
1076 /// possibly be overwritten when lowering the outgoing arguments in a tail
1077 /// call. Currently the implementation of this call is very conservative and
1078 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
1079 /// virtual registers would be overwritten by direct lowering.
1080 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
1081 MachineFrameInfo * MFI) {
1082 RegisterSDNode * OpReg = NULL;
1083 FrameIndexSDNode * FrameIdxNode = NULL;
1085 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
1086 (Op.getOpcode()== ISD::CopyFromReg &&
1087 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
1088 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
1089 (Op.getOpcode() == ISD::LOAD &&
1090 (FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op.getOperand(1))) &&
1091 (MFI->isFixedObjectIndex((FrameIdx = FrameIdxNode->getIndex()))) &&
1092 (MFI->getObjectOffset(FrameIdx) >= 0)))
1097 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1098 /// in a register before calling.
1099 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1100 return !IsTailCall && !Is64Bit &&
1101 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1102 Subtarget->isPICStyleGOT();
1106 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1107 /// address to be loaded in a register.
1109 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1110 return !Is64Bit && IsTailCall &&
1111 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1112 Subtarget->isPICStyleGOT();
1115 /// CopyTailCallClobberedArgumentsToVRegs - Create virtual registers for all
1116 /// arguments to force loading and guarantee that arguments sourcing from
1117 /// incomming parameters are not overwriting each other.
1119 CopyTailCallClobberedArgumentsToVRegs(SDOperand Chain,
1120 SmallVector<std::pair<unsigned, SDOperand>, 8> &TailCallClobberedVRegs,
1122 MachineFunction &MF,
1123 const TargetLowering * TL) {
1126 for (unsigned i = 0, e = TailCallClobberedVRegs.size(); i != e; i++) {
1127 SDOperand Arg = TailCallClobberedVRegs[i].second;
1128 unsigned Idx = TailCallClobberedVRegs[i].first;
1131 createVirtualRegister(TL->getRegClassFor(Arg.getValueType()));
1132 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
1133 InFlag = Chain.getValue(1);
1134 Arg = DAG.getCopyFromReg(Chain, VReg, Arg.getValueType(), InFlag);
1135 TailCallClobberedVRegs[i] = std::make_pair(Idx, Arg);
1136 Chain = Arg.getValue(1);
1137 InFlag = Arg.getValue(2);
1142 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1143 /// by "Src" to address "Dst" with size and alignment information specified by
1144 /// the specific parameter attribute. The copy will be passed as a byval function
1147 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1148 unsigned Flags, SelectionDAG &DAG) {
1149 unsigned Align = 1 <<
1150 ((Flags & ISD::ParamFlags::ByValAlign) >> ISD::ParamFlags::ByValAlignOffs);
1151 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1152 ISD::ParamFlags::ByValSizeOffs;
1153 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1154 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1155 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1156 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, AlignNode, AlwaysInline);
1159 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1160 const CCValAssign &VA,
1161 MachineFrameInfo *MFI,
1163 SDOperand Root, unsigned i) {
1164 // Create the nodes corresponding to a load from this parameter slot.
1165 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
1166 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1167 bool isByVal = Flags & ISD::ParamFlags::ByVal;
1168 bool isImmutable = !AlwaysUseMutable && !isByVal;
1170 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1171 // changed with more analysis.
1172 // In case of tail call optimization mark all arguments mutable. Since they
1173 // could be overwritten by lowering of arguments in case of a tail call.
1174 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1175 VA.getLocMemOffset(), isImmutable);
1176 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1179 return DAG.getLoad(VA.getValVT(), Root, FIN,
1180 PseudoSourceValue::getFixedStack(), FI);
1184 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1185 MachineFunction &MF = DAG.getMachineFunction();
1186 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1188 const Function* Fn = MF.getFunction();
1189 if (Fn->hasExternalLinkage() &&
1190 Subtarget->isTargetCygMing() &&
1191 Fn->getName() == "main")
1192 FuncInfo->setForceFramePointer(true);
1194 // Decorate the function name.
1195 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1197 MachineFrameInfo *MFI = MF.getFrameInfo();
1198 SDOperand Root = Op.getOperand(0);
1199 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1200 unsigned CC = MF.getFunction()->getCallingConv();
1201 bool Is64Bit = Subtarget->is64Bit();
1203 assert(!(isVarArg && CC == CallingConv::Fast) &&
1204 "Var args not supported with calling convention fastcc");
1206 // Assign locations to all of the incoming arguments.
1207 SmallVector<CCValAssign, 16> ArgLocs;
1208 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1209 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1211 SmallVector<SDOperand, 8> ArgValues;
1212 unsigned LastVal = ~0U;
1213 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1214 CCValAssign &VA = ArgLocs[i];
1215 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1217 assert(VA.getValNo() != LastVal &&
1218 "Don't support value assigned to multiple locs yet");
1219 LastVal = VA.getValNo();
1221 if (VA.isRegLoc()) {
1222 MVT::ValueType RegVT = VA.getLocVT();
1223 TargetRegisterClass *RC;
1224 if (RegVT == MVT::i32)
1225 RC = X86::GR32RegisterClass;
1226 else if (Is64Bit && RegVT == MVT::i64)
1227 RC = X86::GR64RegisterClass;
1228 else if (RegVT == MVT::f32)
1229 RC = X86::FR32RegisterClass;
1230 else if (RegVT == MVT::f64)
1231 RC = X86::FR64RegisterClass;
1233 assert(MVT::isVector(RegVT));
1234 if (Is64Bit && MVT::getSizeInBits(RegVT) == 64) {
1235 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1238 RC = X86::VR128RegisterClass;
1241 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1242 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1244 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1245 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1247 if (VA.getLocInfo() == CCValAssign::SExt)
1248 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1249 DAG.getValueType(VA.getValVT()));
1250 else if (VA.getLocInfo() == CCValAssign::ZExt)
1251 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1252 DAG.getValueType(VA.getValVT()));
1254 if (VA.getLocInfo() != CCValAssign::Full)
1255 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1257 // Handle MMX values passed in GPRs.
1258 if (Is64Bit && RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1259 MVT::getSizeInBits(RegVT) == 64)
1260 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1262 ArgValues.push_back(ArgValue);
1264 assert(VA.isMemLoc());
1265 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1269 unsigned StackSize = CCInfo.getNextStackOffset();
1270 // align stack specially for tail calls
1271 if (CC == CallingConv::Fast)
1272 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1274 // If the function takes variable number of arguments, make a frame index for
1275 // the start of the first vararg value... for expansion of llvm.va_start.
1277 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1278 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1281 static const unsigned GPR64ArgRegs[] = {
1282 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1284 static const unsigned XMMArgRegs[] = {
1285 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1286 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1289 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1290 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1292 // For X86-64, if there are vararg parameters that are passed via
1293 // registers, then we must store them to their spots on the stack so they
1294 // may be loaded by deferencing the result of va_next.
1295 VarArgsGPOffset = NumIntRegs * 8;
1296 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1297 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1299 // Store the integer parameter registers.
1300 SmallVector<SDOperand, 8> MemOps;
1301 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1302 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1303 DAG.getIntPtrConstant(VarArgsGPOffset));
1304 for (; NumIntRegs != 6; ++NumIntRegs) {
1305 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1306 X86::GR64RegisterClass);
1307 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1309 DAG.getStore(Val.getValue(1), Val, FIN,
1310 PseudoSourceValue::getFixedStack(),
1312 MemOps.push_back(Store);
1313 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1314 DAG.getIntPtrConstant(8));
1317 // Now store the XMM (fp + vector) parameter registers.
1318 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1319 DAG.getIntPtrConstant(VarArgsFPOffset));
1320 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1321 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1322 X86::VR128RegisterClass);
1323 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1325 DAG.getStore(Val.getValue(1), Val, FIN,
1326 PseudoSourceValue::getFixedStack(),
1328 MemOps.push_back(Store);
1329 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1330 DAG.getIntPtrConstant(16));
1332 if (!MemOps.empty())
1333 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1334 &MemOps[0], MemOps.size());
1338 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1339 // arguments and the arguments after the retaddr has been pushed are
1341 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1342 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1343 (StackSize & 7) == 0)
1346 ArgValues.push_back(Root);
1348 // Some CCs need callee pop.
1349 if (IsCalleePop(Op)) {
1350 BytesToPopOnReturn = StackSize; // Callee pops everything.
1351 BytesCallerReserves = 0;
1353 BytesToPopOnReturn = 0; // Callee pops nothing.
1354 // If this is an sret function, the return should pop the hidden pointer.
1355 if (!Is64Bit && ArgsAreStructReturn(Op))
1356 BytesToPopOnReturn = 4;
1357 BytesCallerReserves = StackSize;
1361 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1362 if (CC == CallingConv::X86_FastCall)
1363 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1366 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1368 // Return the new list of results.
1369 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1370 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1374 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1375 const SDOperand &StackPtr,
1376 const CCValAssign &VA,
1379 unsigned LocMemOffset = VA.getLocMemOffset();
1380 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1381 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1382 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1383 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1384 if (Flags & ISD::ParamFlags::ByVal) {
1385 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1387 return DAG.getStore(Chain, Arg, PtrOff,
1388 PseudoSourceValue::getStack(), LocMemOffset);
1391 /// ClassifyX86_64SRetCallReturn - Classify how to implement a x86-64
1392 /// struct return call to the specified function. X86-64 ABI specifies
1393 /// some SRet calls are actually returned in registers. Since current
1394 /// LLVM cannot represent multi-value calls, they are represent as
1395 /// calls where the results are passed in a hidden struct provided by
1396 /// the caller. This function examines the type of the struct to
1397 /// determine the correct way to implement the call.
1399 X86TargetLowering::ClassifyX86_64SRetCallReturn(const Function *Fn) {
1400 // FIXME: Disabled for now.
1401 return X86::InMemory;
1403 const PointerType *PTy = cast<PointerType>(Fn->arg_begin()->getType());
1404 const Type *RTy = PTy->getElementType();
1405 unsigned Size = getTargetData()->getABITypeSize(RTy);
1406 if (Size != 16 && Size != 32)
1407 return X86::InMemory;
1410 const StructType *STy = dyn_cast<StructType>(RTy);
1411 if (!STy) return X86::InMemory;
1412 if (STy->getNumElements() == 2 &&
1413 STy->getElementType(0) == Type::X86_FP80Ty &&
1414 STy->getElementType(1) == Type::X86_FP80Ty)
1419 for (Type::subtype_iterator I = RTy->subtype_begin(), E = RTy->subtype_end();
1421 const Type *STy = I->get();
1422 if (!STy->isFPOrFPVector()) {
1430 return X86::InGPR64;
1433 void X86TargetLowering::X86_64AnalyzeSRetCallOperands(SDNode *TheCall,
1436 unsigned NumOps = (TheCall->getNumOperands() - 5) / 2;
1437 for (unsigned i = 1; i != NumOps; ++i) {
1438 MVT::ValueType ArgVT = TheCall->getOperand(5+2*i).getValueType();
1439 SDOperand FlagOp = TheCall->getOperand(5+2*i+1);
1440 unsigned ArgFlags =cast<ConstantSDNode>(FlagOp)->getValue();
1441 if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo)) {
1442 cerr << "Call operand #" << i << " has unhandled type "
1443 << MVT::getValueTypeString(ArgVT) << "\n";
1449 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1450 MachineFunction &MF = DAG.getMachineFunction();
1451 MachineFrameInfo * MFI = MF.getFrameInfo();
1452 SDOperand Chain = Op.getOperand(0);
1453 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1454 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1455 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1456 && CC == CallingConv::Fast && PerformTailCallOpt;
1457 SDOperand Callee = Op.getOperand(4);
1458 bool Is64Bit = Subtarget->is64Bit();
1459 bool IsStructRet = CallIsStructReturn(Op);
1461 assert(!(isVarArg && CC == CallingConv::Fast) &&
1462 "Var args not supported with calling convention fastcc");
1464 // Analyze operands of the call, assigning locations to each operand.
1465 SmallVector<CCValAssign, 16> ArgLocs;
1466 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1467 CCAssignFn *CCFn = CCAssignFnForNode(Op);
1469 X86::X86_64SRet SRetMethod = X86::InMemory;
1470 if (Is64Bit && IsStructRet)
1471 // FIXME: We can't figure out type of the sret structure for indirect
1472 // calls. We need to copy more information from CallSite to the ISD::CALL
1474 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1476 ClassifyX86_64SRetCallReturn(dyn_cast<Function>(G->getGlobal()));
1478 // UGLY HACK! For x86-64, some 128-bit aggregates are returns in a pair of
1479 // registers. Unfortunately, llvm does not support i128 yet so we pretend it's
1481 if (SRetMethod != X86::InMemory)
1482 X86_64AnalyzeSRetCallOperands(Op.Val, CCFn, CCInfo);
1484 CCInfo.AnalyzeCallOperands(Op.Val, CCFn);
1486 // Get a count of how many bytes are to be pushed on the stack.
1487 unsigned NumBytes = CCInfo.getNextStackOffset();
1488 if (CC == CallingConv::Fast)
1489 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1491 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1492 // arguments and the arguments after the retaddr has been pushed are aligned.
1493 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1494 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1495 (NumBytes & 7) == 0)
1500 // Lower arguments at fp - stackoffset + fpdiff.
1501 unsigned NumBytesCallerPushed =
1502 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1503 FPDiff = NumBytesCallerPushed - NumBytes;
1505 // Set the delta of movement of the returnaddr stackslot.
1506 // But only set if delta is greater than previous delta.
1507 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1508 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1511 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1513 SDOperand RetAddrFrIdx;
1515 // Adjust the Return address stack slot.
1517 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1518 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1519 // Load the "old" Return address.
1521 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1522 Chain = SDOperand(RetAddrFrIdx.Val, 1);
1526 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1527 SmallVector<std::pair<unsigned, SDOperand>, 8> TailCallClobberedVRegs;
1528 SmallVector<SDOperand, 8> MemOpChains;
1532 // Walk the register/memloc assignments, inserting copies/loads. For tail
1533 // calls, remember all arguments for later special lowering.
1534 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1535 CCValAssign &VA = ArgLocs[i];
1536 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1538 // Promote the value if needed.
1539 switch (VA.getLocInfo()) {
1540 default: assert(0 && "Unknown loc info!");
1541 case CCValAssign::Full: break;
1542 case CCValAssign::SExt:
1543 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1545 case CCValAssign::ZExt:
1546 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1548 case CCValAssign::AExt:
1549 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1553 if (VA.isRegLoc()) {
1554 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1557 assert(VA.isMemLoc());
1558 if (StackPtr.Val == 0)
1559 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1561 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1563 } else if (IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
1564 TailCallClobberedVRegs.push_back(std::make_pair(i,Arg));
1569 if (!MemOpChains.empty())
1570 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1571 &MemOpChains[0], MemOpChains.size());
1573 // Build a sequence of copy-to-reg nodes chained together with token chain
1574 // and flag operands which copy the outgoing args into registers.
1576 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1577 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1579 InFlag = Chain.getValue(1);
1582 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1584 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1585 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1586 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1588 InFlag = Chain.getValue(1);
1590 // If we are tail calling and generating PIC/GOT style code load the address
1591 // of the callee into ecx. The value in ecx is used as target of the tail
1592 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1593 // calls on PIC/GOT architectures. Normally we would just put the address of
1594 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1595 // restored (since ebx is callee saved) before jumping to the target@PLT.
1596 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1597 // Note: The actual moving to ecx is done further down.
1598 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1599 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1600 !G->getGlobal()->hasProtectedVisibility())
1601 Callee = LowerGlobalAddress(Callee, DAG);
1602 else if (isa<ExternalSymbolSDNode>(Callee))
1603 Callee = LowerExternalSymbol(Callee,DAG);
1606 if (Is64Bit && isVarArg) {
1607 // From AMD64 ABI document:
1608 // For calls that may call functions that use varargs or stdargs
1609 // (prototype-less calls or calls to functions containing ellipsis (...) in
1610 // the declaration) %al is used as hidden argument to specify the number
1611 // of SSE registers used. The contents of %al do not need to match exactly
1612 // the number of registers, but must be an ubound on the number of SSE
1613 // registers used and is in the range 0 - 8 inclusive.
1615 // Count the number of XMM registers allocated.
1616 static const unsigned XMMArgRegs[] = {
1617 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1618 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1620 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1622 Chain = DAG.getCopyToReg(Chain, X86::AL,
1623 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1624 InFlag = Chain.getValue(1);
1628 // For tail calls lower the arguments to the 'real' stack slot.
1630 SmallVector<SDOperand, 8> MemOpChains2;
1633 // Do not flag preceeding copytoreg stuff together with the following stuff.
1634 InFlag = SDOperand();
1636 Chain = CopyTailCallClobberedArgumentsToVRegs(Chain, TailCallClobberedVRegs,
1639 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1640 CCValAssign &VA = ArgLocs[i];
1641 if (!VA.isRegLoc()) {
1642 assert(VA.isMemLoc());
1643 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1644 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1645 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1646 // Create frame index.
1647 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1648 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1649 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1650 FIN = DAG.getFrameIndex(FI, MVT::i32);
1652 // Find virtual register for this argument.
1654 for (unsigned idx=0, e= TailCallClobberedVRegs.size(); idx < e; idx++)
1655 if (TailCallClobberedVRegs[idx].first==i) {
1656 Arg = TailCallClobberedVRegs[idx].second;
1660 assert(IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)==false ||
1661 (Found==true && "No corresponding Argument was found"));
1663 if (Flags & ISD::ParamFlags::ByVal) {
1664 // Copy relative to framepointer.
1665 MemOpChains2.push_back(CreateCopyOfByValArgument(Arg, FIN, Chain,
1668 // Store relative to framepointer.
1669 MemOpChains2.push_back(
1670 DAG.getStore(Chain, Arg, FIN,
1671 PseudoSourceValue::getFixedStack(), FI));
1676 if (!MemOpChains2.empty())
1677 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1678 &MemOpChains2[0], MemOpChains2.size());
1680 // Store the return address to the appropriate stack slot.
1682 // Calculate the new stack slot for the return address.
1683 int SlotSize = Is64Bit ? 8 : 4;
1684 int NewReturnAddrFI =
1685 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1686 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1687 SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1688 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1689 PseudoSourceValue::getFixedStack(), NewReturnAddrFI);
1693 // If the callee is a GlobalAddress node (quite common, every direct call is)
1694 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1695 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1696 // We should use extra load for direct calls to dllimported functions in
1698 if ((IsTailCall || !Is64Bit ||
1699 getTargetMachine().getCodeModel() != CodeModel::Large)
1700 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1701 getTargetMachine(), true))
1702 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1703 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1704 if (IsTailCall || !Is64Bit ||
1705 getTargetMachine().getCodeModel() != CodeModel::Large)
1706 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1707 } else if (IsTailCall) {
1708 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1710 Chain = DAG.getCopyToReg(Chain,
1711 DAG.getRegister(Opc, getPointerTy()),
1713 Callee = DAG.getRegister(Opc, getPointerTy());
1714 // Add register as live out.
1715 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1718 // Returns a chain & a flag for retval copy to use.
1719 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1720 SmallVector<SDOperand, 8> Ops;
1723 Ops.push_back(Chain);
1724 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1725 Ops.push_back(DAG.getIntPtrConstant(0));
1727 Ops.push_back(InFlag);
1728 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1729 InFlag = Chain.getValue(1);
1731 // Returns a chain & a flag for retval copy to use.
1732 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1736 Ops.push_back(Chain);
1737 Ops.push_back(Callee);
1740 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1742 // Add an implicit use GOT pointer in EBX.
1743 if (!IsTailCall && !Is64Bit &&
1744 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1745 Subtarget->isPICStyleGOT())
1746 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1748 // Add argument registers to the end of the list so that they are known live
1750 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1751 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1752 RegsToPass[i].second.getValueType()));
1755 Ops.push_back(InFlag);
1758 assert(InFlag.Val &&
1759 "Flag must be set. Depend on flag being set in LowerRET");
1760 Chain = DAG.getNode(X86ISD::TAILCALL,
1761 Op.Val->getVTList(), &Ops[0], Ops.size());
1763 return SDOperand(Chain.Val, Op.ResNo);
1766 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1767 InFlag = Chain.getValue(1);
1769 // Create the CALLSEQ_END node.
1770 unsigned NumBytesForCalleeToPush;
1771 if (IsCalleePop(Op))
1772 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1773 else if (!Is64Bit && IsStructRet)
1774 // If this is is a call to a struct-return function, the callee
1775 // pops the hidden struct pointer, so we have to push it back.
1776 // This is common for Darwin/X86, Linux & Mingw32 targets.
1777 NumBytesForCalleeToPush = 4;
1779 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1781 // Returns a flag for retval copy to use.
1782 Chain = DAG.getCALLSEQ_END(Chain,
1783 DAG.getIntPtrConstant(NumBytes),
1784 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1786 InFlag = Chain.getValue(1);
1788 // Handle result values, copying them out of physregs into vregs that we
1790 switch (SRetMethod) {
1792 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1794 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1796 MVT::i64, DAG), Op.ResNo);
1798 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1799 X86::XMM0, X86::XMM1,
1800 MVT::f64, DAG), Op.ResNo);
1802 return SDOperand(LowerCallResultToTwoX87Regs(Chain, InFlag, Op.Val, DAG),
1808 //===----------------------------------------------------------------------===//
1809 // Fast Calling Convention (tail call) implementation
1810 //===----------------------------------------------------------------------===//
1812 // Like std call, callee cleans arguments, convention except that ECX is
1813 // reserved for storing the tail called function address. Only 2 registers are
1814 // free for argument passing (inreg). Tail call optimization is performed
1816 // * tailcallopt is enabled
1817 // * caller/callee are fastcc
1818 // On X86_64 architecture with GOT-style position independent code only local
1819 // (within module) calls are supported at the moment.
1820 // To keep the stack aligned according to platform abi the function
1821 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1822 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1823 // If a tail called function callee has more arguments than the caller the
1824 // caller needs to make sure that there is room to move the RETADDR to. This is
1825 // achieved by reserving an area the size of the argument delta right after the
1826 // original REtADDR, but before the saved framepointer or the spilled registers
1827 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1839 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1840 /// for a 16 byte align requirement.
1841 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1842 SelectionDAG& DAG) {
1843 if (PerformTailCallOpt) {
1844 MachineFunction &MF = DAG.getMachineFunction();
1845 const TargetMachine &TM = MF.getTarget();
1846 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1847 unsigned StackAlignment = TFI.getStackAlignment();
1848 uint64_t AlignMask = StackAlignment - 1;
1849 int64_t Offset = StackSize;
1850 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1851 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1852 // Number smaller than 12 so just add the difference.
1853 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1855 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1856 Offset = ((~AlignMask) & Offset) + StackAlignment +
1857 (StackAlignment-SlotSize);
1864 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1865 /// following the call is a return. A function is eligible if caller/callee
1866 /// calling conventions match, currently only fastcc supports tail calls, and
1867 /// the function CALL is immediatly followed by a RET.
1868 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1870 SelectionDAG& DAG) const {
1871 if (!PerformTailCallOpt)
1874 // Check whether CALL node immediatly preceeds the RET node and whether the
1875 // return uses the result of the node or is a void return.
1876 unsigned NumOps = Ret.getNumOperands();
1878 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1879 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1881 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1882 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1883 MachineFunction &MF = DAG.getMachineFunction();
1884 unsigned CallerCC = MF.getFunction()->getCallingConv();
1885 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1886 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1887 SDOperand Callee = Call.getOperand(4);
1888 // On x86/32Bit PIC/GOT tail calls are supported.
1889 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1890 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1893 // Can only do local tail calls (in same module, hidden or protected) on
1894 // x86_64 PIC/GOT at the moment.
1895 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1896 return G->getGlobal()->hasHiddenVisibility()
1897 || G->getGlobal()->hasProtectedVisibility();
1904 //===----------------------------------------------------------------------===//
1905 // Other Lowering Hooks
1906 //===----------------------------------------------------------------------===//
1909 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1910 MachineFunction &MF = DAG.getMachineFunction();
1911 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1912 int ReturnAddrIndex = FuncInfo->getRAIndex();
1914 if (ReturnAddrIndex == 0) {
1915 // Set up a frame object for the return address.
1916 if (Subtarget->is64Bit())
1917 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1919 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1921 FuncInfo->setRAIndex(ReturnAddrIndex);
1924 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1929 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1930 /// specific condition code. It returns a false if it cannot do a direct
1931 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1933 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1934 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1935 SelectionDAG &DAG) {
1936 X86CC = X86::COND_INVALID;
1938 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1939 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1940 // X > -1 -> X == 0, jump !sign.
1941 RHS = DAG.getConstant(0, RHS.getValueType());
1942 X86CC = X86::COND_NS;
1944 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1945 // X < 0 -> X == 0, jump on sign.
1946 X86CC = X86::COND_S;
1948 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1950 RHS = DAG.getConstant(0, RHS.getValueType());
1951 X86CC = X86::COND_LE;
1956 switch (SetCCOpcode) {
1958 case ISD::SETEQ: X86CC = X86::COND_E; break;
1959 case ISD::SETGT: X86CC = X86::COND_G; break;
1960 case ISD::SETGE: X86CC = X86::COND_GE; break;
1961 case ISD::SETLT: X86CC = X86::COND_L; break;
1962 case ISD::SETLE: X86CC = X86::COND_LE; break;
1963 case ISD::SETNE: X86CC = X86::COND_NE; break;
1964 case ISD::SETULT: X86CC = X86::COND_B; break;
1965 case ISD::SETUGT: X86CC = X86::COND_A; break;
1966 case ISD::SETULE: X86CC = X86::COND_BE; break;
1967 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1970 // On a floating point condition, the flags are set as follows:
1972 // 0 | 0 | 0 | X > Y
1973 // 0 | 0 | 1 | X < Y
1974 // 1 | 0 | 0 | X == Y
1975 // 1 | 1 | 1 | unordered
1977 switch (SetCCOpcode) {
1980 case ISD::SETEQ: X86CC = X86::COND_E; break;
1981 case ISD::SETOLT: Flip = true; // Fallthrough
1983 case ISD::SETGT: X86CC = X86::COND_A; break;
1984 case ISD::SETOLE: Flip = true; // Fallthrough
1986 case ISD::SETGE: X86CC = X86::COND_AE; break;
1987 case ISD::SETUGT: Flip = true; // Fallthrough
1989 case ISD::SETLT: X86CC = X86::COND_B; break;
1990 case ISD::SETUGE: Flip = true; // Fallthrough
1992 case ISD::SETLE: X86CC = X86::COND_BE; break;
1994 case ISD::SETNE: X86CC = X86::COND_NE; break;
1995 case ISD::SETUO: X86CC = X86::COND_P; break;
1996 case ISD::SETO: X86CC = X86::COND_NP; break;
1999 std::swap(LHS, RHS);
2002 return X86CC != X86::COND_INVALID;
2005 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2006 /// code. Current x86 isa includes the following FP cmov instructions:
2007 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2008 static bool hasFPCMov(unsigned X86CC) {
2024 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2025 /// true if Op is undef or if its value falls within the specified range (L, H].
2026 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2027 if (Op.getOpcode() == ISD::UNDEF)
2030 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2031 return (Val >= Low && Val < Hi);
2034 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2035 /// true if Op is undef or if its value equal to the specified value.
2036 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2037 if (Op.getOpcode() == ISD::UNDEF)
2039 return cast<ConstantSDNode>(Op)->getValue() == Val;
2042 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2043 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2044 bool X86::isPSHUFDMask(SDNode *N) {
2045 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2047 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2050 // Check if the value doesn't reference the second vector.
2051 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2052 SDOperand Arg = N->getOperand(i);
2053 if (Arg.getOpcode() == ISD::UNDEF) continue;
2054 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2055 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2062 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2063 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2064 bool X86::isPSHUFHWMask(SDNode *N) {
2065 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2067 if (N->getNumOperands() != 8)
2070 // Lower quadword copied in order.
2071 for (unsigned i = 0; i != 4; ++i) {
2072 SDOperand Arg = N->getOperand(i);
2073 if (Arg.getOpcode() == ISD::UNDEF) continue;
2074 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2075 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2079 // Upper quadword shuffled.
2080 for (unsigned i = 4; i != 8; ++i) {
2081 SDOperand Arg = N->getOperand(i);
2082 if (Arg.getOpcode() == ISD::UNDEF) continue;
2083 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2084 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2085 if (Val < 4 || Val > 7)
2092 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2093 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2094 bool X86::isPSHUFLWMask(SDNode *N) {
2095 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2097 if (N->getNumOperands() != 8)
2100 // Upper quadword copied in order.
2101 for (unsigned i = 4; i != 8; ++i)
2102 if (!isUndefOrEqual(N->getOperand(i), i))
2105 // Lower quadword shuffled.
2106 for (unsigned i = 0; i != 4; ++i)
2107 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2113 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2114 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2115 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2116 if (NumElems != 2 && NumElems != 4) return false;
2118 unsigned Half = NumElems / 2;
2119 for (unsigned i = 0; i < Half; ++i)
2120 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2122 for (unsigned i = Half; i < NumElems; ++i)
2123 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2129 bool X86::isSHUFPMask(SDNode *N) {
2130 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2131 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2134 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2135 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2136 /// half elements to come from vector 1 (which would equal the dest.) and
2137 /// the upper half to come from vector 2.
2138 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2139 if (NumOps != 2 && NumOps != 4) return false;
2141 unsigned Half = NumOps / 2;
2142 for (unsigned i = 0; i < Half; ++i)
2143 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2145 for (unsigned i = Half; i < NumOps; ++i)
2146 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2151 static bool isCommutedSHUFP(SDNode *N) {
2152 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2153 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2156 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2157 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2158 bool X86::isMOVHLPSMask(SDNode *N) {
2159 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2161 if (N->getNumOperands() != 4)
2164 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2165 return isUndefOrEqual(N->getOperand(0), 6) &&
2166 isUndefOrEqual(N->getOperand(1), 7) &&
2167 isUndefOrEqual(N->getOperand(2), 2) &&
2168 isUndefOrEqual(N->getOperand(3), 3);
2171 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2172 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2174 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2175 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2177 if (N->getNumOperands() != 4)
2180 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2181 return isUndefOrEqual(N->getOperand(0), 2) &&
2182 isUndefOrEqual(N->getOperand(1), 3) &&
2183 isUndefOrEqual(N->getOperand(2), 2) &&
2184 isUndefOrEqual(N->getOperand(3), 3);
2187 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2188 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2189 bool X86::isMOVLPMask(SDNode *N) {
2190 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2192 unsigned NumElems = N->getNumOperands();
2193 if (NumElems != 2 && NumElems != 4)
2196 for (unsigned i = 0; i < NumElems/2; ++i)
2197 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2200 for (unsigned i = NumElems/2; i < NumElems; ++i)
2201 if (!isUndefOrEqual(N->getOperand(i), i))
2207 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2208 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2210 bool X86::isMOVHPMask(SDNode *N) {
2211 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2213 unsigned NumElems = N->getNumOperands();
2214 if (NumElems != 2 && NumElems != 4)
2217 for (unsigned i = 0; i < NumElems/2; ++i)
2218 if (!isUndefOrEqual(N->getOperand(i), i))
2221 for (unsigned i = 0; i < NumElems/2; ++i) {
2222 SDOperand Arg = N->getOperand(i + NumElems/2);
2223 if (!isUndefOrEqual(Arg, i + NumElems))
2230 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2231 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2232 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2233 bool V2IsSplat = false) {
2234 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2237 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2238 SDOperand BitI = Elts[i];
2239 SDOperand BitI1 = Elts[i+1];
2240 if (!isUndefOrEqual(BitI, j))
2243 if (isUndefOrEqual(BitI1, NumElts))
2246 if (!isUndefOrEqual(BitI1, j + NumElts))
2254 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2255 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2256 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2259 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2260 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2261 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2262 bool V2IsSplat = false) {
2263 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2266 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2267 SDOperand BitI = Elts[i];
2268 SDOperand BitI1 = Elts[i+1];
2269 if (!isUndefOrEqual(BitI, j + NumElts/2))
2272 if (isUndefOrEqual(BitI1, NumElts))
2275 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2283 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2284 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2285 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2288 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2289 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2291 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2292 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2294 unsigned NumElems = N->getNumOperands();
2295 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2298 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2299 SDOperand BitI = N->getOperand(i);
2300 SDOperand BitI1 = N->getOperand(i+1);
2302 if (!isUndefOrEqual(BitI, j))
2304 if (!isUndefOrEqual(BitI1, j))
2311 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2312 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2314 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2315 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2317 unsigned NumElems = N->getNumOperands();
2318 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2321 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2322 SDOperand BitI = N->getOperand(i);
2323 SDOperand BitI1 = N->getOperand(i + 1);
2325 if (!isUndefOrEqual(BitI, j))
2327 if (!isUndefOrEqual(BitI1, j))
2334 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2335 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2336 /// MOVSD, and MOVD, i.e. setting the lowest element.
2337 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2338 if (NumElts != 2 && NumElts != 4)
2341 if (!isUndefOrEqual(Elts[0], NumElts))
2344 for (unsigned i = 1; i < NumElts; ++i) {
2345 if (!isUndefOrEqual(Elts[i], i))
2352 bool X86::isMOVLMask(SDNode *N) {
2353 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2354 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2357 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2358 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2359 /// element of vector 2 and the other elements to come from vector 1 in order.
2360 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2361 bool V2IsSplat = false,
2362 bool V2IsUndef = false) {
2363 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2366 if (!isUndefOrEqual(Ops[0], 0))
2369 for (unsigned i = 1; i < NumOps; ++i) {
2370 SDOperand Arg = Ops[i];
2371 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2372 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2373 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2380 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2381 bool V2IsUndef = false) {
2382 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2383 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2384 V2IsSplat, V2IsUndef);
2387 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2388 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2389 bool X86::isMOVSHDUPMask(SDNode *N) {
2390 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2392 if (N->getNumOperands() != 4)
2395 // Expect 1, 1, 3, 3
2396 for (unsigned i = 0; i < 2; ++i) {
2397 SDOperand Arg = N->getOperand(i);
2398 if (Arg.getOpcode() == ISD::UNDEF) continue;
2399 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2400 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2401 if (Val != 1) return false;
2405 for (unsigned i = 2; i < 4; ++i) {
2406 SDOperand Arg = N->getOperand(i);
2407 if (Arg.getOpcode() == ISD::UNDEF) continue;
2408 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2409 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2410 if (Val != 3) return false;
2414 // Don't use movshdup if it can be done with a shufps.
2418 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2419 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2420 bool X86::isMOVSLDUPMask(SDNode *N) {
2421 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2423 if (N->getNumOperands() != 4)
2426 // Expect 0, 0, 2, 2
2427 for (unsigned i = 0; i < 2; ++i) {
2428 SDOperand Arg = N->getOperand(i);
2429 if (Arg.getOpcode() == ISD::UNDEF) continue;
2430 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2431 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2432 if (Val != 0) return false;
2436 for (unsigned i = 2; i < 4; ++i) {
2437 SDOperand Arg = N->getOperand(i);
2438 if (Arg.getOpcode() == ISD::UNDEF) continue;
2439 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2440 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2441 if (Val != 2) return false;
2445 // Don't use movshdup if it can be done with a shufps.
2449 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2450 /// specifies a identity operation on the LHS or RHS.
2451 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2452 unsigned NumElems = N->getNumOperands();
2453 for (unsigned i = 0; i < NumElems; ++i)
2454 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2459 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2460 /// a splat of a single element.
2461 static bool isSplatMask(SDNode *N) {
2462 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2464 // This is a splat operation if each element of the permute is the same, and
2465 // if the value doesn't reference the second vector.
2466 unsigned NumElems = N->getNumOperands();
2467 SDOperand ElementBase;
2469 for (; i != NumElems; ++i) {
2470 SDOperand Elt = N->getOperand(i);
2471 if (isa<ConstantSDNode>(Elt)) {
2477 if (!ElementBase.Val)
2480 for (; i != NumElems; ++i) {
2481 SDOperand Arg = N->getOperand(i);
2482 if (Arg.getOpcode() == ISD::UNDEF) continue;
2483 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2484 if (Arg != ElementBase) return false;
2487 // Make sure it is a splat of the first vector operand.
2488 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2491 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2492 /// a splat of a single element and it's a 2 or 4 element mask.
2493 bool X86::isSplatMask(SDNode *N) {
2494 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2496 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2497 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2499 return ::isSplatMask(N);
2502 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2503 /// specifies a splat of zero element.
2504 bool X86::isSplatLoMask(SDNode *N) {
2505 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2507 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2508 if (!isUndefOrEqual(N->getOperand(i), 0))
2513 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2514 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2516 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2517 unsigned NumOperands = N->getNumOperands();
2518 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2520 for (unsigned i = 0; i < NumOperands; ++i) {
2522 SDOperand Arg = N->getOperand(NumOperands-i-1);
2523 if (Arg.getOpcode() != ISD::UNDEF)
2524 Val = cast<ConstantSDNode>(Arg)->getValue();
2525 if (Val >= NumOperands) Val -= NumOperands;
2527 if (i != NumOperands - 1)
2534 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2535 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2537 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2539 // 8 nodes, but we only care about the last 4.
2540 for (unsigned i = 7; i >= 4; --i) {
2542 SDOperand Arg = N->getOperand(i);
2543 if (Arg.getOpcode() != ISD::UNDEF)
2544 Val = cast<ConstantSDNode>(Arg)->getValue();
2553 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2554 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2556 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2558 // 8 nodes, but we only care about the first 4.
2559 for (int i = 3; i >= 0; --i) {
2561 SDOperand Arg = N->getOperand(i);
2562 if (Arg.getOpcode() != ISD::UNDEF)
2563 Val = cast<ConstantSDNode>(Arg)->getValue();
2572 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2573 /// specifies a 8 element shuffle that can be broken into a pair of
2574 /// PSHUFHW and PSHUFLW.
2575 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2576 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2578 if (N->getNumOperands() != 8)
2581 // Lower quadword shuffled.
2582 for (unsigned i = 0; i != 4; ++i) {
2583 SDOperand Arg = N->getOperand(i);
2584 if (Arg.getOpcode() == ISD::UNDEF) continue;
2585 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2586 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2591 // Upper quadword shuffled.
2592 for (unsigned i = 4; i != 8; ++i) {
2593 SDOperand Arg = N->getOperand(i);
2594 if (Arg.getOpcode() == ISD::UNDEF) continue;
2595 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2596 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2597 if (Val < 4 || Val > 7)
2604 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2605 /// values in ther permute mask.
2606 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2607 SDOperand &V2, SDOperand &Mask,
2608 SelectionDAG &DAG) {
2609 MVT::ValueType VT = Op.getValueType();
2610 MVT::ValueType MaskVT = Mask.getValueType();
2611 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2612 unsigned NumElems = Mask.getNumOperands();
2613 SmallVector<SDOperand, 8> MaskVec;
2615 for (unsigned i = 0; i != NumElems; ++i) {
2616 SDOperand Arg = Mask.getOperand(i);
2617 if (Arg.getOpcode() == ISD::UNDEF) {
2618 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2621 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2622 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2624 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2626 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2630 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2631 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2634 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2635 /// the two vector operands have swapped position.
2637 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2638 MVT::ValueType MaskVT = Mask.getValueType();
2639 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2640 unsigned NumElems = Mask.getNumOperands();
2641 SmallVector<SDOperand, 8> MaskVec;
2642 for (unsigned i = 0; i != NumElems; ++i) {
2643 SDOperand Arg = Mask.getOperand(i);
2644 if (Arg.getOpcode() == ISD::UNDEF) {
2645 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2648 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2649 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2651 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2653 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2655 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2659 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2660 /// match movhlps. The lower half elements should come from upper half of
2661 /// V1 (and in order), and the upper half elements should come from the upper
2662 /// half of V2 (and in order).
2663 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2664 unsigned NumElems = Mask->getNumOperands();
2667 for (unsigned i = 0, e = 2; i != e; ++i)
2668 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2670 for (unsigned i = 2; i != 4; ++i)
2671 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2676 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2677 /// is promoted to a vector.
2678 static inline bool isScalarLoadToVector(SDNode *N) {
2679 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2680 N = N->getOperand(0).Val;
2681 return ISD::isNON_EXTLoad(N);
2686 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2687 /// match movlp{s|d}. The lower half elements should come from lower half of
2688 /// V1 (and in order), and the upper half elements should come from the upper
2689 /// half of V2 (and in order). And since V1 will become the source of the
2690 /// MOVLP, it must be either a vector load or a scalar load to vector.
2691 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2692 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2694 // Is V2 is a vector load, don't do this transformation. We will try to use
2695 // load folding shufps op.
2696 if (ISD::isNON_EXTLoad(V2))
2699 unsigned NumElems = Mask->getNumOperands();
2700 if (NumElems != 2 && NumElems != 4)
2702 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2703 if (!isUndefOrEqual(Mask->getOperand(i), i))
2705 for (unsigned i = NumElems/2; i != NumElems; ++i)
2706 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2711 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2713 static bool isSplatVector(SDNode *N) {
2714 if (N->getOpcode() != ISD::BUILD_VECTOR)
2717 SDOperand SplatValue = N->getOperand(0);
2718 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2719 if (N->getOperand(i) != SplatValue)
2724 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2726 static bool isUndefShuffle(SDNode *N) {
2727 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2730 SDOperand V1 = N->getOperand(0);
2731 SDOperand V2 = N->getOperand(1);
2732 SDOperand Mask = N->getOperand(2);
2733 unsigned NumElems = Mask.getNumOperands();
2734 for (unsigned i = 0; i != NumElems; ++i) {
2735 SDOperand Arg = Mask.getOperand(i);
2736 if (Arg.getOpcode() != ISD::UNDEF) {
2737 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2738 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2740 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2747 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2749 static inline bool isZeroNode(SDOperand Elt) {
2750 return ((isa<ConstantSDNode>(Elt) &&
2751 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2752 (isa<ConstantFPSDNode>(Elt) &&
2753 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2756 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2757 /// to an zero vector.
2758 static bool isZeroShuffle(SDNode *N) {
2759 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2762 SDOperand V1 = N->getOperand(0);
2763 SDOperand V2 = N->getOperand(1);
2764 SDOperand Mask = N->getOperand(2);
2765 unsigned NumElems = Mask.getNumOperands();
2766 for (unsigned i = 0; i != NumElems; ++i) {
2767 SDOperand Arg = Mask.getOperand(i);
2768 if (Arg.getOpcode() == ISD::UNDEF)
2771 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2772 if (Idx < NumElems) {
2773 unsigned Opc = V1.Val->getOpcode();
2774 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2776 if (Opc != ISD::BUILD_VECTOR ||
2777 !isZeroNode(V1.Val->getOperand(Idx)))
2779 } else if (Idx >= NumElems) {
2780 unsigned Opc = V2.Val->getOpcode();
2781 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2783 if (Opc != ISD::BUILD_VECTOR ||
2784 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2791 /// getZeroVector - Returns a vector of specified type with all zero elements.
2793 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2794 assert(MVT::isVector(VT) && "Expected a vector type");
2796 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2797 // type. This ensures they get CSE'd.
2798 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2800 if (MVT::getSizeInBits(VT) == 64) // MMX
2801 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2803 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2804 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2807 /// getOnesVector - Returns a vector of specified type with all bits set.
2809 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2810 assert(MVT::isVector(VT) && "Expected a vector type");
2812 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2813 // type. This ensures they get CSE'd.
2814 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2816 if (MVT::getSizeInBits(VT) == 64) // MMX
2817 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2819 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2820 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2824 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2825 /// that point to V2 points to its first element.
2826 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2827 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2829 bool Changed = false;
2830 SmallVector<SDOperand, 8> MaskVec;
2831 unsigned NumElems = Mask.getNumOperands();
2832 for (unsigned i = 0; i != NumElems; ++i) {
2833 SDOperand Arg = Mask.getOperand(i);
2834 if (Arg.getOpcode() != ISD::UNDEF) {
2835 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2836 if (Val > NumElems) {
2837 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2841 MaskVec.push_back(Arg);
2845 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2846 &MaskVec[0], MaskVec.size());
2850 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2851 /// operation of specified width.
2852 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2853 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2854 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2856 SmallVector<SDOperand, 8> MaskVec;
2857 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2858 for (unsigned i = 1; i != NumElems; ++i)
2859 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2860 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2863 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2864 /// of specified width.
2865 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2866 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2867 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2868 SmallVector<SDOperand, 8> MaskVec;
2869 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2870 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2871 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2873 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2876 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2877 /// of specified width.
2878 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2879 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2880 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2881 unsigned Half = NumElems/2;
2882 SmallVector<SDOperand, 8> MaskVec;
2883 for (unsigned i = 0; i != Half; ++i) {
2884 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2885 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2887 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2890 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2891 /// element #0 of a vector with the specified index, leaving the rest of the
2892 /// elements in place.
2893 static SDOperand getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2894 SelectionDAG &DAG) {
2895 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2896 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2897 SmallVector<SDOperand, 8> MaskVec;
2898 // Element #0 of the result gets the elt we are replacing.
2899 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2900 for (unsigned i = 1; i != NumElems; ++i)
2901 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2902 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2905 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2907 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2908 SDOperand V1 = Op.getOperand(0);
2909 SDOperand Mask = Op.getOperand(2);
2910 MVT::ValueType VT = Op.getValueType();
2911 unsigned NumElems = Mask.getNumOperands();
2912 Mask = getUnpacklMask(NumElems, DAG);
2913 while (NumElems != 4) {
2914 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2917 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2919 Mask = getZeroVector(MVT::v4i32, DAG);
2920 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2921 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2922 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2925 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2926 /// vector of zero or undef vector. This produces a shuffle where the low
2927 /// element of V2 is swizzled into the zero/undef vector, landing at element
2928 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2929 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, unsigned Idx,
2930 bool isZero, SelectionDAG &DAG) {
2931 MVT::ValueType VT = V2.getValueType();
2932 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2933 unsigned NumElems = MVT::getVectorNumElements(V2.getValueType());
2934 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2935 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2936 SmallVector<SDOperand, 16> MaskVec;
2937 for (unsigned i = 0; i != NumElems; ++i)
2938 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2939 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2941 MaskVec.push_back(DAG.getConstant(i, EVT));
2942 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2943 &MaskVec[0], MaskVec.size());
2944 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2947 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2949 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2950 unsigned NumNonZero, unsigned NumZero,
2951 SelectionDAG &DAG, TargetLowering &TLI) {
2957 for (unsigned i = 0; i < 16; ++i) {
2958 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2959 if (ThisIsNonZero && First) {
2961 V = getZeroVector(MVT::v8i16, DAG);
2963 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2968 SDOperand ThisElt(0, 0), LastElt(0, 0);
2969 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2970 if (LastIsNonZero) {
2971 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2973 if (ThisIsNonZero) {
2974 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2975 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2976 ThisElt, DAG.getConstant(8, MVT::i8));
2978 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2983 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2984 DAG.getIntPtrConstant(i/2));
2988 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2991 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2993 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2994 unsigned NumNonZero, unsigned NumZero,
2995 SelectionDAG &DAG, TargetLowering &TLI) {
3001 for (unsigned i = 0; i < 8; ++i) {
3002 bool isNonZero = (NonZeros & (1 << i)) != 0;
3006 V = getZeroVector(MVT::v8i16, DAG);
3008 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3011 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3012 DAG.getIntPtrConstant(i));
3020 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3021 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3022 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3023 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3024 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3025 // eliminated on x86-32 hosts.
3026 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3029 if (ISD::isBuildVectorAllOnes(Op.Val))
3030 return getOnesVector(Op.getValueType(), DAG);
3031 return getZeroVector(Op.getValueType(), DAG);
3034 MVT::ValueType VT = Op.getValueType();
3035 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3036 unsigned EVTBits = MVT::getSizeInBits(EVT);
3038 unsigned NumElems = Op.getNumOperands();
3039 unsigned NumZero = 0;
3040 unsigned NumNonZero = 0;
3041 unsigned NonZeros = 0;
3042 bool IsAllConstants = true;
3043 SmallSet<SDOperand, 8> Values;
3044 for (unsigned i = 0; i < NumElems; ++i) {
3045 SDOperand Elt = Op.getOperand(i);
3046 if (Elt.getOpcode() == ISD::UNDEF)
3049 if (Elt.getOpcode() != ISD::Constant &&
3050 Elt.getOpcode() != ISD::ConstantFP)
3051 IsAllConstants = false;
3052 if (isZeroNode(Elt))
3055 NonZeros |= (1 << i);
3060 if (NumNonZero == 0) {
3061 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3062 return DAG.getNode(ISD::UNDEF, VT);
3065 // Special case for single non-zero, non-undef, element.
3066 if (NumNonZero == 1 && NumElems <= 4) {
3067 unsigned Idx = CountTrailingZeros_32(NonZeros);
3068 SDOperand Item = Op.getOperand(Idx);
3070 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3071 // the value are obviously zero, truncate the value to i32 and do the
3072 // insertion that way. Only do this if the value is non-constant or if the
3073 // value is a constant being inserted into element 0. It is cheaper to do
3074 // a constant pool load than it is to do a movd + shuffle.
3075 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3076 (!IsAllConstants || Idx == 0)) {
3077 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3078 // Handle MMX and SSE both.
3079 MVT::ValueType VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3080 MVT::ValueType VecElts = VT == MVT::v2i64 ? 4 : 2;
3082 // Truncate the value (which may itself be a constant) to i32, and
3083 // convert it to a vector with movd (S2V+shuffle to zero extend).
3084 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3085 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3086 Item = getShuffleVectorZeroOrUndef(Item, 0, true, DAG);
3088 // Now we have our 32-bit value zero extended in the low element of
3089 // a vector. If Idx != 0, swizzle it into place.
3092 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3093 getSwapEltZeroMask(VecElts, Idx, DAG)
3095 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3097 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3101 // If we have a constant or non-constant insertion into the low element of
3102 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3103 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3104 // depending on what the source datatype is. Because we can only get here
3105 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3107 // Don't do this for i64 values on x86-32.
3108 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3109 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3110 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3111 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3114 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3117 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3118 // is a non-constant being inserted into an element other than the low one,
3119 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3120 // movd/movss) to move this into the low element, then shuffle it into
3122 if (EVTBits == 32) {
3123 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3125 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3126 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3127 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3128 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3129 SmallVector<SDOperand, 8> MaskVec;
3130 for (unsigned i = 0; i < NumElems; i++)
3131 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3132 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3133 &MaskVec[0], MaskVec.size());
3134 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3135 DAG.getNode(ISD::UNDEF, VT), Mask);
3139 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3140 if (Values.size() == 1)
3143 // A vector full of immediates; various special cases are already
3144 // handled, so this is best done with a single constant-pool load.
3148 // Let legalizer expand 2-wide build_vectors.
3152 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3153 if (EVTBits == 8 && NumElems == 16) {
3154 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3156 if (V.Val) return V;
3159 if (EVTBits == 16 && NumElems == 8) {
3160 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3162 if (V.Val) return V;
3165 // If element VT is == 32 bits, turn it into a number of shuffles.
3166 SmallVector<SDOperand, 8> V;
3168 if (NumElems == 4 && NumZero > 0) {
3169 for (unsigned i = 0; i < 4; ++i) {
3170 bool isZero = !(NonZeros & (1 << i));
3172 V[i] = getZeroVector(VT, DAG);
3174 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3177 for (unsigned i = 0; i < 2; ++i) {
3178 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3181 V[i] = V[i*2]; // Must be a zero vector.
3184 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3185 getMOVLMask(NumElems, DAG));
3188 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3189 getMOVLMask(NumElems, DAG));
3192 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3193 getUnpacklMask(NumElems, DAG));
3198 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3199 // clears the upper bits.
3200 // FIXME: we can do the same for v4f32 case when we know both parts of
3201 // the lower half come from scalar_to_vector (loadf32). We should do
3202 // that in post legalizer dag combiner with target specific hooks.
3203 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3205 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3206 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3207 SmallVector<SDOperand, 8> MaskVec;
3208 bool Reverse = (NonZeros & 0x3) == 2;
3209 for (unsigned i = 0; i < 2; ++i)
3211 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3213 MaskVec.push_back(DAG.getConstant(i, EVT));
3214 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3215 for (unsigned i = 0; i < 2; ++i)
3217 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3219 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3220 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3221 &MaskVec[0], MaskVec.size());
3222 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3225 if (Values.size() > 2) {
3226 // Expand into a number of unpckl*.
3228 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3229 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3230 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3231 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3232 for (unsigned i = 0; i < NumElems; ++i)
3233 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3235 while (NumElems != 0) {
3236 for (unsigned i = 0; i < NumElems; ++i)
3237 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3248 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3249 SDOperand PermMask, SelectionDAG &DAG,
3250 TargetLowering &TLI) {
3252 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3253 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3254 MVT::ValueType PtrVT = TLI.getPointerTy();
3255 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3256 PermMask.Val->op_end());
3258 // First record which half of which vector the low elements come from.
3259 SmallVector<unsigned, 4> LowQuad(4);
3260 for (unsigned i = 0; i < 4; ++i) {
3261 SDOperand Elt = MaskElts[i];
3262 if (Elt.getOpcode() == ISD::UNDEF)
3264 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3265 int QuadIdx = EltIdx / 4;
3268 int BestLowQuad = -1;
3269 unsigned MaxQuad = 1;
3270 for (unsigned i = 0; i < 4; ++i) {
3271 if (LowQuad[i] > MaxQuad) {
3273 MaxQuad = LowQuad[i];
3277 // Record which half of which vector the high elements come from.
3278 SmallVector<unsigned, 4> HighQuad(4);
3279 for (unsigned i = 4; i < 8; ++i) {
3280 SDOperand Elt = MaskElts[i];
3281 if (Elt.getOpcode() == ISD::UNDEF)
3283 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3284 int QuadIdx = EltIdx / 4;
3285 ++HighQuad[QuadIdx];
3287 int BestHighQuad = -1;
3289 for (unsigned i = 0; i < 4; ++i) {
3290 if (HighQuad[i] > MaxQuad) {
3292 MaxQuad = HighQuad[i];
3296 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3297 if (BestLowQuad != -1 || BestHighQuad != -1) {
3298 // First sort the 4 chunks in order using shufpd.
3299 SmallVector<SDOperand, 8> MaskVec;
3300 if (BestLowQuad != -1)
3301 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3303 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3304 if (BestHighQuad != -1)
3305 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3307 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3308 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3309 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3310 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3311 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3312 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3314 // Now sort high and low parts separately.
3315 BitVector InOrder(8);
3316 if (BestLowQuad != -1) {
3317 // Sort lower half in order using PSHUFLW.
3319 bool AnyOutOrder = false;
3320 for (unsigned i = 0; i != 4; ++i) {
3321 SDOperand Elt = MaskElts[i];
3322 if (Elt.getOpcode() == ISD::UNDEF) {
3323 MaskVec.push_back(Elt);
3326 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3329 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3330 // If this element is in the right place after this shuffle, then
3332 if ((int)(EltIdx / 4) == BestLowQuad)
3337 for (unsigned i = 4; i != 8; ++i)
3338 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3339 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3340 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3344 if (BestHighQuad != -1) {
3345 // Sort high half in order using PSHUFHW if possible.
3347 for (unsigned i = 0; i != 4; ++i)
3348 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3349 bool AnyOutOrder = false;
3350 for (unsigned i = 4; i != 8; ++i) {
3351 SDOperand Elt = MaskElts[i];
3352 if (Elt.getOpcode() == ISD::UNDEF) {
3353 MaskVec.push_back(Elt);
3356 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3359 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3360 // If this element is in the right place after this shuffle, then
3362 if ((int)(EltIdx / 4) == BestHighQuad)
3367 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3368 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3372 // The other elements are put in the right place using pextrw and pinsrw.
3373 for (unsigned i = 0; i != 8; ++i) {
3376 SDOperand Elt = MaskElts[i];
3377 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3380 SDOperand ExtOp = (EltIdx < 8)
3381 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3382 DAG.getConstant(EltIdx, PtrVT))
3383 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3384 DAG.getConstant(EltIdx - 8, PtrVT));
3385 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3386 DAG.getConstant(i, PtrVT));
3391 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3392 ///as few as possible.
3393 // First, let's find out how many elements are already in the right order.
3394 unsigned V1InOrder = 0;
3395 unsigned V1FromV1 = 0;
3396 unsigned V2InOrder = 0;
3397 unsigned V2FromV2 = 0;
3398 SmallVector<SDOperand, 8> V1Elts;
3399 SmallVector<SDOperand, 8> V2Elts;
3400 for (unsigned i = 0; i < 8; ++i) {
3401 SDOperand Elt = MaskElts[i];
3402 if (Elt.getOpcode() == ISD::UNDEF) {
3403 V1Elts.push_back(Elt);
3404 V2Elts.push_back(Elt);
3409 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3411 V1Elts.push_back(Elt);
3412 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3414 } else if (EltIdx == i+8) {
3415 V1Elts.push_back(Elt);
3416 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3418 } else if (EltIdx < 8) {
3419 V1Elts.push_back(Elt);
3422 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3427 if (V2InOrder > V1InOrder) {
3428 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3430 std::swap(V1Elts, V2Elts);
3431 std::swap(V1FromV1, V2FromV2);
3434 if ((V1FromV1 + V1InOrder) != 8) {
3435 // Some elements are from V2.
3437 // If there are elements that are from V1 but out of place,
3438 // then first sort them in place
3439 SmallVector<SDOperand, 8> MaskVec;
3440 for (unsigned i = 0; i < 8; ++i) {
3441 SDOperand Elt = V1Elts[i];
3442 if (Elt.getOpcode() == ISD::UNDEF) {
3443 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3446 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3448 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3450 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3452 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3453 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3457 for (unsigned i = 0; i < 8; ++i) {
3458 SDOperand Elt = V1Elts[i];
3459 if (Elt.getOpcode() == ISD::UNDEF)
3461 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3464 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3465 DAG.getConstant(EltIdx - 8, PtrVT));
3466 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3467 DAG.getConstant(i, PtrVT));
3471 // All elements are from V1.
3473 for (unsigned i = 0; i < 8; ++i) {
3474 SDOperand Elt = V1Elts[i];
3475 if (Elt.getOpcode() == ISD::UNDEF)
3477 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3478 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3479 DAG.getConstant(EltIdx, PtrVT));
3480 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3481 DAG.getConstant(i, PtrVT));
3487 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3488 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3489 /// done when every pair / quad of shuffle mask elements point to elements in
3490 /// the right sequence. e.g.
3491 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3493 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3495 SDOperand PermMask, SelectionDAG &DAG,
3496 TargetLowering &TLI) {
3497 unsigned NumElems = PermMask.getNumOperands();
3498 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3499 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3500 MVT::ValueType NewVT = MaskVT;
3502 case MVT::v4f32: NewVT = MVT::v2f64; break;
3503 case MVT::v4i32: NewVT = MVT::v2i64; break;
3504 case MVT::v8i16: NewVT = MVT::v4i32; break;
3505 case MVT::v16i8: NewVT = MVT::v4i32; break;
3506 default: assert(false && "Unexpected!");
3509 if (NewWidth == 2) {
3510 if (MVT::isInteger(VT))
3515 unsigned Scale = NumElems / NewWidth;
3516 SmallVector<SDOperand, 8> MaskVec;
3517 for (unsigned i = 0; i < NumElems; i += Scale) {
3518 unsigned StartIdx = ~0U;
3519 for (unsigned j = 0; j < Scale; ++j) {
3520 SDOperand Elt = PermMask.getOperand(i+j);
3521 if (Elt.getOpcode() == ISD::UNDEF)
3523 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3524 if (StartIdx == ~0U)
3525 StartIdx = EltIdx - (EltIdx % Scale);
3526 if (EltIdx != StartIdx + j)
3529 if (StartIdx == ~0U)
3530 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3532 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3535 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3536 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3537 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3538 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3539 &MaskVec[0], MaskVec.size()));
3543 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3544 SDOperand V1 = Op.getOperand(0);
3545 SDOperand V2 = Op.getOperand(1);
3546 SDOperand PermMask = Op.getOperand(2);
3547 MVT::ValueType VT = Op.getValueType();
3548 unsigned NumElems = PermMask.getNumOperands();
3549 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3550 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3551 bool V1IsSplat = false;
3552 bool V2IsSplat = false;
3554 if (isUndefShuffle(Op.Val))
3555 return DAG.getNode(ISD::UNDEF, VT);
3557 if (isZeroShuffle(Op.Val))
3558 return getZeroVector(VT, DAG);
3560 if (isIdentityMask(PermMask.Val))
3562 else if (isIdentityMask(PermMask.Val, true))
3565 if (isSplatMask(PermMask.Val)) {
3566 if (NumElems <= 4) return Op;
3567 // Promote it to a v4i32 splat.
3568 return PromoteSplat(Op, DAG);
3571 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3573 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3574 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3576 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3577 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3578 // FIXME: Figure out a cleaner way to do this.
3579 // Try to make use of movq to zero out the top part.
3580 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3581 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3583 SDOperand NewV1 = NewOp.getOperand(0);
3584 SDOperand NewV2 = NewOp.getOperand(1);
3585 SDOperand NewMask = NewOp.getOperand(2);
3586 if (isCommutedMOVL(NewMask.Val, true, false)) {
3587 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3588 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3589 NewV1, NewV2, getMOVLMask(2, DAG));
3590 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3593 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3594 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3595 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3596 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3600 if (X86::isMOVLMask(PermMask.Val))
3601 return (V1IsUndef) ? V2 : Op;
3603 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3604 X86::isMOVSLDUPMask(PermMask.Val) ||
3605 X86::isMOVHLPSMask(PermMask.Val) ||
3606 X86::isMOVHPMask(PermMask.Val) ||
3607 X86::isMOVLPMask(PermMask.Val))
3610 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3611 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3612 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3614 bool Commuted = false;
3615 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3616 // 1,1,1,1 -> v8i16 though.
3617 V1IsSplat = isSplatVector(V1.Val);
3618 V2IsSplat = isSplatVector(V2.Val);
3620 // Canonicalize the splat or undef, if present, to be on the RHS.
3621 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3622 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3623 std::swap(V1IsSplat, V2IsSplat);
3624 std::swap(V1IsUndef, V2IsUndef);
3628 // FIXME: Figure out a cleaner way to do this.
3629 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3630 if (V2IsUndef) return V1;
3631 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3633 // V2 is a splat, so the mask may be malformed. That is, it may point
3634 // to any V2 element. The instruction selectior won't like this. Get
3635 // a corrected mask and commute to form a proper MOVS{S|D}.
3636 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3637 if (NewMask.Val != PermMask.Val)
3638 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3643 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3644 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3645 X86::isUNPCKLMask(PermMask.Val) ||
3646 X86::isUNPCKHMask(PermMask.Val))
3650 // Normalize mask so all entries that point to V2 points to its first
3651 // element then try to match unpck{h|l} again. If match, return a
3652 // new vector_shuffle with the corrected mask.
3653 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3654 if (NewMask.Val != PermMask.Val) {
3655 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3656 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3657 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3658 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3659 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3660 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3665 // Normalize the node to match x86 shuffle ops if needed
3666 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3667 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3670 // Commute is back and try unpck* again.
3671 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3672 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3673 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3674 X86::isUNPCKLMask(PermMask.Val) ||
3675 X86::isUNPCKHMask(PermMask.Val))
3679 // If VT is integer, try PSHUF* first, then SHUFP*.
3680 if (MVT::isInteger(VT)) {
3681 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3682 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3683 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3684 X86::isPSHUFDMask(PermMask.Val)) ||
3685 X86::isPSHUFHWMask(PermMask.Val) ||
3686 X86::isPSHUFLWMask(PermMask.Val)) {
3687 if (V2.getOpcode() != ISD::UNDEF)
3688 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3689 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3693 if (X86::isSHUFPMask(PermMask.Val) &&
3694 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3697 // Floating point cases in the other order.
3698 if (X86::isSHUFPMask(PermMask.Val))
3700 if (X86::isPSHUFDMask(PermMask.Val) ||
3701 X86::isPSHUFHWMask(PermMask.Val) ||
3702 X86::isPSHUFLWMask(PermMask.Val)) {
3703 if (V2.getOpcode() != ISD::UNDEF)
3704 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3705 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3710 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3711 if (VT == MVT::v8i16) {
3712 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3717 // Handle all 4 wide cases with a number of shuffles.
3718 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3719 // Don't do this for MMX.
3720 MVT::ValueType MaskVT = PermMask.getValueType();
3721 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3722 SmallVector<std::pair<int, int>, 8> Locs;
3723 Locs.reserve(NumElems);
3724 SmallVector<SDOperand, 8> Mask1(NumElems,
3725 DAG.getNode(ISD::UNDEF, MaskEVT));
3726 SmallVector<SDOperand, 8> Mask2(NumElems,
3727 DAG.getNode(ISD::UNDEF, MaskEVT));
3730 // If no more than two elements come from either vector. This can be
3731 // implemented with two shuffles. First shuffle gather the elements.
3732 // The second shuffle, which takes the first shuffle as both of its
3733 // vector operands, put the elements into the right order.
3734 for (unsigned i = 0; i != NumElems; ++i) {
3735 SDOperand Elt = PermMask.getOperand(i);
3736 if (Elt.getOpcode() == ISD::UNDEF) {
3737 Locs[i] = std::make_pair(-1, -1);
3739 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3740 if (Val < NumElems) {
3741 Locs[i] = std::make_pair(0, NumLo);
3745 Locs[i] = std::make_pair(1, NumHi);
3746 if (2+NumHi < NumElems)
3747 Mask1[2+NumHi] = Elt;
3752 if (NumLo <= 2 && NumHi <= 2) {
3753 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3754 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3755 &Mask1[0], Mask1.size()));
3756 for (unsigned i = 0; i != NumElems; ++i) {
3757 if (Locs[i].first == -1)
3760 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3761 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3762 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3766 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3767 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3768 &Mask2[0], Mask2.size()));
3771 // Break it into (shuffle shuffle_hi, shuffle_lo).
3773 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3774 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3775 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3776 unsigned MaskIdx = 0;
3778 unsigned HiIdx = NumElems/2;
3779 for (unsigned i = 0; i != NumElems; ++i) {
3780 if (i == NumElems/2) {
3786 SDOperand Elt = PermMask.getOperand(i);
3787 if (Elt.getOpcode() == ISD::UNDEF) {
3788 Locs[i] = std::make_pair(-1, -1);
3789 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3790 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3791 (*MaskPtr)[LoIdx] = Elt;
3794 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3795 (*MaskPtr)[HiIdx] = Elt;
3800 SDOperand LoShuffle =
3801 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3802 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3803 &LoMask[0], LoMask.size()));
3804 SDOperand HiShuffle =
3805 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3806 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3807 &HiMask[0], HiMask.size()));
3808 SmallVector<SDOperand, 8> MaskOps;
3809 for (unsigned i = 0; i != NumElems; ++i) {
3810 if (Locs[i].first == -1) {
3811 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3813 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3814 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3817 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3818 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3819 &MaskOps[0], MaskOps.size()));
3826 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3827 SelectionDAG &DAG) {
3828 MVT::ValueType VT = Op.getValueType();
3829 if (MVT::getSizeInBits(VT) == 8) {
3830 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3831 Op.getOperand(0), Op.getOperand(1));
3832 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3833 DAG.getValueType(VT));
3834 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3835 } else if (MVT::getSizeInBits(VT) == 16) {
3836 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3837 Op.getOperand(0), Op.getOperand(1));
3838 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3839 DAG.getValueType(VT));
3840 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3847 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3848 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3851 if (Subtarget->hasSSE41())
3852 return LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3854 MVT::ValueType VT = Op.getValueType();
3855 // TODO: handle v16i8.
3856 if (MVT::getSizeInBits(VT) == 16) {
3857 SDOperand Vec = Op.getOperand(0);
3858 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3860 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3861 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3862 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3864 // Transform it so it match pextrw which produces a 32-bit result.
3865 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3866 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3867 Op.getOperand(0), Op.getOperand(1));
3868 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3869 DAG.getValueType(VT));
3870 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3871 } else if (MVT::getSizeInBits(VT) == 32) {
3872 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3875 // SHUFPS the element to the lowest double word, then movss.
3876 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3877 SmallVector<SDOperand, 8> IdxVec;
3879 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3881 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3883 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3885 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3886 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3887 &IdxVec[0], IdxVec.size());
3888 SDOperand Vec = Op.getOperand(0);
3889 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3890 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3891 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3892 DAG.getIntPtrConstant(0));
3893 } else if (MVT::getSizeInBits(VT) == 64) {
3894 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3895 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3896 // to match extract_elt for f64.
3897 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3901 // UNPCKHPD the element to the lowest double word, then movsd.
3902 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3903 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3904 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3905 SmallVector<SDOperand, 8> IdxVec;
3906 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3908 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3909 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3910 &IdxVec[0], IdxVec.size());
3911 SDOperand Vec = Op.getOperand(0);
3912 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3913 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3914 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3915 DAG.getIntPtrConstant(0));
3922 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3923 MVT::ValueType VT = Op.getValueType();
3924 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3926 SDOperand N0 = Op.getOperand(0);
3927 SDOperand N1 = Op.getOperand(1);
3928 SDOperand N2 = Op.getOperand(2);
3930 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3931 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3933 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3935 if (N1.getValueType() != MVT::i32)
3936 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3937 if (N2.getValueType() != MVT::i32)
3938 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3939 return DAG.getNode(Opc, VT, N0, N1, N2);
3940 } else if (EVT == MVT::f32) {
3941 // Bits [7:6] of the constant are the source select. This will always be
3942 // zero here. The DAG Combiner may combine an extract_elt index into these
3943 // bits. For example (insert (extract, 3), 2) could be matched by putting
3944 // the '3' into bits [7:6] of X86ISD::INSERTPS.
3945 // Bits [5:4] of the constant are the destination select. This is the
3946 // value of the incoming immediate.
3947 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
3948 // combine either bitwise AND or insert of float 0.0 to set these bits.
3949 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3950 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3956 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3957 MVT::ValueType VT = Op.getValueType();
3958 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3960 if (Subtarget->hasSSE41())
3961 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3966 SDOperand N0 = Op.getOperand(0);
3967 SDOperand N1 = Op.getOperand(1);
3968 SDOperand N2 = Op.getOperand(2);
3970 if (MVT::getSizeInBits(EVT) == 16) {
3971 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3972 // as its second argument.
3973 if (N1.getValueType() != MVT::i32)
3974 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3975 if (N2.getValueType() != MVT::i32)
3976 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3977 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3983 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3984 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3985 MVT::ValueType VT = MVT::v2i32;
3986 switch (Op.getValueType()) {
3993 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
3994 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
3997 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3998 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3999 // one of the above mentioned nodes. It has to be wrapped because otherwise
4000 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4001 // be used to form addressing mode. These wrapped nodes will be selected
4004 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
4005 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4006 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
4008 CP->getAlignment());
4009 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4010 // With PIC, the address is actually $g + Offset.
4011 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4012 !Subtarget->isPICStyleRIPRel()) {
4013 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4014 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4022 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4023 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4024 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4025 // If it's a debug information descriptor, don't mess with it.
4026 if (DAG.isVerifiedDebugInfoDesc(Op))
4028 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4029 // With PIC, the address is actually $g + Offset.
4030 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4031 !Subtarget->isPICStyleRIPRel()) {
4032 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4033 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4037 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4038 // load the value at address GV, not the value of GV itself. This means that
4039 // the GlobalAddress must be in the base or index register of the address, not
4040 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4041 // The same applies for external symbols during PIC codegen
4042 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4043 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4044 PseudoSourceValue::getGOT(), 0);
4049 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
4051 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4052 const MVT::ValueType PtrVT) {
4054 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4055 DAG.getNode(X86ISD::GlobalBaseReg,
4057 InFlag = Chain.getValue(1);
4059 // emit leal symbol@TLSGD(,%ebx,1), %eax
4060 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4061 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4062 GA->getValueType(0),
4064 SDOperand Ops[] = { Chain, TGA, InFlag };
4065 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4066 InFlag = Result.getValue(2);
4067 Chain = Result.getValue(1);
4069 // call ___tls_get_addr. This function receives its argument in
4070 // the register EAX.
4071 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4072 InFlag = Chain.getValue(1);
4074 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4075 SDOperand Ops1[] = { Chain,
4076 DAG.getTargetExternalSymbol("___tls_get_addr",
4078 DAG.getRegister(X86::EAX, PtrVT),
4079 DAG.getRegister(X86::EBX, PtrVT),
4081 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4082 InFlag = Chain.getValue(1);
4084 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4087 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4088 // "local exec" model.
4090 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4091 const MVT::ValueType PtrVT) {
4092 // Get the Thread Pointer
4093 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4094 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4096 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4097 GA->getValueType(0),
4099 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4101 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4102 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4103 PseudoSourceValue::getGOT(), 0);
4105 // The address of the thread local variable is the add of the thread
4106 // pointer with the offset of the variable.
4107 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4111 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4112 // TODO: implement the "local dynamic" model
4113 // TODO: implement the "initial exec"model for pic executables
4114 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4115 "TLS not implemented for non-ELF and 64-bit targets");
4116 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4117 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4118 // otherwise use the "Local Exec"TLS Model
4119 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4120 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4122 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4126 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4127 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4128 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4129 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4130 // With PIC, the address is actually $g + Offset.
4131 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4132 !Subtarget->isPICStyleRIPRel()) {
4133 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4134 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4141 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4142 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4143 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4144 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4145 // With PIC, the address is actually $g + Offset.
4146 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4147 !Subtarget->isPICStyleRIPRel()) {
4148 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4149 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4156 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4157 /// take a 2 x i32 value to shift plus a shift amount.
4158 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4159 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4160 MVT::ValueType VT = Op.getValueType();
4161 unsigned VTBits = MVT::getSizeInBits(VT);
4162 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4163 SDOperand ShOpLo = Op.getOperand(0);
4164 SDOperand ShOpHi = Op.getOperand(1);
4165 SDOperand ShAmt = Op.getOperand(2);
4166 SDOperand Tmp1 = isSRA ?
4167 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4168 DAG.getConstant(0, VT);
4170 SDOperand Tmp2, Tmp3;
4171 if (Op.getOpcode() == ISD::SHL_PARTS) {
4172 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4173 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4175 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4176 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4179 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4180 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4181 DAG.getConstant(VTBits, MVT::i8));
4182 SDOperand Cond = DAG.getNode(X86ISD::CMP, VT,
4183 AndNode, DAG.getConstant(0, MVT::i8));
4186 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4187 VTs = DAG.getNodeValueTypes(VT, MVT::Flag);
4188 SmallVector<SDOperand, 4> Ops;
4189 if (Op.getOpcode() == ISD::SHL_PARTS) {
4190 Ops.push_back(Tmp2);
4191 Ops.push_back(Tmp3);
4193 Ops.push_back(Cond);
4194 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4197 Ops.push_back(Tmp3);
4198 Ops.push_back(Tmp1);
4200 Ops.push_back(Cond);
4201 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4203 Ops.push_back(Tmp2);
4204 Ops.push_back(Tmp3);
4206 Ops.push_back(Cond);
4207 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4210 Ops.push_back(Tmp3);
4211 Ops.push_back(Tmp1);
4213 Ops.push_back(Cond);
4214 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4217 VTs = DAG.getNodeValueTypes(VT, VT);
4221 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4224 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4225 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4226 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
4227 "Unknown SINT_TO_FP to lower!");
4229 // These are really Legal; caller falls through into that case.
4230 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4232 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4233 Subtarget->is64Bit())
4236 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4237 MachineFunction &MF = DAG.getMachineFunction();
4238 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4239 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4240 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4242 PseudoSourceValue::getFixedStack(),
4247 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4249 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4251 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4252 SmallVector<SDOperand, 8> Ops;
4253 Ops.push_back(Chain);
4254 Ops.push_back(StackSlot);
4255 Ops.push_back(DAG.getValueType(SrcVT));
4256 SDOperand Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4257 Tys, &Ops[0], Ops.size());
4260 Chain = Result.getValue(1);
4261 SDOperand InFlag = Result.getValue(2);
4263 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4264 // shouldn't be necessary except that RFP cannot be live across
4265 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4266 MachineFunction &MF = DAG.getMachineFunction();
4267 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4268 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4269 Tys = DAG.getVTList(MVT::Other);
4270 SmallVector<SDOperand, 8> Ops;
4271 Ops.push_back(Chain);
4272 Ops.push_back(Result);
4273 Ops.push_back(StackSlot);
4274 Ops.push_back(DAG.getValueType(Op.getValueType()));
4275 Ops.push_back(InFlag);
4276 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4277 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4278 PseudoSourceValue::getFixedStack(), SSFI);
4284 std::pair<SDOperand,SDOperand> X86TargetLowering::
4285 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4286 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4287 "Unknown FP_TO_SINT to lower!");
4289 // These are really Legal.
4290 if (Op.getValueType() == MVT::i32 &&
4291 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4292 return std::make_pair(SDOperand(), SDOperand());
4293 if (Subtarget->is64Bit() &&
4294 Op.getValueType() == MVT::i64 &&
4295 Op.getOperand(0).getValueType() != MVT::f80)
4296 return std::make_pair(SDOperand(), SDOperand());
4298 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4300 MachineFunction &MF = DAG.getMachineFunction();
4301 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4302 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4303 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4305 switch (Op.getValueType()) {
4306 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4307 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4308 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4309 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4312 SDOperand Chain = DAG.getEntryNode();
4313 SDOperand Value = Op.getOperand(0);
4314 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4315 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4316 Chain = DAG.getStore(Chain, Value, StackSlot,
4317 PseudoSourceValue::getFixedStack(), SSFI);
4318 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4320 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4322 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4323 Chain = Value.getValue(1);
4324 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4325 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4328 // Build the FP_TO_INT*_IN_MEM
4329 SDOperand Ops[] = { Chain, Value, StackSlot };
4330 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4332 return std::make_pair(FIST, StackSlot);
4335 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4336 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4337 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4338 if (FIST.Val == 0) return SDOperand();
4341 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4344 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4345 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4346 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4347 if (FIST.Val == 0) return 0;
4349 // Return an i64 load from the stack slot.
4350 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4352 // Use a MERGE_VALUES node to drop the chain result value.
4353 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4356 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4357 MVT::ValueType VT = Op.getValueType();
4358 MVT::ValueType EltVT = VT;
4359 if (MVT::isVector(VT))
4360 EltVT = MVT::getVectorElementType(VT);
4361 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4362 std::vector<Constant*> CV;
4363 if (EltVT == MVT::f64) {
4364 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4368 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4374 Constant *C = ConstantVector::get(CV);
4375 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4376 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4377 PseudoSourceValue::getConstantPool(), 0,
4379 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4382 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4383 MVT::ValueType VT = Op.getValueType();
4384 MVT::ValueType EltVT = VT;
4385 unsigned EltNum = 1;
4386 if (MVT::isVector(VT)) {
4387 EltVT = MVT::getVectorElementType(VT);
4388 EltNum = MVT::getVectorNumElements(VT);
4390 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4391 std::vector<Constant*> CV;
4392 if (EltVT == MVT::f64) {
4393 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4397 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4403 Constant *C = ConstantVector::get(CV);
4404 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4405 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4406 PseudoSourceValue::getConstantPool(), 0,
4408 if (MVT::isVector(VT)) {
4409 return DAG.getNode(ISD::BIT_CONVERT, VT,
4410 DAG.getNode(ISD::XOR, MVT::v2i64,
4411 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4412 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4414 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4418 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4419 SDOperand Op0 = Op.getOperand(0);
4420 SDOperand Op1 = Op.getOperand(1);
4421 MVT::ValueType VT = Op.getValueType();
4422 MVT::ValueType SrcVT = Op1.getValueType();
4423 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4425 // If second operand is smaller, extend it first.
4426 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4427 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4429 SrcTy = MVT::getTypeForValueType(SrcVT);
4431 // And if it is bigger, shrink it first.
4432 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4433 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4435 SrcTy = MVT::getTypeForValueType(SrcVT);
4438 // At this point the operands and the result should have the same
4439 // type, and that won't be f80 since that is not custom lowered.
4441 // First get the sign bit of second operand.
4442 std::vector<Constant*> CV;
4443 if (SrcVT == MVT::f64) {
4444 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4445 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4447 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4448 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4449 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4450 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4452 Constant *C = ConstantVector::get(CV);
4453 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4454 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4455 PseudoSourceValue::getConstantPool(), 0,
4457 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4459 // Shift sign bit right or left if the two operands have different types.
4460 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4461 // Op0 is MVT::f32, Op1 is MVT::f64.
4462 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4463 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4464 DAG.getConstant(32, MVT::i32));
4465 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4466 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4467 DAG.getIntPtrConstant(0));
4470 // Clear first operand sign bit.
4472 if (VT == MVT::f64) {
4473 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4474 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4476 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4477 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4478 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4479 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4481 C = ConstantVector::get(CV);
4482 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4483 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4484 PseudoSourceValue::getConstantPool(), 0,
4486 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4488 // Or the value with the sign bit.
4489 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4492 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4493 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4495 SDOperand Op0 = Op.getOperand(0);
4496 SDOperand Op1 = Op.getOperand(1);
4497 SDOperand CC = Op.getOperand(2);
4498 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4499 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4502 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4504 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4505 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4506 DAG.getConstant(X86CC, MVT::i8), Cond);
4509 assert(isFP && "Illegal integer SetCC!");
4511 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4512 switch (SetCCOpcode) {
4513 default: assert(false && "Illegal floating point SetCC!");
4514 case ISD::SETOEQ: { // !PF & ZF
4515 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4516 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4517 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4518 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4519 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4521 case ISD::SETUNE: { // PF | !ZF
4522 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4523 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4524 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4525 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4526 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4532 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4533 bool addTest = true;
4534 SDOperand Cond = Op.getOperand(0);
4537 if (Cond.getOpcode() == ISD::SETCC)
4538 Cond = LowerSETCC(Cond, DAG);
4540 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4541 // setting operand in place of the X86ISD::SETCC.
4542 if (Cond.getOpcode() == X86ISD::SETCC) {
4543 CC = Cond.getOperand(0);
4545 SDOperand Cmp = Cond.getOperand(1);
4546 unsigned Opc = Cmp.getOpcode();
4547 MVT::ValueType VT = Op.getValueType();
4549 bool IllegalFPCMov = false;
4550 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4551 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4552 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4554 if ((Opc == X86ISD::CMP ||
4555 Opc == X86ISD::COMI ||
4556 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4563 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4564 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4567 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4569 SmallVector<SDOperand, 4> Ops;
4570 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4571 // condition is true.
4572 Ops.push_back(Op.getOperand(2));
4573 Ops.push_back(Op.getOperand(1));
4575 Ops.push_back(Cond);
4576 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4579 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4580 bool addTest = true;
4581 SDOperand Chain = Op.getOperand(0);
4582 SDOperand Cond = Op.getOperand(1);
4583 SDOperand Dest = Op.getOperand(2);
4586 if (Cond.getOpcode() == ISD::SETCC)
4587 Cond = LowerSETCC(Cond, DAG);
4589 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4590 // setting operand in place of the X86ISD::SETCC.
4591 if (Cond.getOpcode() == X86ISD::SETCC) {
4592 CC = Cond.getOperand(0);
4594 SDOperand Cmp = Cond.getOperand(1);
4595 unsigned Opc = Cmp.getOpcode();
4596 if (Opc == X86ISD::CMP ||
4597 Opc == X86ISD::COMI ||
4598 Opc == X86ISD::UCOMI) {
4605 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4606 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4608 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4609 Chain, Op.getOperand(2), CC, Cond);
4613 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4614 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4615 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4616 // that the guard pages used by the OS virtual memory manager are allocated in
4617 // correct sequence.
4619 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4620 SelectionDAG &DAG) {
4621 assert(Subtarget->isTargetCygMing() &&
4622 "This should be used only on Cygwin/Mingw targets");
4625 SDOperand Chain = Op.getOperand(0);
4626 SDOperand Size = Op.getOperand(1);
4627 // FIXME: Ensure alignment here
4631 MVT::ValueType IntPtr = getPointerTy();
4632 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4634 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4635 Flag = Chain.getValue(1);
4637 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4638 SDOperand Ops[] = { Chain,
4639 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4640 DAG.getRegister(X86::EAX, IntPtr),
4642 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4643 Flag = Chain.getValue(1);
4645 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4647 std::vector<MVT::ValueType> Tys;
4648 Tys.push_back(SPTy);
4649 Tys.push_back(MVT::Other);
4650 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4651 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4654 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4655 SDOperand InFlag(0, 0);
4656 SDOperand Chain = Op.getOperand(0);
4658 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4659 if (Align == 0) Align = 1;
4661 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4662 // If not DWORD aligned or size is more than the threshold, call memset.
4663 // The libc version is likely to be faster for these cases. It can use the
4664 // address value and run time information about the CPU.
4665 if ((Align & 3) != 0 ||
4666 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4667 MVT::ValueType IntPtr = getPointerTy();
4668 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4669 TargetLowering::ArgListTy Args;
4670 TargetLowering::ArgListEntry Entry;
4671 Entry.Node = Op.getOperand(1);
4672 Entry.Ty = IntPtrTy;
4673 Args.push_back(Entry);
4674 // Extend the unsigned i8 argument to be an int value for the call.
4675 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4676 Entry.Ty = IntPtrTy;
4677 Args.push_back(Entry);
4678 Entry.Node = Op.getOperand(3);
4679 Args.push_back(Entry);
4680 std::pair<SDOperand,SDOperand> CallResult =
4681 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4682 false, DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4683 return CallResult.second;
4688 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4689 unsigned BytesLeft = 0;
4690 bool TwoRepStos = false;
4693 uint64_t Val = ValC->getValue() & 255;
4695 // If the value is a constant, then we can potentially use larger sets.
4696 switch (Align & 3) {
4697 case 2: // WORD aligned
4700 Val = (Val << 8) | Val;
4702 case 0: // DWORD aligned
4705 Val = (Val << 8) | Val;
4706 Val = (Val << 16) | Val;
4707 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4710 Val = (Val << 32) | Val;
4713 default: // Byte aligned
4716 Count = Op.getOperand(3);
4720 if (AVT > MVT::i8) {
4722 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4723 Count = DAG.getIntPtrConstant(I->getValue() / UBytes);
4724 BytesLeft = I->getValue() % UBytes;
4726 assert(AVT >= MVT::i32 &&
4727 "Do not use rep;stos if not at least DWORD aligned");
4728 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4729 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4734 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4736 InFlag = Chain.getValue(1);
4739 Count = Op.getOperand(3);
4740 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4741 InFlag = Chain.getValue(1);
4744 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4746 InFlag = Chain.getValue(1);
4747 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4748 Op.getOperand(1), InFlag);
4749 InFlag = Chain.getValue(1);
4751 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4752 SmallVector<SDOperand, 8> Ops;
4753 Ops.push_back(Chain);
4754 Ops.push_back(DAG.getValueType(AVT));
4755 Ops.push_back(InFlag);
4756 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4759 InFlag = Chain.getValue(1);
4760 Count = Op.getOperand(3);
4761 MVT::ValueType CVT = Count.getValueType();
4762 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4763 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4764 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4766 InFlag = Chain.getValue(1);
4767 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4769 Ops.push_back(Chain);
4770 Ops.push_back(DAG.getValueType(MVT::i8));
4771 Ops.push_back(InFlag);
4772 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4773 } else if (BytesLeft) {
4774 // Issue stores for the last 1 - 7 bytes.
4776 unsigned Val = ValC->getValue() & 255;
4777 unsigned Offset = I->getValue() - BytesLeft;
4778 SDOperand DstAddr = Op.getOperand(1);
4779 MVT::ValueType AddrVT = DstAddr.getValueType();
4780 if (BytesLeft >= 4) {
4781 Val = (Val << 8) | Val;
4782 Val = (Val << 16) | Val;
4783 Value = DAG.getConstant(Val, MVT::i32);
4784 Chain = DAG.getStore(Chain, Value,
4785 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4786 DAG.getConstant(Offset, AddrVT)),
4791 if (BytesLeft >= 2) {
4792 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4793 Chain = DAG.getStore(Chain, Value,
4794 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4795 DAG.getConstant(Offset, AddrVT)),
4800 if (BytesLeft == 1) {
4801 Value = DAG.getConstant(Val, MVT::i8);
4802 Chain = DAG.getStore(Chain, Value,
4803 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4804 DAG.getConstant(Offset, AddrVT)),
4812 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4817 SelectionDAG &DAG) {
4819 unsigned BytesLeft = 0;
4820 switch (Align & 3) {
4821 case 2: // WORD aligned
4824 case 0: // DWORD aligned
4826 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4829 default: // Byte aligned
4834 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4835 SDOperand Count = DAG.getIntPtrConstant(Size / UBytes);
4836 BytesLeft = Size % UBytes;
4838 SDOperand InFlag(0, 0);
4839 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4841 InFlag = Chain.getValue(1);
4842 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4844 InFlag = Chain.getValue(1);
4845 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4847 InFlag = Chain.getValue(1);
4849 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4850 SmallVector<SDOperand, 8> Ops;
4851 Ops.push_back(Chain);
4852 Ops.push_back(DAG.getValueType(AVT));
4853 Ops.push_back(InFlag);
4854 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4857 // Issue loads and stores for the last 1 - 7 bytes.
4858 unsigned Offset = Size - BytesLeft;
4859 SDOperand DstAddr = Dest;
4860 MVT::ValueType DstVT = DstAddr.getValueType();
4861 SDOperand SrcAddr = Source;
4862 MVT::ValueType SrcVT = SrcAddr.getValueType();
4864 if (BytesLeft >= 4) {
4865 Value = DAG.getLoad(MVT::i32, Chain,
4866 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4867 DAG.getConstant(Offset, SrcVT)),
4869 Chain = Value.getValue(1);
4870 Chain = DAG.getStore(Chain, Value,
4871 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4872 DAG.getConstant(Offset, DstVT)),
4877 if (BytesLeft >= 2) {
4878 Value = DAG.getLoad(MVT::i16, Chain,
4879 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4880 DAG.getConstant(Offset, SrcVT)),
4882 Chain = Value.getValue(1);
4883 Chain = DAG.getStore(Chain, Value,
4884 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4885 DAG.getConstant(Offset, DstVT)),
4891 if (BytesLeft == 1) {
4892 Value = DAG.getLoad(MVT::i8, Chain,
4893 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4894 DAG.getConstant(Offset, SrcVT)),
4896 Chain = Value.getValue(1);
4897 Chain = DAG.getStore(Chain, Value,
4898 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4899 DAG.getConstant(Offset, DstVT)),
4907 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4908 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4909 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4910 SDOperand TheChain = N->getOperand(0);
4911 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4912 if (Subtarget->is64Bit()) {
4913 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4914 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4915 MVT::i64, rax.getValue(2));
4916 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4917 DAG.getConstant(32, MVT::i8));
4919 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4922 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4923 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4926 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4927 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4928 MVT::i32, eax.getValue(2));
4929 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4930 SDOperand Ops[] = { eax, edx };
4931 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4933 // Use a MERGE_VALUES to return the value and chain.
4934 Ops[1] = edx.getValue(1);
4935 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4936 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4939 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4940 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4942 if (!Subtarget->is64Bit()) {
4943 // vastart just stores the address of the VarArgsFrameIndex slot into the
4944 // memory location argument.
4945 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4946 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4950 // gp_offset (0 - 6 * 8)
4951 // fp_offset (48 - 48 + 8 * 16)
4952 // overflow_arg_area (point to parameters coming in memory).
4954 SmallVector<SDOperand, 8> MemOps;
4955 SDOperand FIN = Op.getOperand(1);
4957 SDOperand Store = DAG.getStore(Op.getOperand(0),
4958 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4960 MemOps.push_back(Store);
4963 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4964 Store = DAG.getStore(Op.getOperand(0),
4965 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4967 MemOps.push_back(Store);
4969 // Store ptr to overflow_arg_area
4970 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4971 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4972 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4973 MemOps.push_back(Store);
4975 // Store ptr to reg_save_area.
4976 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4977 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4978 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4979 MemOps.push_back(Store);
4980 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4983 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4984 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4985 SDOperand Chain = Op.getOperand(0);
4986 SDOperand DstPtr = Op.getOperand(1);
4987 SDOperand SrcPtr = Op.getOperand(2);
4988 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4989 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4991 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr, SrcSV, 0);
4992 Chain = SrcPtr.getValue(1);
4993 for (unsigned i = 0; i < 3; ++i) {
4994 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr, SrcSV, 0);
4995 Chain = Val.getValue(1);
4996 Chain = DAG.getStore(Chain, Val, DstPtr, DstSV, 0);
4999 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
5000 DAG.getIntPtrConstant(8));
5001 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
5002 DAG.getIntPtrConstant(8));
5008 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5009 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5011 default: return SDOperand(); // Don't custom lower most intrinsics.
5012 // Comparison intrinsics.
5013 case Intrinsic::x86_sse_comieq_ss:
5014 case Intrinsic::x86_sse_comilt_ss:
5015 case Intrinsic::x86_sse_comile_ss:
5016 case Intrinsic::x86_sse_comigt_ss:
5017 case Intrinsic::x86_sse_comige_ss:
5018 case Intrinsic::x86_sse_comineq_ss:
5019 case Intrinsic::x86_sse_ucomieq_ss:
5020 case Intrinsic::x86_sse_ucomilt_ss:
5021 case Intrinsic::x86_sse_ucomile_ss:
5022 case Intrinsic::x86_sse_ucomigt_ss:
5023 case Intrinsic::x86_sse_ucomige_ss:
5024 case Intrinsic::x86_sse_ucomineq_ss:
5025 case Intrinsic::x86_sse2_comieq_sd:
5026 case Intrinsic::x86_sse2_comilt_sd:
5027 case Intrinsic::x86_sse2_comile_sd:
5028 case Intrinsic::x86_sse2_comigt_sd:
5029 case Intrinsic::x86_sse2_comige_sd:
5030 case Intrinsic::x86_sse2_comineq_sd:
5031 case Intrinsic::x86_sse2_ucomieq_sd:
5032 case Intrinsic::x86_sse2_ucomilt_sd:
5033 case Intrinsic::x86_sse2_ucomile_sd:
5034 case Intrinsic::x86_sse2_ucomigt_sd:
5035 case Intrinsic::x86_sse2_ucomige_sd:
5036 case Intrinsic::x86_sse2_ucomineq_sd: {
5038 ISD::CondCode CC = ISD::SETCC_INVALID;
5041 case Intrinsic::x86_sse_comieq_ss:
5042 case Intrinsic::x86_sse2_comieq_sd:
5046 case Intrinsic::x86_sse_comilt_ss:
5047 case Intrinsic::x86_sse2_comilt_sd:
5051 case Intrinsic::x86_sse_comile_ss:
5052 case Intrinsic::x86_sse2_comile_sd:
5056 case Intrinsic::x86_sse_comigt_ss:
5057 case Intrinsic::x86_sse2_comigt_sd:
5061 case Intrinsic::x86_sse_comige_ss:
5062 case Intrinsic::x86_sse2_comige_sd:
5066 case Intrinsic::x86_sse_comineq_ss:
5067 case Intrinsic::x86_sse2_comineq_sd:
5071 case Intrinsic::x86_sse_ucomieq_ss:
5072 case Intrinsic::x86_sse2_ucomieq_sd:
5073 Opc = X86ISD::UCOMI;
5076 case Intrinsic::x86_sse_ucomilt_ss:
5077 case Intrinsic::x86_sse2_ucomilt_sd:
5078 Opc = X86ISD::UCOMI;
5081 case Intrinsic::x86_sse_ucomile_ss:
5082 case Intrinsic::x86_sse2_ucomile_sd:
5083 Opc = X86ISD::UCOMI;
5086 case Intrinsic::x86_sse_ucomigt_ss:
5087 case Intrinsic::x86_sse2_ucomigt_sd:
5088 Opc = X86ISD::UCOMI;
5091 case Intrinsic::x86_sse_ucomige_ss:
5092 case Intrinsic::x86_sse2_ucomige_sd:
5093 Opc = X86ISD::UCOMI;
5096 case Intrinsic::x86_sse_ucomineq_ss:
5097 case Intrinsic::x86_sse2_ucomineq_sd:
5098 Opc = X86ISD::UCOMI;
5104 SDOperand LHS = Op.getOperand(1);
5105 SDOperand RHS = Op.getOperand(2);
5106 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5108 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5109 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5110 DAG.getConstant(X86CC, MVT::i8), Cond);
5111 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5116 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5117 // Depths > 0 not supported yet!
5118 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5121 // Just load the return address
5122 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5123 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5126 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5127 // Depths > 0 not supported yet!
5128 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5131 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5132 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5133 DAG.getIntPtrConstant(4));
5136 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5137 SelectionDAG &DAG) {
5138 // Is not yet supported on x86-64
5139 if (Subtarget->is64Bit())
5142 return DAG.getIntPtrConstant(8);
5145 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5147 assert(!Subtarget->is64Bit() &&
5148 "Lowering of eh_return builtin is not supported yet on x86-64");
5150 MachineFunction &MF = DAG.getMachineFunction();
5151 SDOperand Chain = Op.getOperand(0);
5152 SDOperand Offset = Op.getOperand(1);
5153 SDOperand Handler = Op.getOperand(2);
5155 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5158 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5159 DAG.getIntPtrConstant(-4UL));
5160 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5161 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5162 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5163 MF.getRegInfo().addLiveOut(X86::ECX);
5165 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5166 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5169 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5170 SelectionDAG &DAG) {
5171 SDOperand Root = Op.getOperand(0);
5172 SDOperand Trmp = Op.getOperand(1); // trampoline
5173 SDOperand FPtr = Op.getOperand(2); // nested function
5174 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5176 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5178 const X86InstrInfo *TII =
5179 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5181 if (Subtarget->is64Bit()) {
5182 SDOperand OutChains[6];
5184 // Large code-model.
5186 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5187 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5189 const unsigned char N86R10 =
5190 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5191 const unsigned char N86R11 =
5192 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5194 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5196 // Load the pointer to the nested function into R11.
5197 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5198 SDOperand Addr = Trmp;
5199 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5202 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5203 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5205 // Load the 'nest' parameter value into R10.
5206 // R10 is specified in X86CallingConv.td
5207 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5208 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5209 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5212 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5213 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5215 // Jump to the nested function.
5216 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5217 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5218 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5221 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5222 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5223 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5227 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5228 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5230 const Function *Func =
5231 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5232 unsigned CC = Func->getCallingConv();
5237 assert(0 && "Unsupported calling convention");
5238 case CallingConv::C:
5239 case CallingConv::X86_StdCall: {
5240 // Pass 'nest' parameter in ECX.
5241 // Must be kept in sync with X86CallingConv.td
5244 // Check that ECX wasn't needed by an 'inreg' parameter.
5245 const FunctionType *FTy = Func->getFunctionType();
5246 const ParamAttrsList *Attrs = Func->getParamAttrs();
5248 if (Attrs && !Func->isVarArg()) {
5249 unsigned InRegCount = 0;
5252 for (FunctionType::param_iterator I = FTy->param_begin(),
5253 E = FTy->param_end(); I != E; ++I, ++Idx)
5254 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5255 // FIXME: should only count parameters that are lowered to integers.
5256 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5258 if (InRegCount > 2) {
5259 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5265 case CallingConv::X86_FastCall:
5266 // Pass 'nest' parameter in EAX.
5267 // Must be kept in sync with X86CallingConv.td
5272 SDOperand OutChains[4];
5273 SDOperand Addr, Disp;
5275 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5276 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5278 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5279 const unsigned char N86Reg =
5280 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5281 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5284 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5285 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5287 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5288 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5289 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5290 TrmpAddr, 5, false, 1);
5292 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5293 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5296 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5297 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5301 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5303 The rounding mode is in bits 11:10 of FPSR, and has the following
5310 FLT_ROUNDS, on the other hand, expects the following:
5317 To perform the conversion, we do:
5318 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5321 MachineFunction &MF = DAG.getMachineFunction();
5322 const TargetMachine &TM = MF.getTarget();
5323 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5324 unsigned StackAlignment = TFI.getStackAlignment();
5325 MVT::ValueType VT = Op.getValueType();
5327 // Save FP Control Word to stack slot
5328 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5329 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5331 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5332 DAG.getEntryNode(), StackSlot);
5334 // Load FP Control Word from stack slot
5335 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5337 // Transform as necessary
5339 DAG.getNode(ISD::SRL, MVT::i16,
5340 DAG.getNode(ISD::AND, MVT::i16,
5341 CWD, DAG.getConstant(0x800, MVT::i16)),
5342 DAG.getConstant(11, MVT::i8));
5344 DAG.getNode(ISD::SRL, MVT::i16,
5345 DAG.getNode(ISD::AND, MVT::i16,
5346 CWD, DAG.getConstant(0x400, MVT::i16)),
5347 DAG.getConstant(9, MVT::i8));
5350 DAG.getNode(ISD::AND, MVT::i16,
5351 DAG.getNode(ISD::ADD, MVT::i16,
5352 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5353 DAG.getConstant(1, MVT::i16)),
5354 DAG.getConstant(3, MVT::i16));
5357 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5358 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5361 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5362 MVT::ValueType VT = Op.getValueType();
5363 MVT::ValueType OpVT = VT;
5364 unsigned NumBits = MVT::getSizeInBits(VT);
5366 Op = Op.getOperand(0);
5367 if (VT == MVT::i8) {
5368 // Zero extend to i32 since there is not an i8 bsr.
5370 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5373 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5374 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5375 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5377 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5378 SmallVector<SDOperand, 4> Ops;
5380 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5381 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5382 Ops.push_back(Op.getValue(1));
5383 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5385 // Finally xor with NumBits-1.
5386 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5389 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5393 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5394 MVT::ValueType VT = Op.getValueType();
5395 MVT::ValueType OpVT = VT;
5396 unsigned NumBits = MVT::getSizeInBits(VT);
5398 Op = Op.getOperand(0);
5399 if (VT == MVT::i8) {
5401 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5404 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5405 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5406 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5408 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5409 SmallVector<SDOperand, 4> Ops;
5411 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5412 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5413 Ops.push_back(Op.getValue(1));
5414 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5417 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5421 SDOperand X86TargetLowering::LowerLCS(SDOperand Op, SelectionDAG &DAG) {
5422 MVT::ValueType T = cast<AtomicSDNode>(Op.Val)->getVT();
5426 case MVT::i8: Reg = X86::AL; size = 1; break;
5427 case MVT::i16: Reg = X86::AX; size = 2; break;
5428 case MVT::i32: Reg = X86::EAX; size = 4; break;
5430 if (Subtarget->is64Bit()) {
5431 Reg = X86::RAX; size = 8;
5432 } else //Should go away when LowerType stuff lands
5433 return SDOperand(ExpandATOMIC_LCS(Op.Val, DAG), 0);
5436 SDOperand cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5437 Op.getOperand(3), SDOperand());
5438 SDOperand Ops[] = { cpIn.getValue(0),
5441 DAG.getTargetConstant(size, MVT::i8),
5443 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5444 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5446 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5450 SDNode* X86TargetLowering::ExpandATOMIC_LCS(SDNode* Op, SelectionDAG &DAG) {
5451 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5452 assert (T == MVT::i64 && "Only know how to expand i64 CAS");
5453 SDOperand cpInL, cpInH;
5454 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5455 DAG.getConstant(0, MVT::i32));
5456 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5457 DAG.getConstant(1, MVT::i32));
5458 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5459 cpInL, SDOperand());
5460 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5461 cpInH, cpInL.getValue(1));
5462 SDOperand swapInL, swapInH;
5463 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5464 DAG.getConstant(0, MVT::i32));
5465 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5466 DAG.getConstant(1, MVT::i32));
5467 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5468 swapInL, cpInH.getValue(1));
5469 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5470 swapInH, swapInL.getValue(1));
5471 SDOperand Ops[] = { swapInH.getValue(0),
5473 swapInH.getValue(1)};
5474 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5475 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5476 SDOperand cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5477 Result.getValue(1));
5478 SDOperand cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5479 cpOutL.getValue(2));
5480 SDOperand OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5481 SDOperand ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5482 Tys = DAG.getVTList(MVT::i64, MVT::Other);
5483 return DAG.getNode(ISD::MERGE_VALUES, Tys, ResultVal, cpOutH.getValue(1)).Val;
5486 /// LowerOperation - Provide custom lowering hooks for some operations.
5488 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5489 switch (Op.getOpcode()) {
5490 default: assert(0 && "Should not custom lower this!");
5491 case ISD::ATOMIC_LCS: return LowerLCS(Op,DAG);
5492 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5493 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5494 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5495 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5496 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5497 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5498 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5499 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5500 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5501 case ISD::SHL_PARTS:
5502 case ISD::SRA_PARTS:
5503 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5504 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5505 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5506 case ISD::FABS: return LowerFABS(Op, DAG);
5507 case ISD::FNEG: return LowerFNEG(Op, DAG);
5508 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5509 case ISD::SETCC: return LowerSETCC(Op, DAG);
5510 case ISD::SELECT: return LowerSELECT(Op, DAG);
5511 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5512 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5513 case ISD::CALL: return LowerCALL(Op, DAG);
5514 case ISD::RET: return LowerRET(Op, DAG);
5515 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5516 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5517 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
5518 case ISD::VASTART: return LowerVASTART(Op, DAG);
5519 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5520 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5521 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5522 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5523 case ISD::FRAME_TO_ARGS_OFFSET:
5524 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5525 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5526 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5527 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5528 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5529 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5530 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5532 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5533 case ISD::READCYCLECOUNTER:
5534 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5538 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5539 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5540 switch (N->getOpcode()) {
5541 default: assert(0 && "Should not custom lower this!");
5542 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5543 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5544 case ISD::ATOMIC_LCS: return ExpandATOMIC_LCS(N, DAG);
5548 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5550 default: return NULL;
5551 case X86ISD::BSF: return "X86ISD::BSF";
5552 case X86ISD::BSR: return "X86ISD::BSR";
5553 case X86ISD::SHLD: return "X86ISD::SHLD";
5554 case X86ISD::SHRD: return "X86ISD::SHRD";
5555 case X86ISD::FAND: return "X86ISD::FAND";
5556 case X86ISD::FOR: return "X86ISD::FOR";
5557 case X86ISD::FXOR: return "X86ISD::FXOR";
5558 case X86ISD::FSRL: return "X86ISD::FSRL";
5559 case X86ISD::FILD: return "X86ISD::FILD";
5560 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5561 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5562 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5563 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5564 case X86ISD::FLD: return "X86ISD::FLD";
5565 case X86ISD::FST: return "X86ISD::FST";
5566 case X86ISD::FP_GET_ST0: return "X86ISD::FP_GET_ST0";
5567 case X86ISD::FP_GET_ST0_ST1: return "X86ISD::FP_GET_ST0_ST1";
5568 case X86ISD::FP_SET_ST0: return "X86ISD::FP_SET_ST0";
5569 case X86ISD::CALL: return "X86ISD::CALL";
5570 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5571 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5572 case X86ISD::CMP: return "X86ISD::CMP";
5573 case X86ISD::COMI: return "X86ISD::COMI";
5574 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5575 case X86ISD::SETCC: return "X86ISD::SETCC";
5576 case X86ISD::CMOV: return "X86ISD::CMOV";
5577 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5578 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5579 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5580 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5581 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5582 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5583 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5584 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5585 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5586 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5587 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5588 case X86ISD::FMAX: return "X86ISD::FMAX";
5589 case X86ISD::FMIN: return "X86ISD::FMIN";
5590 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5591 case X86ISD::FRCP: return "X86ISD::FRCP";
5592 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5593 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5594 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5595 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5596 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5597 case X86ISD::LCMPXCHG_DAG: return "x86ISD::LCMPXCHG_DAG";
5598 case X86ISD::LCMPXCHG8_DAG: return "x86ISD::LCMPXCHG8_DAG";
5602 // isLegalAddressingMode - Return true if the addressing mode represented
5603 // by AM is legal for this target, for a load/store of the specified type.
5604 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5605 const Type *Ty) const {
5606 // X86 supports extremely general addressing modes.
5608 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5609 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5613 // We can only fold this if we don't need an extra load.
5614 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5617 // X86-64 only supports addr of globals in small code model.
5618 if (Subtarget->is64Bit()) {
5619 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5621 // If lower 4G is not available, then we must use rip-relative addressing.
5622 if (AM.BaseOffs || AM.Scale > 1)
5633 // These scales always work.
5638 // These scales are formed with basereg+scalereg. Only accept if there is
5643 default: // Other stuff never works.
5651 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5652 if (!Ty1->isInteger() || !Ty2->isInteger())
5654 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5655 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5656 if (NumBits1 <= NumBits2)
5658 return Subtarget->is64Bit() || NumBits1 < 64;
5661 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5662 MVT::ValueType VT2) const {
5663 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5665 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5666 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5667 if (NumBits1 <= NumBits2)
5669 return Subtarget->is64Bit() || NumBits1 < 64;
5672 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5673 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5674 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5675 /// are assumed to be legal.
5677 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5678 // Only do shuffles on 128-bit vector types for now.
5679 if (MVT::getSizeInBits(VT) == 64) return false;
5680 return (Mask.Val->getNumOperands() <= 4 ||
5681 isIdentityMask(Mask.Val) ||
5682 isIdentityMask(Mask.Val, true) ||
5683 isSplatMask(Mask.Val) ||
5684 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5685 X86::isUNPCKLMask(Mask.Val) ||
5686 X86::isUNPCKHMask(Mask.Val) ||
5687 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5688 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5691 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5693 SelectionDAG &DAG) const {
5694 unsigned NumElts = BVOps.size();
5695 // Only do shuffles on 128-bit vector types for now.
5696 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5697 if (NumElts == 2) return true;
5699 return (isMOVLMask(&BVOps[0], 4) ||
5700 isCommutedMOVL(&BVOps[0], 4, true) ||
5701 isSHUFPMask(&BVOps[0], 4) ||
5702 isCommutedSHUFP(&BVOps[0], 4));
5707 //===----------------------------------------------------------------------===//
5708 // X86 Scheduler Hooks
5709 //===----------------------------------------------------------------------===//
5712 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5713 MachineBasicBlock *BB) {
5714 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5715 switch (MI->getOpcode()) {
5716 default: assert(false && "Unexpected instr type to insert");
5717 case X86::CMOV_FR32:
5718 case X86::CMOV_FR64:
5719 case X86::CMOV_V4F32:
5720 case X86::CMOV_V2F64:
5721 case X86::CMOV_V2I64: {
5722 // To "insert" a SELECT_CC instruction, we actually have to insert the
5723 // diamond control-flow pattern. The incoming instruction knows the
5724 // destination vreg to set, the condition code register to branch on, the
5725 // true/false values to select between, and a branch opcode to use.
5726 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5727 ilist<MachineBasicBlock>::iterator It = BB;
5733 // cmpTY ccX, r1, r2
5735 // fallthrough --> copy0MBB
5736 MachineBasicBlock *thisMBB = BB;
5737 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5738 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5740 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5741 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5742 MachineFunction *F = BB->getParent();
5743 F->getBasicBlockList().insert(It, copy0MBB);
5744 F->getBasicBlockList().insert(It, sinkMBB);
5745 // Update machine-CFG edges by first adding all successors of the current
5746 // block to the new block which will contain the Phi node for the select.
5747 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5748 e = BB->succ_end(); i != e; ++i)
5749 sinkMBB->addSuccessor(*i);
5750 // Next, remove all successors of the current block, and add the true
5751 // and fallthrough blocks as its successors.
5752 while(!BB->succ_empty())
5753 BB->removeSuccessor(BB->succ_begin());
5754 BB->addSuccessor(copy0MBB);
5755 BB->addSuccessor(sinkMBB);
5758 // %FalseValue = ...
5759 // # fallthrough to sinkMBB
5762 // Update machine-CFG edges
5763 BB->addSuccessor(sinkMBB);
5766 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5769 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5770 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5771 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5773 delete MI; // The pseudo instruction is gone now.
5777 case X86::FP32_TO_INT16_IN_MEM:
5778 case X86::FP32_TO_INT32_IN_MEM:
5779 case X86::FP32_TO_INT64_IN_MEM:
5780 case X86::FP64_TO_INT16_IN_MEM:
5781 case X86::FP64_TO_INT32_IN_MEM:
5782 case X86::FP64_TO_INT64_IN_MEM:
5783 case X86::FP80_TO_INT16_IN_MEM:
5784 case X86::FP80_TO_INT32_IN_MEM:
5785 case X86::FP80_TO_INT64_IN_MEM: {
5786 // Change the floating point control register to use "round towards zero"
5787 // mode when truncating to an integer value.
5788 MachineFunction *F = BB->getParent();
5789 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5790 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5792 // Load the old value of the high byte of the control word...
5794 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5795 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5797 // Set the high part to be round to zero...
5798 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5801 // Reload the modified control word now...
5802 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5804 // Restore the memory image of control word to original value
5805 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5808 // Get the X86 opcode to use.
5810 switch (MI->getOpcode()) {
5811 default: assert(0 && "illegal opcode!");
5812 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5813 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5814 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5815 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5816 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5817 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5818 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5819 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5820 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5824 MachineOperand &Op = MI->getOperand(0);
5825 if (Op.isRegister()) {
5826 AM.BaseType = X86AddressMode::RegBase;
5827 AM.Base.Reg = Op.getReg();
5829 AM.BaseType = X86AddressMode::FrameIndexBase;
5830 AM.Base.FrameIndex = Op.getIndex();
5832 Op = MI->getOperand(1);
5833 if (Op.isImmediate())
5834 AM.Scale = Op.getImm();
5835 Op = MI->getOperand(2);
5836 if (Op.isImmediate())
5837 AM.IndexReg = Op.getImm();
5838 Op = MI->getOperand(3);
5839 if (Op.isGlobalAddress()) {
5840 AM.GV = Op.getGlobal();
5842 AM.Disp = Op.getImm();
5844 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5845 .addReg(MI->getOperand(4).getReg());
5847 // Reload the original control word now.
5848 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5850 delete MI; // The pseudo instruction is gone now.
5856 //===----------------------------------------------------------------------===//
5857 // X86 Optimization Hooks
5858 //===----------------------------------------------------------------------===//
5860 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5864 const SelectionDAG &DAG,
5865 unsigned Depth) const {
5866 unsigned Opc = Op.getOpcode();
5867 assert((Opc >= ISD::BUILTIN_OP_END ||
5868 Opc == ISD::INTRINSIC_WO_CHAIN ||
5869 Opc == ISD::INTRINSIC_W_CHAIN ||
5870 Opc == ISD::INTRINSIC_VOID) &&
5871 "Should use MaskedValueIsZero if you don't know whether Op"
5872 " is a target node!");
5874 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
5878 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
5879 Mask.getBitWidth() - 1);
5884 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5885 /// element of the result of the vector shuffle.
5886 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5887 MVT::ValueType VT = N->getValueType(0);
5888 SDOperand PermMask = N->getOperand(2);
5889 unsigned NumElems = PermMask.getNumOperands();
5890 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5892 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5894 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5895 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5896 SDOperand Idx = PermMask.getOperand(i);
5897 if (Idx.getOpcode() == ISD::UNDEF)
5898 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5899 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5904 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5905 /// node is a GlobalAddress + an offset.
5906 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5907 unsigned Opc = N->getOpcode();
5908 if (Opc == X86ISD::Wrapper) {
5909 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5910 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5913 } else if (Opc == ISD::ADD) {
5914 SDOperand N1 = N->getOperand(0);
5915 SDOperand N2 = N->getOperand(1);
5916 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5917 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5919 Offset += V->getSignExtended();
5922 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5923 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5925 Offset += V->getSignExtended();
5933 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5935 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5936 MachineFrameInfo *MFI) {
5937 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5940 SDOperand Loc = N->getOperand(1);
5941 SDOperand BaseLoc = Base->getOperand(1);
5942 if (Loc.getOpcode() == ISD::FrameIndex) {
5943 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5945 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5946 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5947 int FS = MFI->getObjectSize(FI);
5948 int BFS = MFI->getObjectSize(BFI);
5949 if (FS != BFS || FS != Size) return false;
5950 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5952 GlobalValue *GV1 = NULL;
5953 GlobalValue *GV2 = NULL;
5954 int64_t Offset1 = 0;
5955 int64_t Offset2 = 0;
5956 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5957 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5958 if (isGA1 && isGA2 && GV1 == GV2)
5959 return Offset1 == (Offset2 + Dist*Size);
5965 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5966 const X86Subtarget *Subtarget) {
5969 if (isGAPlusOffset(Base, GV, Offset))
5970 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5971 // DAG combine handles the stack object case.
5976 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5977 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5978 /// if the load addresses are consecutive, non-overlapping, and in the right
5980 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5981 const X86Subtarget *Subtarget) {
5982 MachineFunction &MF = DAG.getMachineFunction();
5983 MachineFrameInfo *MFI = MF.getFrameInfo();
5984 MVT::ValueType VT = N->getValueType(0);
5985 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5986 SDOperand PermMask = N->getOperand(2);
5987 int NumElems = (int)PermMask.getNumOperands();
5988 SDNode *Base = NULL;
5989 for (int i = 0; i < NumElems; ++i) {
5990 SDOperand Idx = PermMask.getOperand(i);
5991 if (Idx.getOpcode() == ISD::UNDEF) {
5992 if (!Base) return SDOperand();
5995 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5996 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
6000 else if (!isConsecutiveLoad(Arg.Val, Base,
6001 i, MVT::getSizeInBits(EVT)/8,MFI))
6006 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
6007 LoadSDNode *LD = cast<LoadSDNode>(Base);
6009 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6010 LD->getSrcValueOffset(), LD->isVolatile());
6012 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6013 LD->getSrcValueOffset(), LD->isVolatile(),
6014 LD->getAlignment());
6018 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6019 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6020 const X86Subtarget *Subtarget) {
6021 SDOperand Cond = N->getOperand(0);
6023 // If we have SSE[12] support, try to form min/max nodes.
6024 if (Subtarget->hasSSE2() &&
6025 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6026 if (Cond.getOpcode() == ISD::SETCC) {
6027 // Get the LHS/RHS of the select.
6028 SDOperand LHS = N->getOperand(1);
6029 SDOperand RHS = N->getOperand(2);
6030 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6032 unsigned Opcode = 0;
6033 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6036 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6039 if (!UnsafeFPMath) break;
6041 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6043 Opcode = X86ISD::FMIN;
6046 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6049 if (!UnsafeFPMath) break;
6051 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6053 Opcode = X86ISD::FMAX;
6056 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6059 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6062 if (!UnsafeFPMath) break;
6064 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6066 Opcode = X86ISD::FMIN;
6069 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6072 if (!UnsafeFPMath) break;
6074 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6076 Opcode = X86ISD::FMAX;
6082 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6090 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6091 static SDOperand PerformSTORECombine(StoreSDNode *St, SelectionDAG &DAG,
6092 const X86Subtarget *Subtarget) {
6093 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
6094 // the FP state in cases where an emms may be missing.
6095 // A preferable solution to the general problem is to figure out the right
6096 // places to insert EMMS. This qualifies as a quick hack.
6097 if (MVT::isVector(St->getValue().getValueType()) &&
6098 MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
6099 isa<LoadSDNode>(St->getValue()) &&
6100 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6101 St->getChain().hasOneUse() && !St->isVolatile()) {
6102 SDNode* LdVal = St->getValue().Val;
6104 int TokenFactorIndex = -1;
6105 SmallVector<SDOperand, 8> Ops;
6106 SDNode* ChainVal = St->getChain().Val;
6107 // Must be a store of a load. We currently handle two cases: the load
6108 // is a direct child, and it's under an intervening TokenFactor. It is
6109 // possible to dig deeper under nested TokenFactors.
6110 if (ChainVal == LdVal)
6111 Ld = cast<LoadSDNode>(St->getChain());
6112 else if (St->getValue().hasOneUse() &&
6113 ChainVal->getOpcode() == ISD::TokenFactor) {
6114 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6115 if (ChainVal->getOperand(i).Val == LdVal) {
6116 TokenFactorIndex = i;
6117 Ld = cast<LoadSDNode>(St->getValue());
6119 Ops.push_back(ChainVal->getOperand(i));
6123 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6124 if (Subtarget->is64Bit()) {
6125 SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6126 Ld->getBasePtr(), Ld->getSrcValue(),
6127 Ld->getSrcValueOffset(), Ld->isVolatile(),
6128 Ld->getAlignment());
6129 SDOperand NewChain = NewLd.getValue(1);
6130 if (TokenFactorIndex != -1) {
6131 Ops.push_back(NewLd);
6132 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6135 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6136 St->getSrcValue(), St->getSrcValueOffset(),
6137 St->isVolatile(), St->getAlignment());
6140 // Otherwise, lower to two 32-bit copies.
6141 SDOperand LoAddr = Ld->getBasePtr();
6142 SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6143 DAG.getConstant(MVT::i32, 4));
6145 SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6146 Ld->getSrcValue(), Ld->getSrcValueOffset(),
6147 Ld->isVolatile(), Ld->getAlignment());
6148 SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6149 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6151 MinAlign(Ld->getAlignment(), 4));
6153 SDOperand NewChain = LoLd.getValue(1);
6154 if (TokenFactorIndex != -1) {
6155 Ops.push_back(LoLd);
6156 Ops.push_back(HiLd);
6157 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6161 LoAddr = St->getBasePtr();
6162 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6163 DAG.getConstant(MVT::i32, 4));
6165 SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6166 St->getSrcValue(), St->getSrcValueOffset(),
6167 St->isVolatile(), St->getAlignment());
6168 SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6169 St->getSrcValue(), St->getSrcValueOffset()+4,
6171 MinAlign(St->getAlignment(), 4));
6172 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6178 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6179 /// X86ISD::FXOR nodes.
6180 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6181 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6182 // F[X]OR(0.0, x) -> x
6183 // F[X]OR(x, 0.0) -> x
6184 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6185 if (C->getValueAPF().isPosZero())
6186 return N->getOperand(1);
6187 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6188 if (C->getValueAPF().isPosZero())
6189 return N->getOperand(0);
6193 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6194 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6195 // FAND(0.0, x) -> 0.0
6196 // FAND(x, 0.0) -> 0.0
6197 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6198 if (C->getValueAPF().isPosZero())
6199 return N->getOperand(0);
6200 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6201 if (C->getValueAPF().isPosZero())
6202 return N->getOperand(1);
6207 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6208 DAGCombinerInfo &DCI) const {
6209 SelectionDAG &DAG = DCI.DAG;
6210 switch (N->getOpcode()) {
6212 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
6213 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6215 return PerformSTORECombine(cast<StoreSDNode>(N), DAG, Subtarget);
6217 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6218 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6224 //===----------------------------------------------------------------------===//
6225 // X86 Inline Assembly Support
6226 //===----------------------------------------------------------------------===//
6228 /// getConstraintType - Given a constraint letter, return the type of
6229 /// constraint it is for this target.
6230 X86TargetLowering::ConstraintType
6231 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6232 if (Constraint.size() == 1) {
6233 switch (Constraint[0]) {
6242 return C_RegisterClass;
6247 return TargetLowering::getConstraintType(Constraint);
6250 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6251 /// with another that has more specific requirements based on the type of the
6252 /// corresponding operand.
6253 void X86TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT,
6254 std::string& s) const {
6255 if (MVT::isFloatingPoint(ConstraintVT)) {
6256 if (Subtarget->hasSSE2())
6258 else if (Subtarget->hasSSE1())
6263 return TargetLowering::lowerXConstraint(ConstraintVT, s);
6266 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6267 /// vector. If it is invalid, don't add anything to Ops.
6268 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6270 std::vector<SDOperand>&Ops,
6271 SelectionDAG &DAG) {
6272 SDOperand Result(0, 0);
6274 switch (Constraint) {
6277 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6278 if (C->getValue() <= 31) {
6279 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6285 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6286 if (C->getValue() <= 255) {
6287 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6293 // Literal immediates are always ok.
6294 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6295 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6299 // If we are in non-pic codegen mode, we allow the address of a global (with
6300 // an optional displacement) to be used with 'i'.
6301 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6304 // Match either (GA) or (GA+C)
6306 Offset = GA->getOffset();
6307 } else if (Op.getOpcode() == ISD::ADD) {
6308 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6309 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6311 Offset = GA->getOffset()+C->getValue();
6313 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6314 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6316 Offset = GA->getOffset()+C->getValue();
6323 // If addressing this global requires a load (e.g. in PIC mode), we can't
6325 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6329 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6335 // Otherwise, not valid for this mode.
6341 Ops.push_back(Result);
6344 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6347 std::vector<unsigned> X86TargetLowering::
6348 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6349 MVT::ValueType VT) const {
6350 if (Constraint.size() == 1) {
6351 // FIXME: not handling fp-stack yet!
6352 switch (Constraint[0]) { // GCC X86 Constraint Letters
6353 default: break; // Unknown constraint letter
6354 case 'A': // EAX/EDX
6355 if (VT == MVT::i32 || VT == MVT::i64)
6356 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6358 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6361 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6362 else if (VT == MVT::i16)
6363 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6364 else if (VT == MVT::i8)
6365 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6366 else if (VT == MVT::i64)
6367 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6372 return std::vector<unsigned>();
6375 std::pair<unsigned, const TargetRegisterClass*>
6376 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6377 MVT::ValueType VT) const {
6378 // First, see if this is a constraint that directly corresponds to an LLVM
6380 if (Constraint.size() == 1) {
6381 // GCC Constraint Letters
6382 switch (Constraint[0]) {
6384 case 'r': // GENERAL_REGS
6385 case 'R': // LEGACY_REGS
6386 case 'l': // INDEX_REGS
6387 if (VT == MVT::i64 && Subtarget->is64Bit())
6388 return std::make_pair(0U, X86::GR64RegisterClass);
6390 return std::make_pair(0U, X86::GR32RegisterClass);
6391 else if (VT == MVT::i16)
6392 return std::make_pair(0U, X86::GR16RegisterClass);
6393 else if (VT == MVT::i8)
6394 return std::make_pair(0U, X86::GR8RegisterClass);
6396 case 'y': // MMX_REGS if MMX allowed.
6397 if (!Subtarget->hasMMX()) break;
6398 return std::make_pair(0U, X86::VR64RegisterClass);
6400 case 'Y': // SSE_REGS if SSE2 allowed
6401 if (!Subtarget->hasSSE2()) break;
6403 case 'x': // SSE_REGS if SSE1 allowed
6404 if (!Subtarget->hasSSE1()) break;
6408 // Scalar SSE types.
6411 return std::make_pair(0U, X86::FR32RegisterClass);
6414 return std::make_pair(0U, X86::FR64RegisterClass);
6422 return std::make_pair(0U, X86::VR128RegisterClass);
6428 // Use the default implementation in TargetLowering to convert the register
6429 // constraint into a member of a register class.
6430 std::pair<unsigned, const TargetRegisterClass*> Res;
6431 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6433 // Not found as a standard register?
6434 if (Res.second == 0) {
6435 // GCC calls "st(0)" just plain "st".
6436 if (StringsEqualNoCase("{st}", Constraint)) {
6437 Res.first = X86::ST0;
6438 Res.second = X86::RFP80RegisterClass;
6444 // Otherwise, check to see if this is a register class of the wrong value
6445 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6446 // turn into {ax},{dx}.
6447 if (Res.second->hasType(VT))
6448 return Res; // Correct type already, nothing to do.
6450 // All of the single-register GCC register classes map their values onto
6451 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6452 // really want an 8-bit or 32-bit register, map to the appropriate register
6453 // class and return the appropriate register.
6454 if (Res.second != X86::GR16RegisterClass)
6457 if (VT == MVT::i8) {
6458 unsigned DestReg = 0;
6459 switch (Res.first) {
6461 case X86::AX: DestReg = X86::AL; break;
6462 case X86::DX: DestReg = X86::DL; break;
6463 case X86::CX: DestReg = X86::CL; break;
6464 case X86::BX: DestReg = X86::BL; break;
6467 Res.first = DestReg;
6468 Res.second = Res.second = X86::GR8RegisterClass;
6470 } else if (VT == MVT::i32) {
6471 unsigned DestReg = 0;
6472 switch (Res.first) {
6474 case X86::AX: DestReg = X86::EAX; break;
6475 case X86::DX: DestReg = X86::EDX; break;
6476 case X86::CX: DestReg = X86::ECX; break;
6477 case X86::BX: DestReg = X86::EBX; break;
6478 case X86::SI: DestReg = X86::ESI; break;
6479 case X86::DI: DestReg = X86::EDI; break;
6480 case X86::BP: DestReg = X86::EBP; break;
6481 case X86::SP: DestReg = X86::ESP; break;
6484 Res.first = DestReg;
6485 Res.second = Res.second = X86::GR32RegisterClass;
6487 } else if (VT == MVT::i64) {
6488 unsigned DestReg = 0;
6489 switch (Res.first) {
6491 case X86::AX: DestReg = X86::RAX; break;
6492 case X86::DX: DestReg = X86::RDX; break;
6493 case X86::CX: DestReg = X86::RCX; break;
6494 case X86::BX: DestReg = X86::RBX; break;
6495 case X86::SI: DestReg = X86::RSI; break;
6496 case X86::DI: DestReg = X86::RDI; break;
6497 case X86::BP: DestReg = X86::RBP; break;
6498 case X86::SP: DestReg = X86::RSP; break;
6501 Res.first = DestReg;
6502 Res.second = Res.second = X86::GR64RegisterClass;