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/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
43 // Forward declarations.
44 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
46 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
47 : TargetLowering(TM) {
48 Subtarget = &TM.getSubtarget<X86Subtarget>();
49 X86ScalarSSEf64 = Subtarget->hasSSE2();
50 X86ScalarSSEf32 = Subtarget->hasSSE1();
51 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
55 RegInfo = TM.getRegisterInfo();
57 // Set up the TargetLowering object.
59 // X86 is weird, it always uses i8 for shift amounts and setcc results.
60 setShiftAmountType(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 if (Subtarget->is64Bit())
212 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
216 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
217 setOperationAction(ISD::FREM , MVT::f32 , Expand);
218 setOperationAction(ISD::FREM , MVT::f64 , Expand);
219 setOperationAction(ISD::FREM , MVT::f80 , Expand);
220 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
222 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
223 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
224 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
225 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
226 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
227 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
228 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
229 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
230 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
231 if (Subtarget->is64Bit()) {
232 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
233 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
234 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
237 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
238 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
240 // These should be promoted to a larger select which is supported.
241 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
242 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
243 // X86 wants to expand cmov itself.
244 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
245 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
246 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
247 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
248 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
249 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
250 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
251 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
252 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
253 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
254 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
255 if (Subtarget->is64Bit()) {
256 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
257 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
259 // X86 ret instruction may pop stack.
260 setOperationAction(ISD::RET , MVT::Other, Custom);
261 if (!Subtarget->is64Bit())
262 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
265 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
266 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
267 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
268 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
269 if (Subtarget->is64Bit())
270 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
271 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
272 if (Subtarget->is64Bit()) {
273 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
274 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
275 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
276 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
278 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
279 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
280 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
281 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
282 if (Subtarget->is64Bit()) {
283 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
284 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
285 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
288 if (Subtarget->hasSSE1())
289 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
291 if (!Subtarget->hasSSE2())
292 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
294 // Expand certain atomics
295 setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i8, Custom);
296 setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i16, Custom);
297 setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i32, Custom);
298 setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i64, Custom);
299 setOperationAction(ISD::ATOMIC_LOAD_SUB , MVT::i8, Expand);
300 setOperationAction(ISD::ATOMIC_LOAD_SUB , MVT::i16, Expand);
301 setOperationAction(ISD::ATOMIC_LOAD_SUB , MVT::i32, Expand);
303 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
304 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
305 // FIXME - use subtarget debug flags
306 if (!Subtarget->isTargetDarwin() &&
307 !Subtarget->isTargetELF() &&
308 !Subtarget->isTargetCygMing()) {
309 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
310 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
313 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
314 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
315 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
316 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
317 if (Subtarget->is64Bit()) {
319 setExceptionPointerRegister(X86::RAX);
320 setExceptionSelectorRegister(X86::RDX);
322 setExceptionPointerRegister(X86::EAX);
323 setExceptionSelectorRegister(X86::EDX);
325 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
327 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
329 setOperationAction(ISD::TRAP, MVT::Other, Legal);
331 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
332 setOperationAction(ISD::VASTART , MVT::Other, Custom);
333 setOperationAction(ISD::VAEND , MVT::Other, Expand);
334 if (Subtarget->is64Bit()) {
335 setOperationAction(ISD::VAARG , MVT::Other, Custom);
336 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
338 setOperationAction(ISD::VAARG , MVT::Other, Expand);
339 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
342 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
343 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
344 if (Subtarget->is64Bit())
345 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
346 if (Subtarget->isTargetCygMing())
347 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
349 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
351 if (X86ScalarSSEf64) {
352 // f32 and f64 use SSE.
353 // Set up the FP register classes.
354 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
355 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
357 // Use ANDPD to simulate FABS.
358 setOperationAction(ISD::FABS , MVT::f64, Custom);
359 setOperationAction(ISD::FABS , MVT::f32, Custom);
361 // Use XORP to simulate FNEG.
362 setOperationAction(ISD::FNEG , MVT::f64, Custom);
363 setOperationAction(ISD::FNEG , MVT::f32, Custom);
365 // Use ANDPD and ORPD to simulate FCOPYSIGN.
366 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
367 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
369 // We don't support sin/cos/fmod
370 setOperationAction(ISD::FSIN , MVT::f64, Expand);
371 setOperationAction(ISD::FCOS , MVT::f64, Expand);
372 setOperationAction(ISD::FSIN , MVT::f32, Expand);
373 setOperationAction(ISD::FCOS , MVT::f32, Expand);
375 // Expand FP immediates into loads from the stack, except for the special
377 addLegalFPImmediate(APFloat(+0.0)); // xorpd
378 addLegalFPImmediate(APFloat(+0.0f)); // xorps
380 // Floating truncations from f80 and extensions to f80 go through memory.
381 // If optimizing, we lie about this though and handle it in
382 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
384 setConvertAction(MVT::f32, MVT::f80, Expand);
385 setConvertAction(MVT::f64, MVT::f80, Expand);
386 setConvertAction(MVT::f80, MVT::f32, Expand);
387 setConvertAction(MVT::f80, MVT::f64, Expand);
389 } else if (X86ScalarSSEf32) {
390 // Use SSE for f32, x87 for f64.
391 // Set up the FP register classes.
392 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
393 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
395 // Use ANDPS to simulate FABS.
396 setOperationAction(ISD::FABS , MVT::f32, Custom);
398 // Use XORP to simulate FNEG.
399 setOperationAction(ISD::FNEG , MVT::f32, Custom);
401 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
403 // Use ANDPS and ORPS to simulate FCOPYSIGN.
404 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
405 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
407 // We don't support sin/cos/fmod
408 setOperationAction(ISD::FSIN , MVT::f32, Expand);
409 setOperationAction(ISD::FCOS , MVT::f32, Expand);
411 // Special cases we handle for FP constants.
412 addLegalFPImmediate(APFloat(+0.0f)); // xorps
413 addLegalFPImmediate(APFloat(+0.0)); // FLD0
414 addLegalFPImmediate(APFloat(+1.0)); // FLD1
415 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
416 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
418 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
419 // this though and handle it in InstructionSelectPreprocess so that
420 // dagcombine2 can hack on these.
422 setConvertAction(MVT::f32, MVT::f64, Expand);
423 setConvertAction(MVT::f32, MVT::f80, Expand);
424 setConvertAction(MVT::f80, MVT::f32, Expand);
425 setConvertAction(MVT::f64, MVT::f32, Expand);
426 // And x87->x87 truncations also.
427 setConvertAction(MVT::f80, MVT::f64, Expand);
431 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
432 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
435 // f32 and f64 in x87.
436 // Set up the FP register classes.
437 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
438 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
440 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
441 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
442 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
443 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
445 // Floating truncations go through memory. If optimizing, we lie about
446 // this though and handle it in InstructionSelectPreprocess so that
447 // dagcombine2 can hack on these.
449 setConvertAction(MVT::f80, MVT::f32, Expand);
450 setConvertAction(MVT::f64, MVT::f32, Expand);
451 setConvertAction(MVT::f80, MVT::f64, Expand);
455 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
456 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
458 addLegalFPImmediate(APFloat(+0.0)); // FLD0
459 addLegalFPImmediate(APFloat(+1.0)); // FLD1
460 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
461 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
462 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
463 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
464 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
465 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
468 // Long double always uses X87.
469 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
470 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
471 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
473 APFloat TmpFlt(+0.0);
474 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
475 addLegalFPImmediate(TmpFlt); // FLD0
477 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
478 APFloat TmpFlt2(+1.0);
479 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
480 addLegalFPImmediate(TmpFlt2); // FLD1
481 TmpFlt2.changeSign();
482 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
486 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
487 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
490 // Always use a library call for pow.
491 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
492 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
493 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
495 // First set operation action for all vector types to expand. Then we
496 // will selectively turn on ones that can be effectively codegen'd.
497 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
498 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
499 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
500 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
501 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
502 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
503 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
504 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
505 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
506 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
507 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
508 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
509 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
510 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
511 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
512 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
513 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::SimpleValueType)VT, Expand);
514 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::SimpleValueType)VT, Expand);
515 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
516 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
517 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
518 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
519 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
520 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
521 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
522 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
523 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
524 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
525 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
526 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
527 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
528 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
529 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
530 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
531 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
532 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
533 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
534 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
535 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
536 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
539 if (Subtarget->hasMMX()) {
540 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
541 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
542 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
543 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
544 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
546 // FIXME: add MMX packed arithmetics
548 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
549 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
550 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
551 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
553 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
554 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
555 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
556 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
558 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
559 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
561 setOperationAction(ISD::AND, MVT::v8i8, Promote);
562 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
563 setOperationAction(ISD::AND, MVT::v4i16, Promote);
564 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
565 setOperationAction(ISD::AND, MVT::v2i32, Promote);
566 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
567 setOperationAction(ISD::AND, MVT::v1i64, Legal);
569 setOperationAction(ISD::OR, MVT::v8i8, Promote);
570 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
571 setOperationAction(ISD::OR, MVT::v4i16, Promote);
572 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
573 setOperationAction(ISD::OR, MVT::v2i32, Promote);
574 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
575 setOperationAction(ISD::OR, MVT::v1i64, Legal);
577 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
578 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
579 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
580 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
581 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
582 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
583 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
585 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
586 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
587 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
588 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
589 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
590 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
591 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
592 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
593 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
595 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
596 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
597 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
598 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
599 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
601 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
602 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
603 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
604 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
606 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
607 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
608 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
609 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
611 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
614 if (Subtarget->hasSSE1()) {
615 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
617 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
618 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
619 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
620 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
621 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
622 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
623 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
624 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
625 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
626 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
627 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
628 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
631 if (Subtarget->hasSSE2()) {
632 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
633 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
634 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
635 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
636 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
638 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
639 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
640 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
641 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
642 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
643 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
644 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
645 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
646 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
647 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
648 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
649 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
650 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
651 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
652 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
654 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
655 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
656 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
657 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
659 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
660 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
661 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
662 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
663 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
665 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
666 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
667 MVT VT = (MVT::SimpleValueType)i;
668 // Do not attempt to custom lower non-power-of-2 vectors
669 if (!isPowerOf2_32(VT.getVectorNumElements()))
671 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
672 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
673 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
675 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
676 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
677 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
678 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
679 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
680 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
681 if (Subtarget->is64Bit()) {
682 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
683 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
686 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
687 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
688 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
689 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
690 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
691 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
692 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
693 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
694 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
695 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
696 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
697 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
700 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
702 // Custom lower v2i64 and v2f64 selects.
703 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
704 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
705 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
706 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
710 if (Subtarget->hasSSE41()) {
711 // FIXME: Do we need to handle scalar-to-vector here?
712 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
713 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
715 // i8 and i16 vectors are custom , because the source register and source
716 // source memory operand types are not the same width. f32 vectors are
717 // custom since the immediate controlling the insert encodes additional
719 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
720 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
721 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
722 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
724 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
725 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
726 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
727 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
729 if (Subtarget->is64Bit()) {
730 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
731 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
735 if (Subtarget->hasSSE42()) {
736 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
739 // We want to custom lower some of our intrinsics.
740 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
742 // We have target-specific dag combine patterns for the following nodes:
743 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
744 setTargetDAGCombine(ISD::BUILD_VECTOR);
745 setTargetDAGCombine(ISD::SELECT);
746 setTargetDAGCombine(ISD::STORE);
748 computeRegisterProperties();
750 // FIXME: These should be based on subtarget info. Plus, the values should
751 // be smaller when we are in optimizing for size mode.
752 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
753 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
754 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
755 allowUnalignedMemoryAccesses = true; // x86 supports it!
756 setPrefLoopAlignment(16);
760 MVT X86TargetLowering::getSetCCResultType(const SDValue &) const {
765 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
766 /// the desired ByVal argument alignment.
767 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
770 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
771 if (VTy->getBitWidth() == 128)
773 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
774 unsigned EltAlign = 0;
775 getMaxByValAlign(ATy->getElementType(), EltAlign);
776 if (EltAlign > MaxAlign)
778 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
779 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
780 unsigned EltAlign = 0;
781 getMaxByValAlign(STy->getElementType(i), EltAlign);
782 if (EltAlign > MaxAlign)
791 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
792 /// function arguments in the caller parameter area. For X86, aggregates
793 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
794 /// are at 4-byte boundaries.
795 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
796 if (Subtarget->is64Bit())
797 return getTargetData()->getABITypeAlignment(Ty);
799 if (Subtarget->hasSSE1())
800 getMaxByValAlign(Ty, Align);
804 /// getOptimalMemOpType - Returns the target specific optimal type for load
805 /// and store operations as a result of memset, memcpy, and memmove
806 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
809 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
810 bool isSrcConst, bool isSrcStr) const {
811 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
813 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
815 if (Subtarget->is64Bit() && Size >= 8)
821 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
823 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
824 SelectionDAG &DAG) const {
825 if (usesGlobalOffsetTable())
826 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
827 if (!Subtarget->isPICStyleRIPRel())
828 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
832 //===----------------------------------------------------------------------===//
833 // Return Value Calling Convention Implementation
834 //===----------------------------------------------------------------------===//
836 #include "X86GenCallingConv.inc"
838 /// LowerRET - Lower an ISD::RET node.
839 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
840 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
842 SmallVector<CCValAssign, 16> RVLocs;
843 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
844 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
845 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
846 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
848 // If this is the first return lowered for this function, add the regs to the
849 // liveout set for the function.
850 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
851 for (unsigned i = 0; i != RVLocs.size(); ++i)
852 if (RVLocs[i].isRegLoc())
853 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
855 SDValue Chain = Op.getOperand(0);
857 // Handle tail call return.
858 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
859 if (Chain.getOpcode() == X86ISD::TAILCALL) {
860 SDValue TailCall = Chain;
861 SDValue TargetAddress = TailCall.getOperand(1);
862 SDValue StackAdjustment = TailCall.getOperand(2);
863 assert(((TargetAddress.getOpcode() == ISD::Register &&
864 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
865 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
866 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
867 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
868 "Expecting an global address, external symbol, or register");
869 assert(StackAdjustment.getOpcode() == ISD::Constant &&
870 "Expecting a const value");
872 SmallVector<SDValue,8> Operands;
873 Operands.push_back(Chain.getOperand(0));
874 Operands.push_back(TargetAddress);
875 Operands.push_back(StackAdjustment);
876 // Copy registers used by the call. Last operand is a flag so it is not
878 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
879 Operands.push_back(Chain.getOperand(i));
881 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
888 SmallVector<SDValue, 6> RetOps;
889 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
890 // Operand #1 = Bytes To Pop
891 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
893 // Copy the result values into the output registers.
894 for (unsigned i = 0; i != RVLocs.size(); ++i) {
895 CCValAssign &VA = RVLocs[i];
896 assert(VA.isRegLoc() && "Can only return in registers!");
897 SDValue ValToCopy = Op.getOperand(i*2+1);
899 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
900 // the RET instruction and handled by the FP Stackifier.
901 if (RVLocs[i].getLocReg() == X86::ST0 ||
902 RVLocs[i].getLocReg() == X86::ST1) {
903 // If this is a copy from an xmm register to ST(0), use an FPExtend to
904 // change the value to the FP stack register class.
905 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
906 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
907 RetOps.push_back(ValToCopy);
908 // Don't emit a copytoreg.
912 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
913 Flag = Chain.getValue(1);
916 // The x86-64 ABI for returning structs by value requires that we copy
917 // the sret argument into %rax for the return. We saved the argument into
918 // a virtual register in the entry block, so now we copy the value out
920 if (Subtarget->is64Bit() &&
921 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
922 MachineFunction &MF = DAG.getMachineFunction();
923 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
924 unsigned Reg = FuncInfo->getSRetReturnReg();
926 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
927 FuncInfo->setSRetReturnReg(Reg);
929 SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
931 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
932 Flag = Chain.getValue(1);
935 RetOps[0] = Chain; // Update chain.
937 // Add the flag if we have it.
939 RetOps.push_back(Flag);
941 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
945 /// LowerCallResult - Lower the result values of an ISD::CALL into the
946 /// appropriate copies out of appropriate physical registers. This assumes that
947 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
948 /// being lowered. The returns a SDNode with the same number of values as the
950 SDNode *X86TargetLowering::
951 LowerCallResult(SDValue Chain, SDValue InFlag, SDNode *TheCall,
952 unsigned CallingConv, SelectionDAG &DAG) {
954 // Assign locations to each value returned by this call.
955 SmallVector<CCValAssign, 16> RVLocs;
956 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
957 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
958 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
960 SmallVector<SDValue, 8> ResultVals;
962 // Copy all of the result registers out of their specified physreg.
963 for (unsigned i = 0; i != RVLocs.size(); ++i) {
964 MVT CopyVT = RVLocs[i].getValVT();
966 // If this is a call to a function that returns an fp value on the floating
967 // point stack, but where we prefer to use the value in xmm registers, copy
968 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
969 if (RVLocs[i].getLocReg() == X86::ST0 &&
970 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
974 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
975 CopyVT, InFlag).getValue(1);
976 SDValue Val = Chain.getValue(0);
977 InFlag = Chain.getValue(2);
979 if (CopyVT != RVLocs[i].getValVT()) {
980 // Round the F80 the right size, which also moves to the appropriate xmm
982 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
983 // This truncation won't change the value.
984 DAG.getIntPtrConstant(1));
987 ResultVals.push_back(Val);
990 // Merge everything together with a MERGE_VALUES node.
991 ResultVals.push_back(Chain);
992 return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
993 ResultVals.size()).Val;
997 //===----------------------------------------------------------------------===//
998 // C & StdCall & Fast Calling Convention implementation
999 //===----------------------------------------------------------------------===//
1000 // StdCall calling convention seems to be standard for many Windows' API
1001 // routines and around. It differs from C calling convention just a little:
1002 // callee should clean up the stack, not caller. Symbols should be also
1003 // decorated in some fancy way :) It doesn't support any vector arguments.
1004 // For info on fast calling convention see Fast Calling Convention (tail call)
1005 // implementation LowerX86_32FastCCCallTo.
1007 /// AddLiveIn - This helper function adds the specified physical register to the
1008 /// MachineFunction as a live in value. It also creates a corresponding virtual
1009 /// register for it.
1010 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1011 const TargetRegisterClass *RC) {
1012 assert(RC->contains(PReg) && "Not the correct regclass!");
1013 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1014 MF.getRegInfo().addLiveIn(PReg, VReg);
1018 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1020 static bool CallIsStructReturn(SDValue Op) {
1021 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1025 return cast<ARG_FLAGSSDNode>(Op.getOperand(6))->getArgFlags().isSRet();
1028 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1029 /// return semantics.
1030 static bool ArgsAreStructReturn(SDValue Op) {
1031 unsigned NumArgs = Op.Val->getNumValues() - 1;
1035 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1038 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1039 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1041 bool X86TargetLowering::IsCalleePop(SDValue Op) {
1042 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1046 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1049 case CallingConv::X86_StdCall:
1050 return !Subtarget->is64Bit();
1051 case CallingConv::X86_FastCall:
1052 return !Subtarget->is64Bit();
1053 case CallingConv::Fast:
1054 return PerformTailCallOpt;
1058 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1059 /// FORMAL_ARGUMENTS node.
1060 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDValue Op) const {
1061 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1063 if (Subtarget->is64Bit()) {
1064 if (Subtarget->isTargetWin64())
1065 return CC_X86_Win64_C;
1067 if (CC == CallingConv::Fast && PerformTailCallOpt)
1068 return CC_X86_64_TailCall;
1074 if (CC == CallingConv::X86_FastCall)
1075 return CC_X86_32_FastCall;
1076 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1077 return CC_X86_32_TailCall;
1082 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1083 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1085 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1086 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1087 if (CC == CallingConv::X86_FastCall)
1089 else if (CC == CallingConv::X86_StdCall)
1095 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1096 /// in a register before calling.
1097 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1098 return !IsTailCall && !Is64Bit &&
1099 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1100 Subtarget->isPICStyleGOT();
1103 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1104 /// address to be loaded in a register.
1106 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1107 return !Is64Bit && IsTailCall &&
1108 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1109 Subtarget->isPICStyleGOT();
1112 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1113 /// by "Src" to address "Dst" with size and alignment information specified by
1114 /// the specific parameter attribute. The copy will be passed as a byval
1115 /// function parameter.
1117 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1118 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1119 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1120 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1121 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1124 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1125 const CCValAssign &VA,
1126 MachineFrameInfo *MFI,
1128 SDValue Root, unsigned i) {
1129 // Create the nodes corresponding to a load from this parameter slot.
1130 ISD::ArgFlagsTy Flags =
1131 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1132 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1133 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1135 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1136 // changed with more analysis.
1137 // In case of tail call optimization mark all arguments mutable. Since they
1138 // could be overwritten by lowering of arguments in case of a tail call.
1139 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1140 VA.getLocMemOffset(), isImmutable);
1141 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1142 if (Flags.isByVal())
1144 return DAG.getLoad(VA.getValVT(), Root, FIN,
1145 PseudoSourceValue::getFixedStack(FI), 0);
1149 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1150 MachineFunction &MF = DAG.getMachineFunction();
1151 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1153 const Function* Fn = MF.getFunction();
1154 if (Fn->hasExternalLinkage() &&
1155 Subtarget->isTargetCygMing() &&
1156 Fn->getName() == "main")
1157 FuncInfo->setForceFramePointer(true);
1159 // Decorate the function name.
1160 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1162 MachineFrameInfo *MFI = MF.getFrameInfo();
1163 SDValue Root = Op.getOperand(0);
1164 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1165 unsigned CC = MF.getFunction()->getCallingConv();
1166 bool Is64Bit = Subtarget->is64Bit();
1167 bool IsWin64 = Subtarget->isTargetWin64();
1169 assert(!(isVarArg && CC == CallingConv::Fast) &&
1170 "Var args not supported with calling convention fastcc");
1172 // Assign locations to all of the incoming arguments.
1173 SmallVector<CCValAssign, 16> ArgLocs;
1174 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1175 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1177 SmallVector<SDValue, 8> ArgValues;
1178 unsigned LastVal = ~0U;
1179 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1180 CCValAssign &VA = ArgLocs[i];
1181 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1183 assert(VA.getValNo() != LastVal &&
1184 "Don't support value assigned to multiple locs yet");
1185 LastVal = VA.getValNo();
1187 if (VA.isRegLoc()) {
1188 MVT RegVT = VA.getLocVT();
1189 TargetRegisterClass *RC;
1190 if (RegVT == MVT::i32)
1191 RC = X86::GR32RegisterClass;
1192 else if (Is64Bit && RegVT == MVT::i64)
1193 RC = X86::GR64RegisterClass;
1194 else if (RegVT == MVT::f32)
1195 RC = X86::FR32RegisterClass;
1196 else if (RegVT == MVT::f64)
1197 RC = X86::FR64RegisterClass;
1198 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1199 RC = X86::VR128RegisterClass;
1200 else if (RegVT.isVector()) {
1201 assert(RegVT.getSizeInBits() == 64);
1203 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1205 // Darwin calling convention passes MMX values in either GPRs or
1206 // XMMs in x86-64. Other targets pass them in memory.
1207 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1208 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1211 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1216 assert(0 && "Unknown argument type!");
1219 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1220 SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1222 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1223 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1225 if (VA.getLocInfo() == CCValAssign::SExt)
1226 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1227 DAG.getValueType(VA.getValVT()));
1228 else if (VA.getLocInfo() == CCValAssign::ZExt)
1229 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1230 DAG.getValueType(VA.getValVT()));
1232 if (VA.getLocInfo() != CCValAssign::Full)
1233 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1235 // Handle MMX values passed in GPRs.
1236 if (Is64Bit && RegVT != VA.getLocVT()) {
1237 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1238 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1239 else if (RC == X86::VR128RegisterClass) {
1240 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1241 DAG.getConstant(0, MVT::i64));
1242 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1246 ArgValues.push_back(ArgValue);
1248 assert(VA.isMemLoc());
1249 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1253 // The x86-64 ABI for returning structs by value requires that we copy
1254 // the sret argument into %rax for the return. Save the argument into
1255 // a virtual register so that we can access it from the return points.
1256 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1257 MachineFunction &MF = DAG.getMachineFunction();
1258 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1259 unsigned Reg = FuncInfo->getSRetReturnReg();
1261 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1262 FuncInfo->setSRetReturnReg(Reg);
1264 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1265 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1268 unsigned StackSize = CCInfo.getNextStackOffset();
1269 // align stack specially for tail calls
1270 if (CC == CallingConv::Fast)
1271 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1273 // If the function takes variable number of arguments, make a frame index for
1274 // the start of the first vararg value... for expansion of llvm.va_start.
1276 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1277 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1280 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1282 // FIXME: We should really autogenerate these arrays
1283 static const unsigned GPR64ArgRegsWin64[] = {
1284 X86::RCX, X86::RDX, X86::R8, X86::R9
1286 static const unsigned XMMArgRegsWin64[] = {
1287 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1289 static const unsigned GPR64ArgRegs64Bit[] = {
1290 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1292 static const unsigned XMMArgRegs64Bit[] = {
1293 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1294 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1296 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1299 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1300 GPR64ArgRegs = GPR64ArgRegsWin64;
1301 XMMArgRegs = XMMArgRegsWin64;
1303 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1304 GPR64ArgRegs = GPR64ArgRegs64Bit;
1305 XMMArgRegs = XMMArgRegs64Bit;
1307 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1309 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1312 // For X86-64, if there are vararg parameters that are passed via
1313 // registers, then we must store them to their spots on the stack so they
1314 // may be loaded by deferencing the result of va_next.
1315 VarArgsGPOffset = NumIntRegs * 8;
1316 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1317 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1318 TotalNumXMMRegs * 16, 16);
1320 // Store the integer parameter registers.
1321 SmallVector<SDValue, 8> MemOps;
1322 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1323 SDValue FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1324 DAG.getIntPtrConstant(VarArgsGPOffset));
1325 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1326 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1327 X86::GR64RegisterClass);
1328 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1330 DAG.getStore(Val.getValue(1), Val, FIN,
1331 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1332 MemOps.push_back(Store);
1333 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1334 DAG.getIntPtrConstant(8));
1337 // Now store the XMM (fp + vector) parameter registers.
1338 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1339 DAG.getIntPtrConstant(VarArgsFPOffset));
1340 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1341 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1342 X86::VR128RegisterClass);
1343 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1345 DAG.getStore(Val.getValue(1), Val, FIN,
1346 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1347 MemOps.push_back(Store);
1348 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1349 DAG.getIntPtrConstant(16));
1351 if (!MemOps.empty())
1352 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1353 &MemOps[0], MemOps.size());
1357 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1358 // arguments and the arguments after the retaddr has been pushed are
1360 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1361 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1362 (StackSize & 7) == 0)
1365 ArgValues.push_back(Root);
1367 // Some CCs need callee pop.
1368 if (IsCalleePop(Op)) {
1369 BytesToPopOnReturn = StackSize; // Callee pops everything.
1370 BytesCallerReserves = 0;
1372 BytesToPopOnReturn = 0; // Callee pops nothing.
1373 // If this is an sret function, the return should pop the hidden pointer.
1374 if (!Is64Bit && ArgsAreStructReturn(Op))
1375 BytesToPopOnReturn = 4;
1376 BytesCallerReserves = StackSize;
1380 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1381 if (CC == CallingConv::X86_FastCall)
1382 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1385 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1387 // Return the new list of results.
1388 return DAG.getMergeValues(Op.Val->getVTList(), &ArgValues[0],
1389 ArgValues.size()).getValue(Op.ResNo);
1393 X86TargetLowering::LowerMemOpCallTo(SDValue Op, SelectionDAG &DAG,
1394 const SDValue &StackPtr,
1395 const CCValAssign &VA,
1398 unsigned LocMemOffset = VA.getLocMemOffset();
1399 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1400 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1401 ISD::ArgFlagsTy Flags =
1402 cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->getArgFlags();
1403 if (Flags.isByVal()) {
1404 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1406 return DAG.getStore(Chain, Arg, PtrOff,
1407 PseudoSourceValue::getStack(), LocMemOffset);
1410 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1411 /// optimization is performed and it is required.
1413 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1414 SDValue &OutRetAddr,
1419 if (!IsTailCall || FPDiff==0) return Chain;
1421 // Adjust the Return address stack slot.
1422 MVT VT = getPointerTy();
1423 OutRetAddr = getReturnAddressFrameIndex(DAG);
1424 // Load the "old" Return address.
1425 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1426 return SDValue(OutRetAddr.Val, 1);
1429 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1430 /// optimization is performed and it is required (FPDiff!=0).
1432 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1433 SDValue Chain, SDValue RetAddrFrIdx,
1434 bool Is64Bit, int FPDiff) {
1435 // Store the return address to the appropriate stack slot.
1436 if (!FPDiff) return Chain;
1437 // Calculate the new stack slot for the return address.
1438 int SlotSize = Is64Bit ? 8 : 4;
1439 int NewReturnAddrFI =
1440 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1441 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1442 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1443 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1444 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1448 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1449 MachineFunction &MF = DAG.getMachineFunction();
1450 SDValue Chain = Op.getOperand(0);
1451 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1452 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1453 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1454 && CC == CallingConv::Fast && PerformTailCallOpt;
1455 SDValue Callee = Op.getOperand(4);
1456 bool Is64Bit = Subtarget->is64Bit();
1457 bool IsStructRet = CallIsStructReturn(Op);
1459 assert(!(isVarArg && CC == CallingConv::Fast) &&
1460 "Var args not supported with calling convention fastcc");
1462 // Analyze operands of the call, assigning locations to each operand.
1463 SmallVector<CCValAssign, 16> ArgLocs;
1464 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1465 CCInfo.AnalyzeCallOperands(Op.Val, CCAssignFnForNode(Op));
1467 // Get a count of how many bytes are to be pushed on the stack.
1468 unsigned NumBytes = CCInfo.getNextStackOffset();
1469 if (CC == CallingConv::Fast)
1470 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1472 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1473 // arguments and the arguments after the retaddr has been pushed are aligned.
1474 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1475 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1476 (NumBytes & 7) == 0)
1481 // Lower arguments at fp - stackoffset + fpdiff.
1482 unsigned NumBytesCallerPushed =
1483 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1484 FPDiff = NumBytesCallerPushed - NumBytes;
1486 // Set the delta of movement of the returnaddr stackslot.
1487 // But only set if delta is greater than previous delta.
1488 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1489 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1492 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1494 SDValue RetAddrFrIdx;
1495 // Load return adress for tail calls.
1496 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1499 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1500 SmallVector<SDValue, 8> MemOpChains;
1503 // Walk the register/memloc assignments, inserting copies/loads. In the case
1504 // of tail call optimization arguments are handle later.
1505 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1506 CCValAssign &VA = ArgLocs[i];
1507 SDValue Arg = Op.getOperand(5+2*VA.getValNo());
1508 bool isByVal = cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->
1509 getArgFlags().isByVal();
1511 // Promote the value if needed.
1512 switch (VA.getLocInfo()) {
1513 default: assert(0 && "Unknown loc info!");
1514 case CCValAssign::Full: break;
1515 case CCValAssign::SExt:
1516 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1518 case CCValAssign::ZExt:
1519 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1521 case CCValAssign::AExt:
1522 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1526 if (VA.isRegLoc()) {
1528 MVT RegVT = VA.getLocVT();
1529 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1530 switch (VA.getLocReg()) {
1533 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1535 // Special case: passing MMX values in GPR registers.
1536 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1539 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1540 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1541 // Special case: passing MMX values in XMM registers.
1542 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1543 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1544 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1545 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1546 getMOVLMask(2, DAG));
1551 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1553 if (!IsTailCall || (IsTailCall && isByVal)) {
1554 assert(VA.isMemLoc());
1555 if (StackPtr.Val == 0)
1556 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1558 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1564 if (!MemOpChains.empty())
1565 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1566 &MemOpChains[0], MemOpChains.size());
1568 // Build a sequence of copy-to-reg nodes chained together with token chain
1569 // and flag operands which copy the outgoing args into registers.
1571 // Tail call byval lowering might overwrite argument registers so in case of
1572 // tail call optimization the copies to registers are lowered later.
1574 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1575 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1577 InFlag = Chain.getValue(1);
1580 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1582 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1583 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1584 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1586 InFlag = Chain.getValue(1);
1588 // If we are tail calling and generating PIC/GOT style code load the address
1589 // of the callee into ecx. The value in ecx is used as target of the tail
1590 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1591 // calls on PIC/GOT architectures. Normally we would just put the address of
1592 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1593 // restored (since ebx is callee saved) before jumping to the target@PLT.
1594 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1595 // Note: The actual moving to ecx is done further down.
1596 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1597 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1598 !G->getGlobal()->hasProtectedVisibility())
1599 Callee = LowerGlobalAddress(Callee, DAG);
1600 else if (isa<ExternalSymbolSDNode>(Callee))
1601 Callee = LowerExternalSymbol(Callee,DAG);
1604 if (Is64Bit && isVarArg) {
1605 // From AMD64 ABI document:
1606 // For calls that may call functions that use varargs or stdargs
1607 // (prototype-less calls or calls to functions containing ellipsis (...) in
1608 // the declaration) %al is used as hidden argument to specify the number
1609 // of SSE registers used. The contents of %al do not need to match exactly
1610 // the number of registers, but must be an ubound on the number of SSE
1611 // registers used and is in the range 0 - 8 inclusive.
1613 // FIXME: Verify this on Win64
1614 // Count the number of XMM registers allocated.
1615 static const unsigned XMMArgRegs[] = {
1616 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1617 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1619 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1621 Chain = DAG.getCopyToReg(Chain, X86::AL,
1622 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1623 InFlag = Chain.getValue(1);
1627 // For tail calls lower the arguments to the 'real' stack slot.
1629 SmallVector<SDValue, 8> MemOpChains2;
1632 // Do not flag preceeding copytoreg stuff together with the following stuff.
1634 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1635 CCValAssign &VA = ArgLocs[i];
1636 if (!VA.isRegLoc()) {
1637 assert(VA.isMemLoc());
1638 SDValue Arg = Op.getOperand(5+2*VA.getValNo());
1639 SDValue FlagsOp = Op.getOperand(6+2*VA.getValNo());
1640 ISD::ArgFlagsTy Flags =
1641 cast<ARG_FLAGSSDNode>(FlagsOp)->getArgFlags();
1642 // Create frame index.
1643 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1644 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1645 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1646 FIN = DAG.getFrameIndex(FI, getPointerTy());
1648 if (Flags.isByVal()) {
1649 // Copy relative to framepointer.
1650 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1651 if (StackPtr.Val == 0)
1652 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1653 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1655 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1658 // Store relative to framepointer.
1659 MemOpChains2.push_back(
1660 DAG.getStore(Chain, Arg, FIN,
1661 PseudoSourceValue::getFixedStack(FI), 0));
1666 if (!MemOpChains2.empty())
1667 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1668 &MemOpChains2[0], MemOpChains2.size());
1670 // Copy arguments to their registers.
1671 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1672 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1674 InFlag = Chain.getValue(1);
1678 // Store the return address to the appropriate stack slot.
1679 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1683 // If the callee is a GlobalAddress node (quite common, every direct call is)
1684 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1685 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1686 // We should use extra load for direct calls to dllimported functions in
1688 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1689 getTargetMachine(), true))
1690 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1691 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1692 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1693 } else if (IsTailCall) {
1694 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1696 Chain = DAG.getCopyToReg(Chain,
1697 DAG.getRegister(Opc, getPointerTy()),
1699 Callee = DAG.getRegister(Opc, getPointerTy());
1700 // Add register as live out.
1701 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1704 // Returns a chain & a flag for retval copy to use.
1705 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1706 SmallVector<SDValue, 8> Ops;
1709 Ops.push_back(Chain);
1710 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1711 Ops.push_back(DAG.getIntPtrConstant(0));
1713 Ops.push_back(InFlag);
1714 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1715 InFlag = Chain.getValue(1);
1717 // Returns a chain & a flag for retval copy to use.
1718 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1722 Ops.push_back(Chain);
1723 Ops.push_back(Callee);
1726 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1728 // Add argument registers to the end of the list so that they are known live
1730 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1731 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1732 RegsToPass[i].second.getValueType()));
1734 // Add an implicit use GOT pointer in EBX.
1735 if (!IsTailCall && !Is64Bit &&
1736 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1737 Subtarget->isPICStyleGOT())
1738 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1740 // Add an implicit use of AL for x86 vararg functions.
1741 if (Is64Bit && isVarArg)
1742 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1745 Ops.push_back(InFlag);
1748 assert(InFlag.Val &&
1749 "Flag must be set. Depend on flag being set in LowerRET");
1750 Chain = DAG.getNode(X86ISD::TAILCALL,
1751 Op.Val->getVTList(), &Ops[0], Ops.size());
1753 return SDValue(Chain.Val, Op.ResNo);
1756 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1757 InFlag = Chain.getValue(1);
1759 // Create the CALLSEQ_END node.
1760 unsigned NumBytesForCalleeToPush;
1761 if (IsCalleePop(Op))
1762 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1763 else if (!Is64Bit && IsStructRet)
1764 // If this is is a call to a struct-return function, the callee
1765 // pops the hidden struct pointer, so we have to push it back.
1766 // This is common for Darwin/X86, Linux & Mingw32 targets.
1767 NumBytesForCalleeToPush = 4;
1769 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1771 // Returns a flag for retval copy to use.
1772 Chain = DAG.getCALLSEQ_END(Chain,
1773 DAG.getIntPtrConstant(NumBytes),
1774 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1776 InFlag = Chain.getValue(1);
1778 // Handle result values, copying them out of physregs into vregs that we
1780 return SDValue(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1784 //===----------------------------------------------------------------------===//
1785 // Fast Calling Convention (tail call) implementation
1786 //===----------------------------------------------------------------------===//
1788 // Like std call, callee cleans arguments, convention except that ECX is
1789 // reserved for storing the tail called function address. Only 2 registers are
1790 // free for argument passing (inreg). Tail call optimization is performed
1792 // * tailcallopt is enabled
1793 // * caller/callee are fastcc
1794 // On X86_64 architecture with GOT-style position independent code only local
1795 // (within module) calls are supported at the moment.
1796 // To keep the stack aligned according to platform abi the function
1797 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1798 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1799 // If a tail called function callee has more arguments than the caller the
1800 // caller needs to make sure that there is room to move the RETADDR to. This is
1801 // achieved by reserving an area the size of the argument delta right after the
1802 // original REtADDR, but before the saved framepointer or the spilled registers
1803 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1815 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1816 /// for a 16 byte align requirement.
1817 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1818 SelectionDAG& DAG) {
1819 if (PerformTailCallOpt) {
1820 MachineFunction &MF = DAG.getMachineFunction();
1821 const TargetMachine &TM = MF.getTarget();
1822 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1823 unsigned StackAlignment = TFI.getStackAlignment();
1824 uint64_t AlignMask = StackAlignment - 1;
1825 int64_t Offset = StackSize;
1826 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1827 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1828 // Number smaller than 12 so just add the difference.
1829 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1831 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1832 Offset = ((~AlignMask) & Offset) + StackAlignment +
1833 (StackAlignment-SlotSize);
1840 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1841 /// following the call is a return. A function is eligible if caller/callee
1842 /// calling conventions match, currently only fastcc supports tail calls, and
1843 /// the function CALL is immediatly followed by a RET.
1844 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Call,
1846 SelectionDAG& DAG) const {
1847 if (!PerformTailCallOpt)
1850 if (CheckTailCallReturnConstraints(Call, Ret)) {
1851 MachineFunction &MF = DAG.getMachineFunction();
1852 unsigned CallerCC = MF.getFunction()->getCallingConv();
1853 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1854 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1855 SDValue Callee = Call.getOperand(4);
1856 // On x86/32Bit PIC/GOT tail calls are supported.
1857 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1858 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1861 // Can only do local tail calls (in same module, hidden or protected) on
1862 // x86_64 PIC/GOT at the moment.
1863 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1864 return G->getGlobal()->hasHiddenVisibility()
1865 || G->getGlobal()->hasProtectedVisibility();
1872 //===----------------------------------------------------------------------===//
1873 // Other Lowering Hooks
1874 //===----------------------------------------------------------------------===//
1877 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1878 MachineFunction &MF = DAG.getMachineFunction();
1879 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1880 int ReturnAddrIndex = FuncInfo->getRAIndex();
1882 if (ReturnAddrIndex == 0) {
1883 // Set up a frame object for the return address.
1884 if (Subtarget->is64Bit())
1885 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1887 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1889 FuncInfo->setRAIndex(ReturnAddrIndex);
1892 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1897 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1898 /// specific condition code. It returns a false if it cannot do a direct
1899 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1901 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1902 unsigned &X86CC, SDValue &LHS, SDValue &RHS,
1903 SelectionDAG &DAG) {
1904 X86CC = X86::COND_INVALID;
1906 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1907 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1908 // X > -1 -> X == 0, jump !sign.
1909 RHS = DAG.getConstant(0, RHS.getValueType());
1910 X86CC = X86::COND_NS;
1912 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1913 // X < 0 -> X == 0, jump on sign.
1914 X86CC = X86::COND_S;
1916 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1918 RHS = DAG.getConstant(0, RHS.getValueType());
1919 X86CC = X86::COND_LE;
1924 switch (SetCCOpcode) {
1926 case ISD::SETEQ: X86CC = X86::COND_E; break;
1927 case ISD::SETGT: X86CC = X86::COND_G; break;
1928 case ISD::SETGE: X86CC = X86::COND_GE; break;
1929 case ISD::SETLT: X86CC = X86::COND_L; break;
1930 case ISD::SETLE: X86CC = X86::COND_LE; break;
1931 case ISD::SETNE: X86CC = X86::COND_NE; break;
1932 case ISD::SETULT: X86CC = X86::COND_B; break;
1933 case ISD::SETUGT: X86CC = X86::COND_A; break;
1934 case ISD::SETULE: X86CC = X86::COND_BE; break;
1935 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1938 // On a floating point condition, the flags are set as follows:
1940 // 0 | 0 | 0 | X > Y
1941 // 0 | 0 | 1 | X < Y
1942 // 1 | 0 | 0 | X == Y
1943 // 1 | 1 | 1 | unordered
1945 switch (SetCCOpcode) {
1948 case ISD::SETEQ: X86CC = X86::COND_E; break;
1949 case ISD::SETOLT: Flip = true; // Fallthrough
1951 case ISD::SETGT: X86CC = X86::COND_A; break;
1952 case ISD::SETOLE: Flip = true; // Fallthrough
1954 case ISD::SETGE: X86CC = X86::COND_AE; break;
1955 case ISD::SETUGT: Flip = true; // Fallthrough
1957 case ISD::SETLT: X86CC = X86::COND_B; break;
1958 case ISD::SETUGE: Flip = true; // Fallthrough
1960 case ISD::SETLE: X86CC = X86::COND_BE; break;
1962 case ISD::SETNE: X86CC = X86::COND_NE; break;
1963 case ISD::SETUO: X86CC = X86::COND_P; break;
1964 case ISD::SETO: X86CC = X86::COND_NP; break;
1967 std::swap(LHS, RHS);
1970 return X86CC != X86::COND_INVALID;
1973 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1974 /// code. Current x86 isa includes the following FP cmov instructions:
1975 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1976 static bool hasFPCMov(unsigned X86CC) {
1992 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1993 /// true if Op is undef or if its value falls within the specified range (L, H].
1994 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
1995 if (Op.getOpcode() == ISD::UNDEF)
1998 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1999 return (Val >= Low && Val < Hi);
2002 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2003 /// true if Op is undef or if its value equal to the specified value.
2004 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2005 if (Op.getOpcode() == ISD::UNDEF)
2007 return cast<ConstantSDNode>(Op)->getValue() == Val;
2010 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2011 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2012 bool X86::isPSHUFDMask(SDNode *N) {
2013 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2015 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2018 // Check if the value doesn't reference the second vector.
2019 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2020 SDValue Arg = N->getOperand(i);
2021 if (Arg.getOpcode() == ISD::UNDEF) continue;
2022 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2023 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2030 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2031 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2032 bool X86::isPSHUFHWMask(SDNode *N) {
2033 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2035 if (N->getNumOperands() != 8)
2038 // Lower quadword copied in order.
2039 for (unsigned i = 0; i != 4; ++i) {
2040 SDValue Arg = N->getOperand(i);
2041 if (Arg.getOpcode() == ISD::UNDEF) continue;
2042 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2043 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2047 // Upper quadword shuffled.
2048 for (unsigned i = 4; i != 8; ++i) {
2049 SDValue Arg = N->getOperand(i);
2050 if (Arg.getOpcode() == ISD::UNDEF) continue;
2051 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2052 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2053 if (Val < 4 || Val > 7)
2060 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2061 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2062 bool X86::isPSHUFLWMask(SDNode *N) {
2063 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2065 if (N->getNumOperands() != 8)
2068 // Upper quadword copied in order.
2069 for (unsigned i = 4; i != 8; ++i)
2070 if (!isUndefOrEqual(N->getOperand(i), i))
2073 // Lower quadword shuffled.
2074 for (unsigned i = 0; i != 4; ++i)
2075 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2081 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2082 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2083 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2084 if (NumElems != 2 && NumElems != 4) return false;
2086 unsigned Half = NumElems / 2;
2087 for (unsigned i = 0; i < Half; ++i)
2088 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2090 for (unsigned i = Half; i < NumElems; ++i)
2091 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2097 bool X86::isSHUFPMask(SDNode *N) {
2098 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2099 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2102 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2103 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2104 /// half elements to come from vector 1 (which would equal the dest.) and
2105 /// the upper half to come from vector 2.
2106 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2107 if (NumOps != 2 && NumOps != 4) return false;
2109 unsigned Half = NumOps / 2;
2110 for (unsigned i = 0; i < Half; ++i)
2111 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2113 for (unsigned i = Half; i < NumOps; ++i)
2114 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2119 static bool isCommutedSHUFP(SDNode *N) {
2120 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2121 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2124 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2125 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2126 bool X86::isMOVHLPSMask(SDNode *N) {
2127 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2129 if (N->getNumOperands() != 4)
2132 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2133 return isUndefOrEqual(N->getOperand(0), 6) &&
2134 isUndefOrEqual(N->getOperand(1), 7) &&
2135 isUndefOrEqual(N->getOperand(2), 2) &&
2136 isUndefOrEqual(N->getOperand(3), 3);
2139 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2140 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2142 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2143 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2145 if (N->getNumOperands() != 4)
2148 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2149 return isUndefOrEqual(N->getOperand(0), 2) &&
2150 isUndefOrEqual(N->getOperand(1), 3) &&
2151 isUndefOrEqual(N->getOperand(2), 2) &&
2152 isUndefOrEqual(N->getOperand(3), 3);
2155 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2156 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2157 bool X86::isMOVLPMask(SDNode *N) {
2158 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2160 unsigned NumElems = N->getNumOperands();
2161 if (NumElems != 2 && NumElems != 4)
2164 for (unsigned i = 0; i < NumElems/2; ++i)
2165 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2168 for (unsigned i = NumElems/2; i < NumElems; ++i)
2169 if (!isUndefOrEqual(N->getOperand(i), i))
2175 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2176 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2178 bool X86::isMOVHPMask(SDNode *N) {
2179 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2181 unsigned NumElems = N->getNumOperands();
2182 if (NumElems != 2 && NumElems != 4)
2185 for (unsigned i = 0; i < NumElems/2; ++i)
2186 if (!isUndefOrEqual(N->getOperand(i), i))
2189 for (unsigned i = 0; i < NumElems/2; ++i) {
2190 SDValue Arg = N->getOperand(i + NumElems/2);
2191 if (!isUndefOrEqual(Arg, i + NumElems))
2198 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2199 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2200 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2201 bool V2IsSplat = false) {
2202 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2205 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2206 SDValue BitI = Elts[i];
2207 SDValue BitI1 = Elts[i+1];
2208 if (!isUndefOrEqual(BitI, j))
2211 if (isUndefOrEqual(BitI1, NumElts))
2214 if (!isUndefOrEqual(BitI1, j + NumElts))
2222 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2223 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2224 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2227 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2228 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2229 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2230 bool V2IsSplat = false) {
2231 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2234 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2235 SDValue BitI = Elts[i];
2236 SDValue BitI1 = Elts[i+1];
2237 if (!isUndefOrEqual(BitI, j + NumElts/2))
2240 if (isUndefOrEqual(BitI1, NumElts))
2243 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2251 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2252 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2253 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2256 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2257 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2259 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2260 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2262 unsigned NumElems = N->getNumOperands();
2263 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2266 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2267 SDValue BitI = N->getOperand(i);
2268 SDValue BitI1 = N->getOperand(i+1);
2270 if (!isUndefOrEqual(BitI, j))
2272 if (!isUndefOrEqual(BitI1, j))
2279 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2280 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2282 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2283 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2285 unsigned NumElems = N->getNumOperands();
2286 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2289 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2290 SDValue BitI = N->getOperand(i);
2291 SDValue BitI1 = N->getOperand(i + 1);
2293 if (!isUndefOrEqual(BitI, j))
2295 if (!isUndefOrEqual(BitI1, j))
2302 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2303 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2304 /// MOVSD, and MOVD, i.e. setting the lowest element.
2305 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2306 if (NumElts != 2 && NumElts != 4)
2309 if (!isUndefOrEqual(Elts[0], NumElts))
2312 for (unsigned i = 1; i < NumElts; ++i) {
2313 if (!isUndefOrEqual(Elts[i], i))
2320 bool X86::isMOVLMask(SDNode *N) {
2321 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2322 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2325 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2326 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2327 /// element of vector 2 and the other elements to come from vector 1 in order.
2328 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2329 bool V2IsSplat = false,
2330 bool V2IsUndef = false) {
2331 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2334 if (!isUndefOrEqual(Ops[0], 0))
2337 for (unsigned i = 1; i < NumOps; ++i) {
2338 SDValue Arg = Ops[i];
2339 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2340 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2341 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2348 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2349 bool V2IsUndef = false) {
2350 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2351 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2352 V2IsSplat, V2IsUndef);
2355 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2356 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2357 bool X86::isMOVSHDUPMask(SDNode *N) {
2358 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2360 if (N->getNumOperands() != 4)
2363 // Expect 1, 1, 3, 3
2364 for (unsigned i = 0; i < 2; ++i) {
2365 SDValue Arg = N->getOperand(i);
2366 if (Arg.getOpcode() == ISD::UNDEF) continue;
2367 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2368 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2369 if (Val != 1) return false;
2373 for (unsigned i = 2; i < 4; ++i) {
2374 SDValue Arg = N->getOperand(i);
2375 if (Arg.getOpcode() == ISD::UNDEF) continue;
2376 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2377 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2378 if (Val != 3) return false;
2382 // Don't use movshdup if it can be done with a shufps.
2386 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2387 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2388 bool X86::isMOVSLDUPMask(SDNode *N) {
2389 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2391 if (N->getNumOperands() != 4)
2394 // Expect 0, 0, 2, 2
2395 for (unsigned i = 0; i < 2; ++i) {
2396 SDValue Arg = N->getOperand(i);
2397 if (Arg.getOpcode() == ISD::UNDEF) continue;
2398 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2399 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2400 if (Val != 0) return false;
2404 for (unsigned i = 2; i < 4; ++i) {
2405 SDValue Arg = N->getOperand(i);
2406 if (Arg.getOpcode() == ISD::UNDEF) continue;
2407 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2408 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2409 if (Val != 2) return false;
2413 // Don't use movshdup if it can be done with a shufps.
2417 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2418 /// specifies a identity operation on the LHS or RHS.
2419 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2420 unsigned NumElems = N->getNumOperands();
2421 for (unsigned i = 0; i < NumElems; ++i)
2422 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2427 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2428 /// a splat of a single element.
2429 static bool isSplatMask(SDNode *N) {
2430 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2432 // This is a splat operation if each element of the permute is the same, and
2433 // if the value doesn't reference the second vector.
2434 unsigned NumElems = N->getNumOperands();
2435 SDValue ElementBase;
2437 for (; i != NumElems; ++i) {
2438 SDValue Elt = N->getOperand(i);
2439 if (isa<ConstantSDNode>(Elt)) {
2445 if (!ElementBase.Val)
2448 for (; i != NumElems; ++i) {
2449 SDValue Arg = N->getOperand(i);
2450 if (Arg.getOpcode() == ISD::UNDEF) continue;
2451 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2452 if (Arg != ElementBase) return false;
2455 // Make sure it is a splat of the first vector operand.
2456 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2459 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2460 /// a splat of a single element and it's a 2 or 4 element mask.
2461 bool X86::isSplatMask(SDNode *N) {
2462 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2464 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2465 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2467 return ::isSplatMask(N);
2470 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2471 /// specifies a splat of zero element.
2472 bool X86::isSplatLoMask(SDNode *N) {
2473 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2475 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2476 if (!isUndefOrEqual(N->getOperand(i), 0))
2481 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2482 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2484 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2485 unsigned NumOperands = N->getNumOperands();
2486 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2488 for (unsigned i = 0; i < NumOperands; ++i) {
2490 SDValue Arg = N->getOperand(NumOperands-i-1);
2491 if (Arg.getOpcode() != ISD::UNDEF)
2492 Val = cast<ConstantSDNode>(Arg)->getValue();
2493 if (Val >= NumOperands) Val -= NumOperands;
2495 if (i != NumOperands - 1)
2502 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2503 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2505 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2507 // 8 nodes, but we only care about the last 4.
2508 for (unsigned i = 7; i >= 4; --i) {
2510 SDValue Arg = N->getOperand(i);
2511 if (Arg.getOpcode() != ISD::UNDEF)
2512 Val = cast<ConstantSDNode>(Arg)->getValue();
2521 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2522 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2524 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2526 // 8 nodes, but we only care about the first 4.
2527 for (int i = 3; i >= 0; --i) {
2529 SDValue Arg = N->getOperand(i);
2530 if (Arg.getOpcode() != ISD::UNDEF)
2531 Val = cast<ConstantSDNode>(Arg)->getValue();
2540 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2541 /// specifies a 8 element shuffle that can be broken into a pair of
2542 /// PSHUFHW and PSHUFLW.
2543 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2544 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2546 if (N->getNumOperands() != 8)
2549 // Lower quadword shuffled.
2550 for (unsigned i = 0; i != 4; ++i) {
2551 SDValue Arg = N->getOperand(i);
2552 if (Arg.getOpcode() == ISD::UNDEF) continue;
2553 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2554 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2559 // Upper quadword shuffled.
2560 for (unsigned i = 4; i != 8; ++i) {
2561 SDValue Arg = N->getOperand(i);
2562 if (Arg.getOpcode() == ISD::UNDEF) continue;
2563 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2564 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2565 if (Val < 4 || Val > 7)
2572 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2573 /// values in ther permute mask.
2574 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2575 SDValue &V2, SDValue &Mask,
2576 SelectionDAG &DAG) {
2577 MVT VT = Op.getValueType();
2578 MVT MaskVT = Mask.getValueType();
2579 MVT EltVT = MaskVT.getVectorElementType();
2580 unsigned NumElems = Mask.getNumOperands();
2581 SmallVector<SDValue, 8> MaskVec;
2583 for (unsigned i = 0; i != NumElems; ++i) {
2584 SDValue Arg = Mask.getOperand(i);
2585 if (Arg.getOpcode() == ISD::UNDEF) {
2586 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2589 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2590 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2592 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2594 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2598 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2599 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2602 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2603 /// the two vector operands have swapped position.
2605 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2606 MVT MaskVT = Mask.getValueType();
2607 MVT EltVT = MaskVT.getVectorElementType();
2608 unsigned NumElems = Mask.getNumOperands();
2609 SmallVector<SDValue, 8> MaskVec;
2610 for (unsigned i = 0; i != NumElems; ++i) {
2611 SDValue Arg = Mask.getOperand(i);
2612 if (Arg.getOpcode() == ISD::UNDEF) {
2613 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2616 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2617 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2619 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2621 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2623 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2627 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2628 /// match movhlps. The lower half elements should come from upper half of
2629 /// V1 (and in order), and the upper half elements should come from the upper
2630 /// half of V2 (and in order).
2631 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2632 unsigned NumElems = Mask->getNumOperands();
2635 for (unsigned i = 0, e = 2; i != e; ++i)
2636 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2638 for (unsigned i = 2; i != 4; ++i)
2639 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2644 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2645 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2647 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2648 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2649 N = N->getOperand(0).Val;
2650 if (ISD::isNON_EXTLoad(N)) {
2652 *LD = cast<LoadSDNode>(N);
2659 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2660 /// match movlp{s|d}. The lower half elements should come from lower half of
2661 /// V1 (and in order), and the upper half elements should come from the upper
2662 /// half of V2 (and in order). And since V1 will become the source of the
2663 /// MOVLP, it must be either a vector load or a scalar load to vector.
2664 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2665 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2667 // Is V2 is a vector load, don't do this transformation. We will try to use
2668 // load folding shufps op.
2669 if (ISD::isNON_EXTLoad(V2))
2672 unsigned NumElems = Mask->getNumOperands();
2673 if (NumElems != 2 && NumElems != 4)
2675 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2676 if (!isUndefOrEqual(Mask->getOperand(i), i))
2678 for (unsigned i = NumElems/2; i != NumElems; ++i)
2679 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2684 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2686 static bool isSplatVector(SDNode *N) {
2687 if (N->getOpcode() != ISD::BUILD_VECTOR)
2690 SDValue SplatValue = N->getOperand(0);
2691 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2692 if (N->getOperand(i) != SplatValue)
2697 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2699 static bool isUndefShuffle(SDNode *N) {
2700 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2703 SDValue V1 = N->getOperand(0);
2704 SDValue V2 = N->getOperand(1);
2705 SDValue Mask = N->getOperand(2);
2706 unsigned NumElems = Mask.getNumOperands();
2707 for (unsigned i = 0; i != NumElems; ++i) {
2708 SDValue Arg = Mask.getOperand(i);
2709 if (Arg.getOpcode() != ISD::UNDEF) {
2710 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2711 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2713 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2720 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2722 static inline bool isZeroNode(SDValue Elt) {
2723 return ((isa<ConstantSDNode>(Elt) &&
2724 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2725 (isa<ConstantFPSDNode>(Elt) &&
2726 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2729 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2730 /// to an zero vector.
2731 static bool isZeroShuffle(SDNode *N) {
2732 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2735 SDValue V1 = N->getOperand(0);
2736 SDValue V2 = N->getOperand(1);
2737 SDValue Mask = N->getOperand(2);
2738 unsigned NumElems = Mask.getNumOperands();
2739 for (unsigned i = 0; i != NumElems; ++i) {
2740 SDValue Arg = Mask.getOperand(i);
2741 if (Arg.getOpcode() == ISD::UNDEF)
2744 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2745 if (Idx < NumElems) {
2746 unsigned Opc = V1.Val->getOpcode();
2747 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2749 if (Opc != ISD::BUILD_VECTOR ||
2750 !isZeroNode(V1.Val->getOperand(Idx)))
2752 } else if (Idx >= NumElems) {
2753 unsigned Opc = V2.Val->getOpcode();
2754 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2756 if (Opc != ISD::BUILD_VECTOR ||
2757 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2764 /// getZeroVector - Returns a vector of specified type with all zero elements.
2766 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2767 assert(VT.isVector() && "Expected a vector type");
2769 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2770 // type. This ensures they get CSE'd.
2772 if (VT.getSizeInBits() == 64) { // MMX
2773 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2774 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2775 } else if (HasSSE2) { // SSE2
2776 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2777 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2779 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2780 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2782 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2785 /// getOnesVector - Returns a vector of specified type with all bits set.
2787 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2788 assert(VT.isVector() && "Expected a vector type");
2790 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2791 // type. This ensures they get CSE'd.
2792 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2794 if (VT.getSizeInBits() == 64) // MMX
2795 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2797 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2798 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2802 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2803 /// that point to V2 points to its first element.
2804 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2805 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2807 bool Changed = false;
2808 SmallVector<SDValue, 8> MaskVec;
2809 unsigned NumElems = Mask.getNumOperands();
2810 for (unsigned i = 0; i != NumElems; ++i) {
2811 SDValue Arg = Mask.getOperand(i);
2812 if (Arg.getOpcode() != ISD::UNDEF) {
2813 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2814 if (Val > NumElems) {
2815 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2819 MaskVec.push_back(Arg);
2823 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2824 &MaskVec[0], MaskVec.size());
2828 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2829 /// operation of specified width.
2830 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2831 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2832 MVT BaseVT = MaskVT.getVectorElementType();
2834 SmallVector<SDValue, 8> MaskVec;
2835 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2836 for (unsigned i = 1; i != NumElems; ++i)
2837 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2838 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2841 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2842 /// of specified width.
2843 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2844 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2845 MVT BaseVT = MaskVT.getVectorElementType();
2846 SmallVector<SDValue, 8> MaskVec;
2847 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2848 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2849 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2851 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2854 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2855 /// of specified width.
2856 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2857 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2858 MVT BaseVT = MaskVT.getVectorElementType();
2859 unsigned Half = NumElems/2;
2860 SmallVector<SDValue, 8> MaskVec;
2861 for (unsigned i = 0; i != Half; ++i) {
2862 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2863 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2865 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2868 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2869 /// element #0 of a vector with the specified index, leaving the rest of the
2870 /// elements in place.
2871 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2872 SelectionDAG &DAG) {
2873 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2874 MVT BaseVT = MaskVT.getVectorElementType();
2875 SmallVector<SDValue, 8> MaskVec;
2876 // Element #0 of the result gets the elt we are replacing.
2877 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2878 for (unsigned i = 1; i != NumElems; ++i)
2879 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2880 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2883 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2884 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
2885 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2886 MVT VT = Op.getValueType();
2889 SDValue V1 = Op.getOperand(0);
2890 SDValue Mask = Op.getOperand(2);
2891 unsigned NumElems = Mask.getNumOperands();
2892 // Special handling of v4f32 -> v4i32.
2893 if (VT != MVT::v4f32) {
2894 Mask = getUnpacklMask(NumElems, DAG);
2895 while (NumElems > 4) {
2896 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2899 Mask = getZeroVector(MVT::v4i32, true, DAG);
2902 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2903 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2904 DAG.getNode(ISD::UNDEF, PVT), Mask);
2905 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2908 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2909 /// vector of zero or undef vector. This produces a shuffle where the low
2910 /// element of V2 is swizzled into the zero/undef vector, landing at element
2911 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2912 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2913 bool isZero, bool HasSSE2,
2914 SelectionDAG &DAG) {
2915 MVT VT = V2.getValueType();
2917 ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
2918 unsigned NumElems = V2.getValueType().getVectorNumElements();
2919 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2920 MVT EVT = MaskVT.getVectorElementType();
2921 SmallVector<SDValue, 16> MaskVec;
2922 for (unsigned i = 0; i != NumElems; ++i)
2923 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2924 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2926 MaskVec.push_back(DAG.getConstant(i, EVT));
2927 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2928 &MaskVec[0], MaskVec.size());
2929 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2932 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2933 /// a shuffle that is zero.
2935 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
2936 unsigned NumElems, bool Low,
2937 SelectionDAG &DAG) {
2938 unsigned NumZeros = 0;
2939 for (unsigned i = 0; i < NumElems; ++i) {
2940 unsigned Index = Low ? i : NumElems-i-1;
2941 SDValue Idx = Mask.getOperand(Index);
2942 if (Idx.getOpcode() == ISD::UNDEF) {
2946 SDValue Elt = DAG.getShuffleScalarElt(Op.Val, Index);
2947 if (Elt.Val && isZeroNode(Elt))
2955 /// isVectorShift - Returns true if the shuffle can be implemented as a
2956 /// logical left or right shift of a vector.
2957 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
2958 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
2959 unsigned NumElems = Mask.getNumOperands();
2962 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
2965 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
2970 bool SeenV1 = false;
2971 bool SeenV2 = false;
2972 for (unsigned i = NumZeros; i < NumElems; ++i) {
2973 unsigned Val = isLeft ? (i - NumZeros) : i;
2974 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
2975 if (Idx.getOpcode() == ISD::UNDEF)
2977 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
2978 if (Index < NumElems)
2987 if (SeenV1 && SeenV2)
2990 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
2996 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2998 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
2999 unsigned NumNonZero, unsigned NumZero,
3000 SelectionDAG &DAG, TargetLowering &TLI) {
3006 for (unsigned i = 0; i < 16; ++i) {
3007 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3008 if (ThisIsNonZero && First) {
3010 V = getZeroVector(MVT::v8i16, true, DAG);
3012 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3017 SDValue ThisElt(0, 0), LastElt(0, 0);
3018 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3019 if (LastIsNonZero) {
3020 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3022 if (ThisIsNonZero) {
3023 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3024 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3025 ThisElt, DAG.getConstant(8, MVT::i8));
3027 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3032 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3033 DAG.getIntPtrConstant(i/2));
3037 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3040 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3042 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3043 unsigned NumNonZero, unsigned NumZero,
3044 SelectionDAG &DAG, TargetLowering &TLI) {
3050 for (unsigned i = 0; i < 8; ++i) {
3051 bool isNonZero = (NonZeros & (1 << i)) != 0;
3055 V = getZeroVector(MVT::v8i16, true, DAG);
3057 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3060 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3061 DAG.getIntPtrConstant(i));
3068 /// getVShift - Return a vector logical shift node.
3070 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3071 unsigned NumBits, SelectionDAG &DAG,
3072 const TargetLowering &TLI) {
3073 bool isMMX = VT.getSizeInBits() == 64;
3074 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3075 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3076 SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3077 return DAG.getNode(ISD::BIT_CONVERT, VT,
3078 DAG.getNode(Opc, ShVT, SrcOp,
3079 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3083 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3084 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3085 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3086 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3087 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3088 // eliminated on x86-32 hosts.
3089 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3092 if (ISD::isBuildVectorAllOnes(Op.Val))
3093 return getOnesVector(Op.getValueType(), DAG);
3094 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3097 MVT VT = Op.getValueType();
3098 MVT EVT = VT.getVectorElementType();
3099 unsigned EVTBits = EVT.getSizeInBits();
3101 unsigned NumElems = Op.getNumOperands();
3102 unsigned NumZero = 0;
3103 unsigned NumNonZero = 0;
3104 unsigned NonZeros = 0;
3105 bool IsAllConstants = true;
3106 SmallSet<SDValue, 8> Values;
3107 for (unsigned i = 0; i < NumElems; ++i) {
3108 SDValue Elt = Op.getOperand(i);
3109 if (Elt.getOpcode() == ISD::UNDEF)
3112 if (Elt.getOpcode() != ISD::Constant &&
3113 Elt.getOpcode() != ISD::ConstantFP)
3114 IsAllConstants = false;
3115 if (isZeroNode(Elt))
3118 NonZeros |= (1 << i);
3123 if (NumNonZero == 0) {
3124 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3125 return DAG.getNode(ISD::UNDEF, VT);
3128 // Special case for single non-zero, non-undef, element.
3129 if (NumNonZero == 1 && NumElems <= 4) {
3130 unsigned Idx = CountTrailingZeros_32(NonZeros);
3131 SDValue Item = Op.getOperand(Idx);
3133 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3134 // the value are obviously zero, truncate the value to i32 and do the
3135 // insertion that way. Only do this if the value is non-constant or if the
3136 // value is a constant being inserted into element 0. It is cheaper to do
3137 // a constant pool load than it is to do a movd + shuffle.
3138 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3139 (!IsAllConstants || Idx == 0)) {
3140 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3141 // Handle MMX and SSE both.
3142 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3143 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3145 // Truncate the value (which may itself be a constant) to i32, and
3146 // convert it to a vector with movd (S2V+shuffle to zero extend).
3147 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3148 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3149 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3150 Subtarget->hasSSE2(), DAG);
3152 // Now we have our 32-bit value zero extended in the low element of
3153 // a vector. If Idx != 0, swizzle it into place.
3156 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3157 getSwapEltZeroMask(VecElts, Idx, DAG)
3159 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3161 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3165 // If we have a constant or non-constant insertion into the low element of
3166 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3167 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3168 // depending on what the source datatype is. Because we can only get here
3169 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3171 // Don't do this for i64 values on x86-32.
3172 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3173 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3174 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3175 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3176 Subtarget->hasSSE2(), DAG);
3179 // Is it a vector logical left shift?
3180 if (NumElems == 2 && Idx == 1 &&
3181 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3182 unsigned NumBits = VT.getSizeInBits();
3183 return getVShift(true, VT,
3184 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3185 NumBits/2, DAG, *this);
3188 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3191 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3192 // is a non-constant being inserted into an element other than the low one,
3193 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3194 // movd/movss) to move this into the low element, then shuffle it into
3196 if (EVTBits == 32) {
3197 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3199 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3200 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3201 Subtarget->hasSSE2(), DAG);
3202 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3203 MVT MaskEVT = MaskVT.getVectorElementType();
3204 SmallVector<SDValue, 8> MaskVec;
3205 for (unsigned i = 0; i < NumElems; i++)
3206 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3207 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3208 &MaskVec[0], MaskVec.size());
3209 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3210 DAG.getNode(ISD::UNDEF, VT), Mask);
3214 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3215 if (Values.size() == 1)
3218 // A vector full of immediates; various special cases are already
3219 // handled, so this is best done with a single constant-pool load.
3223 // Let legalizer expand 2-wide build_vectors.
3224 if (EVTBits == 64) {
3225 if (NumNonZero == 1) {
3226 // One half is zero or undef.
3227 unsigned Idx = CountTrailingZeros_32(NonZeros);
3228 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3229 Op.getOperand(Idx));
3230 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3231 Subtarget->hasSSE2(), DAG);
3236 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3237 if (EVTBits == 8 && NumElems == 16) {
3238 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3240 if (V.Val) return V;
3243 if (EVTBits == 16 && NumElems == 8) {
3244 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3246 if (V.Val) return V;
3249 // If element VT is == 32 bits, turn it into a number of shuffles.
3250 SmallVector<SDValue, 8> V;
3252 if (NumElems == 4 && NumZero > 0) {
3253 for (unsigned i = 0; i < 4; ++i) {
3254 bool isZero = !(NonZeros & (1 << i));
3256 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3258 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3261 for (unsigned i = 0; i < 2; ++i) {
3262 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3265 V[i] = V[i*2]; // Must be a zero vector.
3268 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3269 getMOVLMask(NumElems, DAG));
3272 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3273 getMOVLMask(NumElems, DAG));
3276 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3277 getUnpacklMask(NumElems, DAG));
3282 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3283 MVT EVT = MaskVT.getVectorElementType();
3284 SmallVector<SDValue, 8> MaskVec;
3285 bool Reverse = (NonZeros & 0x3) == 2;
3286 for (unsigned i = 0; i < 2; ++i)
3288 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3290 MaskVec.push_back(DAG.getConstant(i, EVT));
3291 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3292 for (unsigned i = 0; i < 2; ++i)
3294 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3296 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3297 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3298 &MaskVec[0], MaskVec.size());
3299 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3302 if (Values.size() > 2) {
3303 // Expand into a number of unpckl*.
3305 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3306 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3307 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3308 SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3309 for (unsigned i = 0; i < NumElems; ++i)
3310 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3312 while (NumElems != 0) {
3313 for (unsigned i = 0; i < NumElems; ++i)
3314 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3325 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3326 SDValue PermMask, SelectionDAG &DAG,
3327 TargetLowering &TLI) {
3329 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3330 MVT MaskEVT = MaskVT.getVectorElementType();
3331 MVT PtrVT = TLI.getPointerTy();
3332 SmallVector<SDValue, 8> MaskElts(PermMask.Val->op_begin(),
3333 PermMask.Val->op_end());
3335 // First record which half of which vector the low elements come from.
3336 SmallVector<unsigned, 4> LowQuad(4);
3337 for (unsigned i = 0; i < 4; ++i) {
3338 SDValue Elt = MaskElts[i];
3339 if (Elt.getOpcode() == ISD::UNDEF)
3341 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3342 int QuadIdx = EltIdx / 4;
3345 int BestLowQuad = -1;
3346 unsigned MaxQuad = 1;
3347 for (unsigned i = 0; i < 4; ++i) {
3348 if (LowQuad[i] > MaxQuad) {
3350 MaxQuad = LowQuad[i];
3354 // Record which half of which vector the high elements come from.
3355 SmallVector<unsigned, 4> HighQuad(4);
3356 for (unsigned i = 4; i < 8; ++i) {
3357 SDValue Elt = MaskElts[i];
3358 if (Elt.getOpcode() == ISD::UNDEF)
3360 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3361 int QuadIdx = EltIdx / 4;
3362 ++HighQuad[QuadIdx];
3364 int BestHighQuad = -1;
3366 for (unsigned i = 0; i < 4; ++i) {
3367 if (HighQuad[i] > MaxQuad) {
3369 MaxQuad = HighQuad[i];
3373 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3374 if (BestLowQuad != -1 || BestHighQuad != -1) {
3375 // First sort the 4 chunks in order using shufpd.
3376 SmallVector<SDValue, 8> MaskVec;
3377 if (BestLowQuad != -1)
3378 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3380 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3381 if (BestHighQuad != -1)
3382 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3384 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3385 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3386 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3387 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3388 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3389 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3391 // Now sort high and low parts separately.
3392 BitVector InOrder(8);
3393 if (BestLowQuad != -1) {
3394 // Sort lower half in order using PSHUFLW.
3396 bool AnyOutOrder = false;
3397 for (unsigned i = 0; i != 4; ++i) {
3398 SDValue Elt = MaskElts[i];
3399 if (Elt.getOpcode() == ISD::UNDEF) {
3400 MaskVec.push_back(Elt);
3403 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3406 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3407 // If this element is in the right place after this shuffle, then
3409 if ((int)(EltIdx / 4) == BestLowQuad)
3414 for (unsigned i = 4; i != 8; ++i)
3415 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3416 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3417 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3421 if (BestHighQuad != -1) {
3422 // Sort high half in order using PSHUFHW if possible.
3424 for (unsigned i = 0; i != 4; ++i)
3425 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3426 bool AnyOutOrder = false;
3427 for (unsigned i = 4; i != 8; ++i) {
3428 SDValue Elt = MaskElts[i];
3429 if (Elt.getOpcode() == ISD::UNDEF) {
3430 MaskVec.push_back(Elt);
3433 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3436 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3437 // If this element is in the right place after this shuffle, then
3439 if ((int)(EltIdx / 4) == BestHighQuad)
3444 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3445 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3449 // The other elements are put in the right place using pextrw and pinsrw.
3450 for (unsigned i = 0; i != 8; ++i) {
3453 SDValue Elt = MaskElts[i];
3454 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3455 SDValue ExtOp = (EltIdx < 8)
3456 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3457 DAG.getConstant(EltIdx, PtrVT))
3458 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3459 DAG.getConstant(EltIdx - 8, PtrVT));
3460 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3461 DAG.getConstant(i, PtrVT));
3466 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3467 ///as few as possible.
3468 // First, let's find out how many elements are already in the right order.
3469 unsigned V1InOrder = 0;
3470 unsigned V1FromV1 = 0;
3471 unsigned V2InOrder = 0;
3472 unsigned V2FromV2 = 0;
3473 SmallVector<SDValue, 8> V1Elts;
3474 SmallVector<SDValue, 8> V2Elts;
3475 for (unsigned i = 0; i < 8; ++i) {
3476 SDValue Elt = MaskElts[i];
3477 if (Elt.getOpcode() == ISD::UNDEF) {
3478 V1Elts.push_back(Elt);
3479 V2Elts.push_back(Elt);
3484 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3486 V1Elts.push_back(Elt);
3487 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3489 } else if (EltIdx == i+8) {
3490 V1Elts.push_back(Elt);
3491 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3493 } else if (EltIdx < 8) {
3494 V1Elts.push_back(Elt);
3497 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3502 if (V2InOrder > V1InOrder) {
3503 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3505 std::swap(V1Elts, V2Elts);
3506 std::swap(V1FromV1, V2FromV2);
3509 if ((V1FromV1 + V1InOrder) != 8) {
3510 // Some elements are from V2.
3512 // If there are elements that are from V1 but out of place,
3513 // then first sort them in place
3514 SmallVector<SDValue, 8> MaskVec;
3515 for (unsigned i = 0; i < 8; ++i) {
3516 SDValue Elt = V1Elts[i];
3517 if (Elt.getOpcode() == ISD::UNDEF) {
3518 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3521 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3523 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3525 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3527 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3528 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3532 for (unsigned i = 0; i < 8; ++i) {
3533 SDValue Elt = V1Elts[i];
3534 if (Elt.getOpcode() == ISD::UNDEF)
3536 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3539 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3540 DAG.getConstant(EltIdx - 8, PtrVT));
3541 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3542 DAG.getConstant(i, PtrVT));
3546 // All elements are from V1.
3548 for (unsigned i = 0; i < 8; ++i) {
3549 SDValue Elt = V1Elts[i];
3550 if (Elt.getOpcode() == ISD::UNDEF)
3552 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3553 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3554 DAG.getConstant(EltIdx, PtrVT));
3555 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3556 DAG.getConstant(i, PtrVT));
3562 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3563 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3564 /// done when every pair / quad of shuffle mask elements point to elements in
3565 /// the right sequence. e.g.
3566 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3568 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3570 SDValue PermMask, SelectionDAG &DAG,
3571 TargetLowering &TLI) {
3572 unsigned NumElems = PermMask.getNumOperands();
3573 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3574 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3575 MVT MaskEltVT = MaskVT.getVectorElementType();
3577 switch (VT.getSimpleVT()) {
3578 default: assert(false && "Unexpected!");
3579 case MVT::v4f32: NewVT = MVT::v2f64; break;
3580 case MVT::v4i32: NewVT = MVT::v2i64; break;
3581 case MVT::v8i16: NewVT = MVT::v4i32; break;
3582 case MVT::v16i8: NewVT = MVT::v4i32; break;
3585 if (NewWidth == 2) {
3591 unsigned Scale = NumElems / NewWidth;
3592 SmallVector<SDValue, 8> MaskVec;
3593 for (unsigned i = 0; i < NumElems; i += Scale) {
3594 unsigned StartIdx = ~0U;
3595 for (unsigned j = 0; j < Scale; ++j) {
3596 SDValue Elt = PermMask.getOperand(i+j);
3597 if (Elt.getOpcode() == ISD::UNDEF)
3599 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3600 if (StartIdx == ~0U)
3601 StartIdx = EltIdx - (EltIdx % Scale);
3602 if (EltIdx != StartIdx + j)
3605 if (StartIdx == ~0U)
3606 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3608 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3611 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3612 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3613 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3614 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3615 &MaskVec[0], MaskVec.size()));
3618 /// getVZextMovL - Return a zero-extending vector move low node.
3620 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3621 SDValue SrcOp, SelectionDAG &DAG,
3622 const X86Subtarget *Subtarget) {
3623 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3624 LoadSDNode *LD = NULL;
3625 if (!isScalarLoadToVector(SrcOp.Val, &LD))
3626 LD = dyn_cast<LoadSDNode>(SrcOp);
3628 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3630 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3631 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3632 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3633 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3634 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3636 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3637 return DAG.getNode(ISD::BIT_CONVERT, VT,
3638 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3639 DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3640 SrcOp.getOperand(0).getOperand(0))));
3645 return DAG.getNode(ISD::BIT_CONVERT, VT,
3646 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3647 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3650 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3653 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3654 SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3655 MVT MaskVT = PermMask.getValueType();
3656 MVT MaskEVT = MaskVT.getVectorElementType();
3657 SmallVector<std::pair<int, int>, 8> Locs;
3659 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3662 for (unsigned i = 0; i != 4; ++i) {
3663 SDValue Elt = PermMask.getOperand(i);
3664 if (Elt.getOpcode() == ISD::UNDEF) {
3665 Locs[i] = std::make_pair(-1, -1);
3667 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3668 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3670 Locs[i] = std::make_pair(0, NumLo);
3674 Locs[i] = std::make_pair(1, NumHi);
3676 Mask1[2+NumHi] = Elt;
3682 if (NumLo <= 2 && NumHi <= 2) {
3683 // If no more than two elements come from either vector. This can be
3684 // implemented with two shuffles. First shuffle gather the elements.
3685 // The second shuffle, which takes the first shuffle as both of its
3686 // vector operands, put the elements into the right order.
3687 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3688 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3689 &Mask1[0], Mask1.size()));
3691 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3692 for (unsigned i = 0; i != 4; ++i) {
3693 if (Locs[i].first == -1)
3696 unsigned Idx = (i < 2) ? 0 : 4;
3697 Idx += Locs[i].first * 2 + Locs[i].second;
3698 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3702 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3703 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3704 &Mask2[0], Mask2.size()));
3705 } else if (NumLo == 3 || NumHi == 3) {
3706 // Otherwise, we must have three elements from one vector, call it X, and
3707 // one element from the other, call it Y. First, use a shufps to build an
3708 // intermediate vector with the one element from Y and the element from X
3709 // that will be in the same half in the final destination (the indexes don't
3710 // matter). Then, use a shufps to build the final vector, taking the half
3711 // containing the element from Y from the intermediate, and the other half
3714 // Normalize it so the 3 elements come from V1.
3715 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3719 // Find the element from V2.
3721 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3722 SDValue Elt = PermMask.getOperand(HiIndex);
3723 if (Elt.getOpcode() == ISD::UNDEF)
3725 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3730 Mask1[0] = PermMask.getOperand(HiIndex);
3731 Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3732 Mask1[2] = PermMask.getOperand(HiIndex^1);
3733 Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3734 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3735 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3738 Mask1[0] = PermMask.getOperand(0);
3739 Mask1[1] = PermMask.getOperand(1);
3740 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3741 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3742 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3743 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3745 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3746 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3747 Mask1[2] = PermMask.getOperand(2);
3748 Mask1[3] = PermMask.getOperand(3);
3749 if (Mask1[2].getOpcode() != ISD::UNDEF)
3750 Mask1[2] = DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getValue()+4,
3752 if (Mask1[3].getOpcode() != ISD::UNDEF)
3753 Mask1[3] = DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getValue()+4,
3755 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3756 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3760 // Break it into (shuffle shuffle_hi, shuffle_lo).
3762 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3763 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3764 SmallVector<SDValue,8> *MaskPtr = &LoMask;
3765 unsigned MaskIdx = 0;
3768 for (unsigned i = 0; i != 4; ++i) {
3775 SDValue Elt = PermMask.getOperand(i);
3776 if (Elt.getOpcode() == ISD::UNDEF) {
3777 Locs[i] = std::make_pair(-1, -1);
3778 } else if (cast<ConstantSDNode>(Elt)->getValue() < 4) {
3779 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3780 (*MaskPtr)[LoIdx] = Elt;
3783 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3784 (*MaskPtr)[HiIdx] = Elt;
3789 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3790 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3791 &LoMask[0], LoMask.size()));
3792 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3793 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3794 &HiMask[0], HiMask.size()));
3795 SmallVector<SDValue, 8> MaskOps;
3796 for (unsigned i = 0; i != 4; ++i) {
3797 if (Locs[i].first == -1) {
3798 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3800 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3801 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3804 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3805 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3806 &MaskOps[0], MaskOps.size()));
3810 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3811 SDValue V1 = Op.getOperand(0);
3812 SDValue V2 = Op.getOperand(1);
3813 SDValue PermMask = Op.getOperand(2);
3814 MVT VT = Op.getValueType();
3815 unsigned NumElems = PermMask.getNumOperands();
3816 bool isMMX = VT.getSizeInBits() == 64;
3817 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3818 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3819 bool V1IsSplat = false;
3820 bool V2IsSplat = false;
3822 if (isUndefShuffle(Op.Val))
3823 return DAG.getNode(ISD::UNDEF, VT);
3825 if (isZeroShuffle(Op.Val))
3826 return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3828 if (isIdentityMask(PermMask.Val))
3830 else if (isIdentityMask(PermMask.Val, true))
3833 if (isSplatMask(PermMask.Val)) {
3834 if (isMMX || NumElems < 4) return Op;
3835 // Promote it to a v4{if}32 splat.
3836 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3839 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3841 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3842 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3844 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3845 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3846 // FIXME: Figure out a cleaner way to do this.
3847 // Try to make use of movq to zero out the top part.
3848 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3849 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3852 SDValue NewV1 = NewOp.getOperand(0);
3853 SDValue NewV2 = NewOp.getOperand(1);
3854 SDValue NewMask = NewOp.getOperand(2);
3855 if (isCommutedMOVL(NewMask.Val, true, false)) {
3856 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3857 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
3860 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3861 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3863 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3864 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3869 // Check if this can be converted into a logical shift.
3870 bool isLeft = false;
3873 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
3874 if (isShift && ShVal.hasOneUse()) {
3875 // If the shifted value has multiple uses, it may be cheaper to use
3876 // v_set0 + movlhps or movhlps, etc.
3877 MVT EVT = VT.getVectorElementType();
3878 ShAmt *= EVT.getSizeInBits();
3879 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3882 if (X86::isMOVLMask(PermMask.Val)) {
3885 if (ISD::isBuildVectorAllZeros(V1.Val))
3886 return getVZextMovL(VT, VT, V2, DAG, Subtarget);
3891 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.Val) ||
3892 X86::isMOVSLDUPMask(PermMask.Val) ||
3893 X86::isMOVHLPSMask(PermMask.Val) ||
3894 X86::isMOVHPMask(PermMask.Val) ||
3895 X86::isMOVLPMask(PermMask.Val)))
3898 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3899 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3900 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3903 // No better options. Use a vshl / vsrl.
3904 MVT EVT = VT.getVectorElementType();
3905 ShAmt *= EVT.getSizeInBits();
3906 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3909 bool Commuted = false;
3910 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3911 // 1,1,1,1 -> v8i16 though.
3912 V1IsSplat = isSplatVector(V1.Val);
3913 V2IsSplat = isSplatVector(V2.Val);
3915 // Canonicalize the splat or undef, if present, to be on the RHS.
3916 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3917 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3918 std::swap(V1IsSplat, V2IsSplat);
3919 std::swap(V1IsUndef, V2IsUndef);
3923 // FIXME: Figure out a cleaner way to do this.
3924 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3925 if (V2IsUndef) return V1;
3926 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3928 // V2 is a splat, so the mask may be malformed. That is, it may point
3929 // to any V2 element. The instruction selectior won't like this. Get
3930 // a corrected mask and commute to form a proper MOVS{S|D}.
3931 SDValue NewMask = getMOVLMask(NumElems, DAG);
3932 if (NewMask.Val != PermMask.Val)
3933 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3938 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3939 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3940 X86::isUNPCKLMask(PermMask.Val) ||
3941 X86::isUNPCKHMask(PermMask.Val))
3945 // Normalize mask so all entries that point to V2 points to its first
3946 // element then try to match unpck{h|l} again. If match, return a
3947 // new vector_shuffle with the corrected mask.
3948 SDValue NewMask = NormalizeMask(PermMask, DAG);
3949 if (NewMask.Val != PermMask.Val) {
3950 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3951 SDValue NewMask = getUnpacklMask(NumElems, DAG);
3952 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3953 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3954 SDValue NewMask = getUnpackhMask(NumElems, DAG);
3955 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3960 // Normalize the node to match x86 shuffle ops if needed
3961 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3962 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3965 // Commute is back and try unpck* again.
3966 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3967 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3968 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3969 X86::isUNPCKLMask(PermMask.Val) ||
3970 X86::isUNPCKHMask(PermMask.Val))
3974 // Try PSHUF* first, then SHUFP*.
3975 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
3976 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3977 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.Val)) {
3978 if (V2.getOpcode() != ISD::UNDEF)
3979 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3980 DAG.getNode(ISD::UNDEF, VT), PermMask);
3985 if (Subtarget->hasSSE2() &&
3986 (X86::isPSHUFDMask(PermMask.Val) ||
3987 X86::isPSHUFHWMask(PermMask.Val) ||
3988 X86::isPSHUFLWMask(PermMask.Val))) {
3990 if (VT == MVT::v4f32) {
3992 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
3993 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
3994 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3995 } else if (V2.getOpcode() != ISD::UNDEF)
3996 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
3997 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3999 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4003 // Binary or unary shufps.
4004 if (X86::isSHUFPMask(PermMask.Val) ||
4005 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.Val)))
4009 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4010 if (VT == MVT::v8i16) {
4011 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4016 // Handle all 4 wide cases with a number of shuffles except for MMX.
4017 if (NumElems == 4 && !isMMX)
4018 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4024 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4025 SelectionDAG &DAG) {
4026 MVT VT = Op.getValueType();
4027 if (VT.getSizeInBits() == 8) {
4028 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4029 Op.getOperand(0), Op.getOperand(1));
4030 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4031 DAG.getValueType(VT));
4032 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4033 } else if (VT.getSizeInBits() == 16) {
4034 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4035 Op.getOperand(0), Op.getOperand(1));
4036 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4037 DAG.getValueType(VT));
4038 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4039 } else if (VT == MVT::f32) {
4040 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4041 // the result back to FR32 register. It's only worth matching if the
4042 // result has a single use which is a store or a bitcast to i32.
4043 if (!Op.hasOneUse())
4045 SDNode *User = *Op.Val->use_begin();
4046 if (User->getOpcode() != ISD::STORE &&
4047 (User->getOpcode() != ISD::BIT_CONVERT ||
4048 User->getValueType(0) != MVT::i32))
4050 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4051 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4053 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4060 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4061 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4064 if (Subtarget->hasSSE41()) {
4065 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4070 MVT VT = Op.getValueType();
4071 // TODO: handle v16i8.
4072 if (VT.getSizeInBits() == 16) {
4073 SDValue Vec = Op.getOperand(0);
4074 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4076 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4077 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4078 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4080 // Transform it so it match pextrw which produces a 32-bit result.
4081 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4082 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4083 Op.getOperand(0), Op.getOperand(1));
4084 SDValue Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
4085 DAG.getValueType(VT));
4086 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4087 } else if (VT.getSizeInBits() == 32) {
4088 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4091 // SHUFPS the element to the lowest double word, then movss.
4092 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4093 SmallVector<SDValue, 8> IdxVec;
4095 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4097 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4099 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4101 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4102 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4103 &IdxVec[0], IdxVec.size());
4104 SDValue Vec = Op.getOperand(0);
4105 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4106 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4107 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4108 DAG.getIntPtrConstant(0));
4109 } else if (VT.getSizeInBits() == 64) {
4110 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4111 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4112 // to match extract_elt for f64.
4113 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4117 // UNPCKHPD the element to the lowest double word, then movsd.
4118 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4119 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4120 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4121 SmallVector<SDValue, 8> IdxVec;
4122 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4124 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4125 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4126 &IdxVec[0], IdxVec.size());
4127 SDValue Vec = Op.getOperand(0);
4128 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4129 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4130 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4131 DAG.getIntPtrConstant(0));
4138 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4139 MVT VT = Op.getValueType();
4140 MVT EVT = VT.getVectorElementType();
4142 SDValue N0 = Op.getOperand(0);
4143 SDValue N1 = Op.getOperand(1);
4144 SDValue N2 = Op.getOperand(2);
4146 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4147 isa<ConstantSDNode>(N2)) {
4148 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4150 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4152 if (N1.getValueType() != MVT::i32)
4153 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4154 if (N2.getValueType() != MVT::i32)
4155 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
4156 return DAG.getNode(Opc, VT, N0, N1, N2);
4157 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4158 // Bits [7:6] of the constant are the source select. This will always be
4159 // zero here. The DAG Combiner may combine an extract_elt index into these
4160 // bits. For example (insert (extract, 3), 2) could be matched by putting
4161 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4162 // Bits [5:4] of the constant are the destination select. This is the
4163 // value of the incoming immediate.
4164 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4165 // combine either bitwise AND or insert of float 0.0 to set these bits.
4166 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
4167 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4173 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4174 MVT VT = Op.getValueType();
4175 MVT EVT = VT.getVectorElementType();
4177 if (Subtarget->hasSSE41())
4178 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4183 SDValue N0 = Op.getOperand(0);
4184 SDValue N1 = Op.getOperand(1);
4185 SDValue N2 = Op.getOperand(2);
4187 if (EVT.getSizeInBits() == 16) {
4188 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4189 // as its second argument.
4190 if (N1.getValueType() != MVT::i32)
4191 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4192 if (N2.getValueType() != MVT::i32)
4193 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
4194 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4200 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4201 if (Op.getValueType() == MVT::v2f32)
4202 return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4203 DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4204 DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4205 Op.getOperand(0))));
4207 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4208 MVT VT = MVT::v2i32;
4209 switch (Op.getValueType().getSimpleVT()) {
4216 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4217 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4220 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4221 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4222 // one of the above mentioned nodes. It has to be wrapped because otherwise
4223 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4224 // be used to form addressing mode. These wrapped nodes will be selected
4227 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4228 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4229 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4231 CP->getAlignment());
4232 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4233 // With PIC, the address is actually $g + Offset.
4234 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4235 !Subtarget->isPICStyleRIPRel()) {
4236 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4237 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4245 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4246 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4247 SDValue Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4248 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4249 // With PIC, the address is actually $g + Offset.
4250 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4251 !Subtarget->isPICStyleRIPRel()) {
4252 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4253 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4257 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4258 // load the value at address GV, not the value of GV itself. This means that
4259 // the GlobalAddress must be in the base or index register of the address, not
4260 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4261 // The same applies for external symbols during PIC codegen
4262 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4263 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4264 PseudoSourceValue::getGOT(), 0);
4269 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4271 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4274 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4275 DAG.getNode(X86ISD::GlobalBaseReg,
4277 InFlag = Chain.getValue(1);
4279 // emit leal symbol@TLSGD(,%ebx,1), %eax
4280 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4281 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4282 GA->getValueType(0),
4284 SDValue Ops[] = { Chain, TGA, InFlag };
4285 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4286 InFlag = Result.getValue(2);
4287 Chain = Result.getValue(1);
4289 // call ___tls_get_addr. This function receives its argument in
4290 // the register EAX.
4291 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4292 InFlag = Chain.getValue(1);
4294 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4295 SDValue Ops1[] = { Chain,
4296 DAG.getTargetExternalSymbol("___tls_get_addr",
4298 DAG.getRegister(X86::EAX, PtrVT),
4299 DAG.getRegister(X86::EBX, PtrVT),
4301 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4302 InFlag = Chain.getValue(1);
4304 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4307 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4309 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4311 SDValue InFlag, Chain;
4313 // emit leaq symbol@TLSGD(%rip), %rdi
4314 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4315 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4316 GA->getValueType(0),
4318 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4319 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4320 Chain = Result.getValue(1);
4321 InFlag = Result.getValue(2);
4323 // call ___tls_get_addr. This function receives its argument in
4324 // the register RDI.
4325 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4326 InFlag = Chain.getValue(1);
4328 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4329 SDValue Ops1[] = { Chain,
4330 DAG.getTargetExternalSymbol("___tls_get_addr",
4332 DAG.getRegister(X86::RDI, PtrVT),
4334 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4335 InFlag = Chain.getValue(1);
4337 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4340 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4341 // "local exec" model.
4342 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4344 // Get the Thread Pointer
4345 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4346 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4348 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4349 GA->getValueType(0),
4351 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4353 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4354 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4355 PseudoSourceValue::getGOT(), 0);
4357 // The address of the thread local variable is the add of the thread
4358 // pointer with the offset of the variable.
4359 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4363 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4364 // TODO: implement the "local dynamic" model
4365 // TODO: implement the "initial exec"model for pic executables
4366 assert(Subtarget->isTargetELF() &&
4367 "TLS not implemented for non-ELF targets");
4368 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4369 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4370 // otherwise use the "Local Exec"TLS Model
4371 if (Subtarget->is64Bit()) {
4372 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4374 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4375 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4377 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4382 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4383 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4384 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4385 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4386 // With PIC, the address is actually $g + Offset.
4387 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4388 !Subtarget->isPICStyleRIPRel()) {
4389 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4390 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4397 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4398 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4399 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4400 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4401 // With PIC, the address is actually $g + Offset.
4402 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4403 !Subtarget->isPICStyleRIPRel()) {
4404 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4405 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4412 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4413 /// take a 2 x i32 value to shift plus a shift amount.
4414 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4415 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4416 MVT VT = Op.getValueType();
4417 unsigned VTBits = VT.getSizeInBits();
4418 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4419 SDValue ShOpLo = Op.getOperand(0);
4420 SDValue ShOpHi = Op.getOperand(1);
4421 SDValue ShAmt = Op.getOperand(2);
4422 SDValue Tmp1 = isSRA ?
4423 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4424 DAG.getConstant(0, VT);
4427 if (Op.getOpcode() == ISD::SHL_PARTS) {
4428 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4429 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4431 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4432 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4435 SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4436 DAG.getConstant(VTBits, MVT::i8));
4437 SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4438 AndNode, DAG.getConstant(0, MVT::i8));
4441 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4442 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4443 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4445 if (Op.getOpcode() == ISD::SHL_PARTS) {
4446 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4447 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4449 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4450 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4453 SDValue Ops[2] = { Lo, Hi };
4454 return DAG.getMergeValues(Ops, 2);
4457 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4458 MVT SrcVT = Op.getOperand(0).getValueType();
4459 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4460 "Unknown SINT_TO_FP to lower!");
4462 // These are really Legal; caller falls through into that case.
4463 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4465 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4466 Subtarget->is64Bit())
4469 unsigned Size = SrcVT.getSizeInBits()/8;
4470 MachineFunction &MF = DAG.getMachineFunction();
4471 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4472 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4473 SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4475 PseudoSourceValue::getFixedStack(SSFI), 0);
4479 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4481 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4483 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4484 SmallVector<SDValue, 8> Ops;
4485 Ops.push_back(Chain);
4486 Ops.push_back(StackSlot);
4487 Ops.push_back(DAG.getValueType(SrcVT));
4488 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4489 Tys, &Ops[0], Ops.size());
4492 Chain = Result.getValue(1);
4493 SDValue InFlag = Result.getValue(2);
4495 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4496 // shouldn't be necessary except that RFP cannot be live across
4497 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4498 MachineFunction &MF = DAG.getMachineFunction();
4499 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4500 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4501 Tys = DAG.getVTList(MVT::Other);
4502 SmallVector<SDValue, 8> Ops;
4503 Ops.push_back(Chain);
4504 Ops.push_back(Result);
4505 Ops.push_back(StackSlot);
4506 Ops.push_back(DAG.getValueType(Op.getValueType()));
4507 Ops.push_back(InFlag);
4508 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4509 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4510 PseudoSourceValue::getFixedStack(SSFI), 0);
4516 std::pair<SDValue,SDValue> X86TargetLowering::
4517 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4518 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4519 Op.getValueType().getSimpleVT() >= MVT::i16 &&
4520 "Unknown FP_TO_SINT to lower!");
4522 // These are really Legal.
4523 if (Op.getValueType() == MVT::i32 &&
4524 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4525 return std::make_pair(SDValue(), SDValue());
4526 if (Subtarget->is64Bit() &&
4527 Op.getValueType() == MVT::i64 &&
4528 Op.getOperand(0).getValueType() != MVT::f80)
4529 return std::make_pair(SDValue(), SDValue());
4531 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4533 MachineFunction &MF = DAG.getMachineFunction();
4534 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4535 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4536 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4538 switch (Op.getValueType().getSimpleVT()) {
4539 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4540 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4541 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4542 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4545 SDValue Chain = DAG.getEntryNode();
4546 SDValue Value = Op.getOperand(0);
4547 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4548 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4549 Chain = DAG.getStore(Chain, Value, StackSlot,
4550 PseudoSourceValue::getFixedStack(SSFI), 0);
4551 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4553 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4555 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4556 Chain = Value.getValue(1);
4557 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4558 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4561 // Build the FP_TO_INT*_IN_MEM
4562 SDValue Ops[] = { Chain, Value, StackSlot };
4563 SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4565 return std::make_pair(FIST, StackSlot);
4568 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4569 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4570 SDValue FIST = Vals.first, StackSlot = Vals.second;
4571 if (FIST.Val == 0) return SDValue();
4574 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4577 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4578 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
4579 SDValue FIST = Vals.first, StackSlot = Vals.second;
4580 if (FIST.Val == 0) return 0;
4582 MVT VT = N->getValueType(0);
4584 // Return a load from the stack slot.
4585 SDValue Res = DAG.getLoad(VT, FIST, StackSlot, NULL, 0);
4587 // Use MERGE_VALUES to drop the chain result value and get a node with one
4588 // result. This requires turning off getMergeValues simplification, since
4589 // otherwise it will give us Res back.
4590 return DAG.getMergeValues(&Res, 1, false).Val;
4593 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4594 MVT VT = Op.getValueType();
4597 EltVT = VT.getVectorElementType();
4598 std::vector<Constant*> CV;
4599 if (EltVT == MVT::f64) {
4600 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4604 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4610 Constant *C = ConstantVector::get(CV);
4611 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4612 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4613 PseudoSourceValue::getConstantPool(), 0,
4615 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4618 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4619 MVT VT = Op.getValueType();
4621 unsigned EltNum = 1;
4622 if (VT.isVector()) {
4623 EltVT = VT.getVectorElementType();
4624 EltNum = VT.getVectorNumElements();
4626 std::vector<Constant*> CV;
4627 if (EltVT == MVT::f64) {
4628 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4632 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4638 Constant *C = ConstantVector::get(CV);
4639 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4640 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4641 PseudoSourceValue::getConstantPool(), 0,
4643 if (VT.isVector()) {
4644 return DAG.getNode(ISD::BIT_CONVERT, VT,
4645 DAG.getNode(ISD::XOR, MVT::v2i64,
4646 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4647 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4649 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4653 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4654 SDValue Op0 = Op.getOperand(0);
4655 SDValue Op1 = Op.getOperand(1);
4656 MVT VT = Op.getValueType();
4657 MVT SrcVT = Op1.getValueType();
4659 // If second operand is smaller, extend it first.
4660 if (SrcVT.bitsLT(VT)) {
4661 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4664 // And if it is bigger, shrink it first.
4665 if (SrcVT.bitsGT(VT)) {
4666 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4670 // At this point the operands and the result should have the same
4671 // type, and that won't be f80 since that is not custom lowered.
4673 // First get the sign bit of second operand.
4674 std::vector<Constant*> CV;
4675 if (SrcVT == MVT::f64) {
4676 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4677 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4679 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4680 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4681 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4682 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4684 Constant *C = ConstantVector::get(CV);
4685 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4686 SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4687 PseudoSourceValue::getConstantPool(), 0,
4689 SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4691 // Shift sign bit right or left if the two operands have different types.
4692 if (SrcVT.bitsGT(VT)) {
4693 // Op0 is MVT::f32, Op1 is MVT::f64.
4694 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4695 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4696 DAG.getConstant(32, MVT::i32));
4697 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4698 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4699 DAG.getIntPtrConstant(0));
4702 // Clear first operand sign bit.
4704 if (VT == MVT::f64) {
4705 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4706 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4708 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4709 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4710 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4711 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4713 C = ConstantVector::get(CV);
4714 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4715 SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4716 PseudoSourceValue::getConstantPool(), 0,
4718 SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4720 // Or the value with the sign bit.
4721 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4724 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
4725 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4727 SDValue Op0 = Op.getOperand(0);
4728 SDValue Op1 = Op.getOperand(1);
4729 SDValue CC = Op.getOperand(2);
4730 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4731 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4734 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4736 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4737 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4738 DAG.getConstant(X86CC, MVT::i8), Cond);
4741 assert(isFP && "Illegal integer SetCC!");
4743 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4744 switch (SetCCOpcode) {
4745 default: assert(false && "Illegal floating point SetCC!");
4746 case ISD::SETOEQ: { // !PF & ZF
4747 SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4748 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4749 SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4750 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4751 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4753 case ISD::SETUNE: { // PF | !ZF
4754 SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4755 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4756 SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4757 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4758 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4763 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4765 SDValue Op0 = Op.getOperand(0);
4766 SDValue Op1 = Op.getOperand(1);
4767 SDValue CC = Op.getOperand(2);
4768 MVT VT = Op.getValueType();
4769 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4770 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4774 MVT VT0 = Op0.getValueType();
4775 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
4776 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
4779 switch (SetCCOpcode) {
4782 case ISD::SETEQ: SSECC = 0; break;
4784 case ISD::SETGT: Swap = true; // Fallthrough
4786 case ISD::SETOLT: SSECC = 1; break;
4788 case ISD::SETGE: Swap = true; // Fallthrough
4790 case ISD::SETOLE: SSECC = 2; break;
4791 case ISD::SETUO: SSECC = 3; break;
4793 case ISD::SETNE: SSECC = 4; break;
4794 case ISD::SETULE: Swap = true;
4795 case ISD::SETUGE: SSECC = 5; break;
4796 case ISD::SETULT: Swap = true;
4797 case ISD::SETUGT: SSECC = 6; break;
4798 case ISD::SETO: SSECC = 7; break;
4801 std::swap(Op0, Op1);
4803 // In the two special cases we can't handle, emit two comparisons.
4805 if (SetCCOpcode == ISD::SETUEQ) {
4807 UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
4808 EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
4809 return DAG.getNode(ISD::OR, VT, UNORD, EQ);
4811 else if (SetCCOpcode == ISD::SETONE) {
4813 ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
4814 NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
4815 return DAG.getNode(ISD::AND, VT, ORD, NEQ);
4817 assert(0 && "Illegal FP comparison");
4819 // Handle all other FP comparisons here.
4820 return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
4823 // We are handling one of the integer comparisons here. Since SSE only has
4824 // GT and EQ comparisons for integer, swapping operands and multiple
4825 // operations may be required for some comparisons.
4826 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
4827 bool Swap = false, Invert = false, FlipSigns = false;
4829 switch (VT.getSimpleVT()) {
4831 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
4832 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
4833 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
4834 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
4837 switch (SetCCOpcode) {
4839 case ISD::SETNE: Invert = true;
4840 case ISD::SETEQ: Opc = EQOpc; break;
4841 case ISD::SETLT: Swap = true;
4842 case ISD::SETGT: Opc = GTOpc; break;
4843 case ISD::SETGE: Swap = true;
4844 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
4845 case ISD::SETULT: Swap = true;
4846 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
4847 case ISD::SETUGE: Swap = true;
4848 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
4851 std::swap(Op0, Op1);
4853 // Since SSE has no unsigned integer comparisons, we need to flip the sign
4854 // bits of the inputs before performing those operations.
4856 MVT EltVT = VT.getVectorElementType();
4857 SDValue SignBit = DAG.getConstant(EltVT.getIntegerVTSignBit(), EltVT);
4858 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
4859 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
4861 Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
4862 Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
4865 SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
4867 // If the logical-not of the result is required, perform that now.
4869 MVT EltVT = VT.getVectorElementType();
4870 SDValue NegOne = DAG.getConstant(EltVT.getIntegerVTBitMask(), EltVT);
4871 std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOne);
4872 SDValue NegOneV = DAG.getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0],
4874 Result = DAG.getNode(ISD::XOR, VT, Result, NegOneV);
4879 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
4880 bool addTest = true;
4881 SDValue Cond = Op.getOperand(0);
4884 if (Cond.getOpcode() == ISD::SETCC)
4885 Cond = LowerSETCC(Cond, DAG);
4887 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4888 // setting operand in place of the X86ISD::SETCC.
4889 if (Cond.getOpcode() == X86ISD::SETCC) {
4890 CC = Cond.getOperand(0);
4892 SDValue Cmp = Cond.getOperand(1);
4893 unsigned Opc = Cmp.getOpcode();
4894 MVT VT = Op.getValueType();
4896 bool IllegalFPCMov = false;
4897 if (VT.isFloatingPoint() && !VT.isVector() &&
4898 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4899 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4901 if ((Opc == X86ISD::CMP ||
4902 Opc == X86ISD::COMI ||
4903 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4910 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4911 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4914 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4916 SmallVector<SDValue, 4> Ops;
4917 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4918 // condition is true.
4919 Ops.push_back(Op.getOperand(2));
4920 Ops.push_back(Op.getOperand(1));
4922 Ops.push_back(Cond);
4923 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4926 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
4927 bool addTest = true;
4928 SDValue Chain = Op.getOperand(0);
4929 SDValue Cond = Op.getOperand(1);
4930 SDValue Dest = Op.getOperand(2);
4933 if (Cond.getOpcode() == ISD::SETCC)
4934 Cond = LowerSETCC(Cond, DAG);
4936 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4937 // setting operand in place of the X86ISD::SETCC.
4938 if (Cond.getOpcode() == X86ISD::SETCC) {
4939 CC = Cond.getOperand(0);
4941 SDValue Cmp = Cond.getOperand(1);
4942 unsigned Opc = Cmp.getOpcode();
4943 if (Opc == X86ISD::CMP ||
4944 Opc == X86ISD::COMI ||
4945 Opc == X86ISD::UCOMI) {
4952 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4953 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4955 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4956 Chain, Op.getOperand(2), CC, Cond);
4960 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4961 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4962 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4963 // that the guard pages used by the OS virtual memory manager are allocated in
4964 // correct sequence.
4966 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4967 SelectionDAG &DAG) {
4968 assert(Subtarget->isTargetCygMing() &&
4969 "This should be used only on Cygwin/Mingw targets");
4972 SDValue Chain = Op.getOperand(0);
4973 SDValue Size = Op.getOperand(1);
4974 // FIXME: Ensure alignment here
4978 MVT IntPtr = getPointerTy();
4979 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4981 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0));
4983 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4984 Flag = Chain.getValue(1);
4986 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4987 SDValue Ops[] = { Chain,
4988 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4989 DAG.getRegister(X86::EAX, IntPtr),
4990 DAG.getRegister(X86StackPtr, SPTy),
4992 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
4993 Flag = Chain.getValue(1);
4995 Chain = DAG.getCALLSEQ_END(Chain,
4996 DAG.getIntPtrConstant(0),
4997 DAG.getIntPtrConstant(0),
5000 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5002 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5003 return DAG.getMergeValues(Ops1, 2);
5007 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5009 SDValue Dst, SDValue Src,
5010 SDValue Size, unsigned Align,
5011 const Value *DstSV, uint64_t DstSVOff) {
5012 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5014 /// If not DWORD aligned or size is more than the threshold, call the library.
5015 /// The libc version is likely to be faster for these cases. It can use the
5016 /// address value and run time information about the CPU.
5017 if ((Align & 3) == 0 ||
5019 ConstantSize->getValue() > getSubtarget()->getMaxInlineSizeThreshold()) {
5020 SDValue InFlag(0, 0);
5022 // Check to see if there is a specialized entry-point for memory zeroing.
5023 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5024 if (const char *bzeroEntry =
5025 V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5026 MVT IntPtr = getPointerTy();
5027 const Type *IntPtrTy = getTargetData()->getIntPtrType();
5028 TargetLowering::ArgListTy Args;
5029 TargetLowering::ArgListEntry Entry;
5031 Entry.Ty = IntPtrTy;
5032 Args.push_back(Entry);
5034 Args.push_back(Entry);
5035 std::pair<SDValue,SDValue> CallResult =
5036 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
5037 false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
5039 return CallResult.second;
5042 // Otherwise have the target-independent code call memset.
5046 uint64_t SizeVal = ConstantSize->getValue();
5047 SDValue InFlag(0, 0);
5050 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5051 unsigned BytesLeft = 0;
5052 bool TwoRepStos = false;
5055 uint64_t Val = ValC->getValue() & 255;
5057 // If the value is a constant, then we can potentially use larger sets.
5058 switch (Align & 3) {
5059 case 2: // WORD aligned
5062 Val = (Val << 8) | Val;
5064 case 0: // DWORD aligned
5067 Val = (Val << 8) | Val;
5068 Val = (Val << 16) | Val;
5069 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5072 Val = (Val << 32) | Val;
5075 default: // Byte aligned
5078 Count = DAG.getIntPtrConstant(SizeVal);
5082 if (AVT.bitsGT(MVT::i8)) {
5083 unsigned UBytes = AVT.getSizeInBits() / 8;
5084 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5085 BytesLeft = SizeVal % UBytes;
5088 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5090 InFlag = Chain.getValue(1);
5093 Count = DAG.getIntPtrConstant(SizeVal);
5094 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5095 InFlag = Chain.getValue(1);
5098 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5100 InFlag = Chain.getValue(1);
5101 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5103 InFlag = Chain.getValue(1);
5105 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5106 SmallVector<SDValue, 8> Ops;
5107 Ops.push_back(Chain);
5108 Ops.push_back(DAG.getValueType(AVT));
5109 Ops.push_back(InFlag);
5110 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5113 InFlag = Chain.getValue(1);
5115 MVT CVT = Count.getValueType();
5116 SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5117 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5118 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5120 InFlag = Chain.getValue(1);
5121 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5123 Ops.push_back(Chain);
5124 Ops.push_back(DAG.getValueType(MVT::i8));
5125 Ops.push_back(InFlag);
5126 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5127 } else if (BytesLeft) {
5128 // Handle the last 1 - 7 bytes.
5129 unsigned Offset = SizeVal - BytesLeft;
5130 MVT AddrVT = Dst.getValueType();
5131 MVT SizeVT = Size.getValueType();
5133 Chain = DAG.getMemset(Chain,
5134 DAG.getNode(ISD::ADD, AddrVT, Dst,
5135 DAG.getConstant(Offset, AddrVT)),
5137 DAG.getConstant(BytesLeft, SizeVT),
5138 Align, DstSV, DstSVOff + Offset);
5141 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5146 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5148 SDValue Dst, SDValue Src,
5149 SDValue Size, unsigned Align,
5151 const Value *DstSV, uint64_t DstSVOff,
5152 const Value *SrcSV, uint64_t SrcSVOff){
5154 // This requires the copy size to be a constant, preferrably
5155 // within a subtarget-specific limit.
5156 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5159 uint64_t SizeVal = ConstantSize->getValue();
5160 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5164 unsigned BytesLeft = 0;
5165 if (Align >= 8 && Subtarget->is64Bit())
5167 else if (Align >= 4)
5169 else if (Align >= 2)
5174 unsigned UBytes = AVT.getSizeInBits() / 8;
5175 unsigned CountVal = SizeVal / UBytes;
5176 SDValue Count = DAG.getIntPtrConstant(CountVal);
5177 BytesLeft = SizeVal % UBytes;
5179 SDValue InFlag(0, 0);
5180 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5182 InFlag = Chain.getValue(1);
5183 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5185 InFlag = Chain.getValue(1);
5186 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5188 InFlag = Chain.getValue(1);
5190 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5191 SmallVector<SDValue, 8> Ops;
5192 Ops.push_back(Chain);
5193 Ops.push_back(DAG.getValueType(AVT));
5194 Ops.push_back(InFlag);
5195 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5197 SmallVector<SDValue, 4> Results;
5198 Results.push_back(RepMovs);
5200 // Handle the last 1 - 7 bytes.
5201 unsigned Offset = SizeVal - BytesLeft;
5202 MVT DstVT = Dst.getValueType();
5203 MVT SrcVT = Src.getValueType();
5204 MVT SizeVT = Size.getValueType();
5205 Results.push_back(DAG.getMemcpy(Chain,
5206 DAG.getNode(ISD::ADD, DstVT, Dst,
5207 DAG.getConstant(Offset, DstVT)),
5208 DAG.getNode(ISD::ADD, SrcVT, Src,
5209 DAG.getConstant(Offset, SrcVT)),
5210 DAG.getConstant(BytesLeft, SizeVT),
5211 Align, AlwaysInline,
5212 DstSV, DstSVOff + Offset,
5213 SrcSV, SrcSVOff + Offset));
5216 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5219 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
5220 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
5221 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5222 SDValue TheChain = N->getOperand(0);
5223 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
5224 if (Subtarget->is64Bit()) {
5225 SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
5226 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
5227 MVT::i64, rax.getValue(2));
5228 SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
5229 DAG.getConstant(32, MVT::i8));
5231 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
5234 return DAG.getMergeValues(Ops, 2).Val;
5237 SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
5238 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
5239 MVT::i32, eax.getValue(2));
5240 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
5241 SDValue Ops[] = { eax, edx };
5242 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
5244 // Use a MERGE_VALUES to return the value and chain.
5245 Ops[1] = edx.getValue(1);
5246 return DAG.getMergeValues(Ops, 2).Val;
5249 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5250 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5252 if (!Subtarget->is64Bit()) {
5253 // vastart just stores the address of the VarArgsFrameIndex slot into the
5254 // memory location argument.
5255 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5256 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5260 // gp_offset (0 - 6 * 8)
5261 // fp_offset (48 - 48 + 8 * 16)
5262 // overflow_arg_area (point to parameters coming in memory).
5264 SmallVector<SDValue, 8> MemOps;
5265 SDValue FIN = Op.getOperand(1);
5267 SDValue Store = DAG.getStore(Op.getOperand(0),
5268 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5270 MemOps.push_back(Store);
5273 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5274 Store = DAG.getStore(Op.getOperand(0),
5275 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5277 MemOps.push_back(Store);
5279 // Store ptr to overflow_arg_area
5280 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5281 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5282 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5283 MemOps.push_back(Store);
5285 // Store ptr to reg_save_area.
5286 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5287 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5288 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5289 MemOps.push_back(Store);
5290 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5293 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5294 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5295 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5296 SDValue Chain = Op.getOperand(0);
5297 SDValue SrcPtr = Op.getOperand(1);
5298 SDValue SrcSV = Op.getOperand(2);
5300 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5305 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5306 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5307 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5308 SDValue Chain = Op.getOperand(0);
5309 SDValue DstPtr = Op.getOperand(1);
5310 SDValue SrcPtr = Op.getOperand(2);
5311 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5312 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5314 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5315 DAG.getIntPtrConstant(24), 8, false,
5316 DstSV, 0, SrcSV, 0);
5320 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5321 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5323 default: return SDValue(); // Don't custom lower most intrinsics.
5324 // Comparison intrinsics.
5325 case Intrinsic::x86_sse_comieq_ss:
5326 case Intrinsic::x86_sse_comilt_ss:
5327 case Intrinsic::x86_sse_comile_ss:
5328 case Intrinsic::x86_sse_comigt_ss:
5329 case Intrinsic::x86_sse_comige_ss:
5330 case Intrinsic::x86_sse_comineq_ss:
5331 case Intrinsic::x86_sse_ucomieq_ss:
5332 case Intrinsic::x86_sse_ucomilt_ss:
5333 case Intrinsic::x86_sse_ucomile_ss:
5334 case Intrinsic::x86_sse_ucomigt_ss:
5335 case Intrinsic::x86_sse_ucomige_ss:
5336 case Intrinsic::x86_sse_ucomineq_ss:
5337 case Intrinsic::x86_sse2_comieq_sd:
5338 case Intrinsic::x86_sse2_comilt_sd:
5339 case Intrinsic::x86_sse2_comile_sd:
5340 case Intrinsic::x86_sse2_comigt_sd:
5341 case Intrinsic::x86_sse2_comige_sd:
5342 case Intrinsic::x86_sse2_comineq_sd:
5343 case Intrinsic::x86_sse2_ucomieq_sd:
5344 case Intrinsic::x86_sse2_ucomilt_sd:
5345 case Intrinsic::x86_sse2_ucomile_sd:
5346 case Intrinsic::x86_sse2_ucomigt_sd:
5347 case Intrinsic::x86_sse2_ucomige_sd:
5348 case Intrinsic::x86_sse2_ucomineq_sd: {
5350 ISD::CondCode CC = ISD::SETCC_INVALID;
5353 case Intrinsic::x86_sse_comieq_ss:
5354 case Intrinsic::x86_sse2_comieq_sd:
5358 case Intrinsic::x86_sse_comilt_ss:
5359 case Intrinsic::x86_sse2_comilt_sd:
5363 case Intrinsic::x86_sse_comile_ss:
5364 case Intrinsic::x86_sse2_comile_sd:
5368 case Intrinsic::x86_sse_comigt_ss:
5369 case Intrinsic::x86_sse2_comigt_sd:
5373 case Intrinsic::x86_sse_comige_ss:
5374 case Intrinsic::x86_sse2_comige_sd:
5378 case Intrinsic::x86_sse_comineq_ss:
5379 case Intrinsic::x86_sse2_comineq_sd:
5383 case Intrinsic::x86_sse_ucomieq_ss:
5384 case Intrinsic::x86_sse2_ucomieq_sd:
5385 Opc = X86ISD::UCOMI;
5388 case Intrinsic::x86_sse_ucomilt_ss:
5389 case Intrinsic::x86_sse2_ucomilt_sd:
5390 Opc = X86ISD::UCOMI;
5393 case Intrinsic::x86_sse_ucomile_ss:
5394 case Intrinsic::x86_sse2_ucomile_sd:
5395 Opc = X86ISD::UCOMI;
5398 case Intrinsic::x86_sse_ucomigt_ss:
5399 case Intrinsic::x86_sse2_ucomigt_sd:
5400 Opc = X86ISD::UCOMI;
5403 case Intrinsic::x86_sse_ucomige_ss:
5404 case Intrinsic::x86_sse2_ucomige_sd:
5405 Opc = X86ISD::UCOMI;
5408 case Intrinsic::x86_sse_ucomineq_ss:
5409 case Intrinsic::x86_sse2_ucomineq_sd:
5410 Opc = X86ISD::UCOMI;
5416 SDValue LHS = Op.getOperand(1);
5417 SDValue RHS = Op.getOperand(2);
5418 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5420 SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5421 SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5422 DAG.getConstant(X86CC, MVT::i8), Cond);
5423 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5426 // Fix vector shift instructions where the last operand is a non-immediate
5428 case Intrinsic::x86_sse2_pslli_w:
5429 case Intrinsic::x86_sse2_pslli_d:
5430 case Intrinsic::x86_sse2_pslli_q:
5431 case Intrinsic::x86_sse2_psrli_w:
5432 case Intrinsic::x86_sse2_psrli_d:
5433 case Intrinsic::x86_sse2_psrli_q:
5434 case Intrinsic::x86_sse2_psrai_w:
5435 case Intrinsic::x86_sse2_psrai_d:
5436 case Intrinsic::x86_mmx_pslli_w:
5437 case Intrinsic::x86_mmx_pslli_d:
5438 case Intrinsic::x86_mmx_pslli_q:
5439 case Intrinsic::x86_mmx_psrli_w:
5440 case Intrinsic::x86_mmx_psrli_d:
5441 case Intrinsic::x86_mmx_psrli_q:
5442 case Intrinsic::x86_mmx_psrai_w:
5443 case Intrinsic::x86_mmx_psrai_d: {
5444 SDValue ShAmt = Op.getOperand(2);
5445 if (isa<ConstantSDNode>(ShAmt))
5448 unsigned NewIntNo = 0;
5449 MVT ShAmtVT = MVT::v4i32;
5451 case Intrinsic::x86_sse2_pslli_w:
5452 NewIntNo = Intrinsic::x86_sse2_psll_w;
5454 case Intrinsic::x86_sse2_pslli_d:
5455 NewIntNo = Intrinsic::x86_sse2_psll_d;
5457 case Intrinsic::x86_sse2_pslli_q:
5458 NewIntNo = Intrinsic::x86_sse2_psll_q;
5460 case Intrinsic::x86_sse2_psrli_w:
5461 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5463 case Intrinsic::x86_sse2_psrli_d:
5464 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5466 case Intrinsic::x86_sse2_psrli_q:
5467 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5469 case Intrinsic::x86_sse2_psrai_w:
5470 NewIntNo = Intrinsic::x86_sse2_psra_w;
5472 case Intrinsic::x86_sse2_psrai_d:
5473 NewIntNo = Intrinsic::x86_sse2_psra_d;
5476 ShAmtVT = MVT::v2i32;
5478 case Intrinsic::x86_mmx_pslli_w:
5479 NewIntNo = Intrinsic::x86_mmx_psll_w;
5481 case Intrinsic::x86_mmx_pslli_d:
5482 NewIntNo = Intrinsic::x86_mmx_psll_d;
5484 case Intrinsic::x86_mmx_pslli_q:
5485 NewIntNo = Intrinsic::x86_mmx_psll_q;
5487 case Intrinsic::x86_mmx_psrli_w:
5488 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5490 case Intrinsic::x86_mmx_psrli_d:
5491 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5493 case Intrinsic::x86_mmx_psrli_q:
5494 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5496 case Intrinsic::x86_mmx_psrai_w:
5497 NewIntNo = Intrinsic::x86_mmx_psra_w;
5499 case Intrinsic::x86_mmx_psrai_d:
5500 NewIntNo = Intrinsic::x86_mmx_psra_d;
5502 default: abort(); // Can't reach here.
5507 MVT VT = Op.getValueType();
5508 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5509 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5510 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5511 DAG.getConstant(NewIntNo, MVT::i32),
5512 Op.getOperand(1), ShAmt);
5517 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5518 // Depths > 0 not supported yet!
5519 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5522 // Just load the return address
5523 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5524 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5527 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5528 // Depths > 0 not supported yet!
5529 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5532 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5533 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5534 DAG.getIntPtrConstant(!Subtarget->is64Bit() ? 4 : 8));
5537 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
5538 SelectionDAG &DAG) {
5539 // Is not yet supported on x86-64
5540 if (Subtarget->is64Bit())
5543 return DAG.getIntPtrConstant(8);
5546 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
5548 assert(!Subtarget->is64Bit() &&
5549 "Lowering of eh_return builtin is not supported yet on x86-64");
5551 MachineFunction &MF = DAG.getMachineFunction();
5552 SDValue Chain = Op.getOperand(0);
5553 SDValue Offset = Op.getOperand(1);
5554 SDValue Handler = Op.getOperand(2);
5556 SDValue Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5559 SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5560 DAG.getIntPtrConstant(-4UL));
5561 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5562 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5563 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5564 MF.getRegInfo().addLiveOut(X86::ECX);
5566 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5567 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5570 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
5571 SelectionDAG &DAG) {
5572 SDValue Root = Op.getOperand(0);
5573 SDValue Trmp = Op.getOperand(1); // trampoline
5574 SDValue FPtr = Op.getOperand(2); // nested function
5575 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
5577 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5579 const X86InstrInfo *TII =
5580 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5582 if (Subtarget->is64Bit()) {
5583 SDValue OutChains[6];
5585 // Large code-model.
5587 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5588 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5590 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5591 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5593 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5595 // Load the pointer to the nested function into R11.
5596 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5597 SDValue Addr = Trmp;
5598 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5601 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5602 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5604 // Load the 'nest' parameter value into R10.
5605 // R10 is specified in X86CallingConv.td
5606 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5607 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5608 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5611 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5612 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5614 // Jump to the nested function.
5615 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5616 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5617 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5620 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5621 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5622 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5626 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5627 return DAG.getMergeValues(Ops, 2);
5629 const Function *Func =
5630 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5631 unsigned CC = Func->getCallingConv();
5636 assert(0 && "Unsupported calling convention");
5637 case CallingConv::C:
5638 case CallingConv::X86_StdCall: {
5639 // Pass 'nest' parameter in ECX.
5640 // Must be kept in sync with X86CallingConv.td
5643 // Check that ECX wasn't needed by an 'inreg' parameter.
5644 const FunctionType *FTy = Func->getFunctionType();
5645 const PAListPtr &Attrs = Func->getParamAttrs();
5647 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5648 unsigned InRegCount = 0;
5651 for (FunctionType::param_iterator I = FTy->param_begin(),
5652 E = FTy->param_end(); I != E; ++I, ++Idx)
5653 if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5654 // FIXME: should only count parameters that are lowered to integers.
5655 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5657 if (InRegCount > 2) {
5658 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5664 case CallingConv::X86_FastCall:
5665 // Pass 'nest' parameter in EAX.
5666 // Must be kept in sync with X86CallingConv.td
5671 SDValue OutChains[4];
5674 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5675 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5677 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5678 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
5679 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5682 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5683 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5685 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5686 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5687 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5688 TrmpAddr, 5, false, 1);
5690 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5691 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5694 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5695 return DAG.getMergeValues(Ops, 2);
5699 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
5701 The rounding mode is in bits 11:10 of FPSR, and has the following
5708 FLT_ROUNDS, on the other hand, expects the following:
5715 To perform the conversion, we do:
5716 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5719 MachineFunction &MF = DAG.getMachineFunction();
5720 const TargetMachine &TM = MF.getTarget();
5721 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5722 unsigned StackAlignment = TFI.getStackAlignment();
5723 MVT VT = Op.getValueType();
5725 // Save FP Control Word to stack slot
5726 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5727 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5729 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5730 DAG.getEntryNode(), StackSlot);
5732 // Load FP Control Word from stack slot
5733 SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5735 // Transform as necessary
5737 DAG.getNode(ISD::SRL, MVT::i16,
5738 DAG.getNode(ISD::AND, MVT::i16,
5739 CWD, DAG.getConstant(0x800, MVT::i16)),
5740 DAG.getConstant(11, MVT::i8));
5742 DAG.getNode(ISD::SRL, MVT::i16,
5743 DAG.getNode(ISD::AND, MVT::i16,
5744 CWD, DAG.getConstant(0x400, MVT::i16)),
5745 DAG.getConstant(9, MVT::i8));
5748 DAG.getNode(ISD::AND, MVT::i16,
5749 DAG.getNode(ISD::ADD, MVT::i16,
5750 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5751 DAG.getConstant(1, MVT::i16)),
5752 DAG.getConstant(3, MVT::i16));
5755 return DAG.getNode((VT.getSizeInBits() < 16 ?
5756 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5759 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
5760 MVT VT = Op.getValueType();
5762 unsigned NumBits = VT.getSizeInBits();
5764 Op = Op.getOperand(0);
5765 if (VT == MVT::i8) {
5766 // Zero extend to i32 since there is not an i8 bsr.
5768 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5771 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5772 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5773 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5775 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5776 SmallVector<SDValue, 4> Ops;
5778 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5779 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5780 Ops.push_back(Op.getValue(1));
5781 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5783 // Finally xor with NumBits-1.
5784 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5787 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5791 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
5792 MVT VT = Op.getValueType();
5794 unsigned NumBits = VT.getSizeInBits();
5796 Op = Op.getOperand(0);
5797 if (VT == MVT::i8) {
5799 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5802 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5803 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5804 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5806 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5807 SmallVector<SDValue, 4> Ops;
5809 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5810 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5811 Ops.push_back(Op.getValue(1));
5812 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5815 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5819 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
5820 MVT T = Op.getValueType();
5823 switch(T.getSimpleVT()) {
5825 assert(false && "Invalid value type!");
5826 case MVT::i8: Reg = X86::AL; size = 1; break;
5827 case MVT::i16: Reg = X86::AX; size = 2; break;
5828 case MVT::i32: Reg = X86::EAX; size = 4; break;
5830 if (Subtarget->is64Bit()) {
5831 Reg = X86::RAX; size = 8;
5832 } else //Should go away when LowerType stuff lands
5833 return SDValue(ExpandATOMIC_CMP_SWAP(Op.Val, DAG), 0);
5836 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5837 Op.getOperand(3), SDValue());
5838 SDValue Ops[] = { cpIn.getValue(0),
5841 DAG.getTargetConstant(size, MVT::i8),
5843 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5844 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5846 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5850 SDNode* X86TargetLowering::ExpandATOMIC_CMP_SWAP(SDNode* Op, SelectionDAG &DAG) {
5851 MVT T = Op->getValueType(0);
5852 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
5853 SDValue cpInL, cpInH;
5854 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5855 DAG.getConstant(0, MVT::i32));
5856 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5857 DAG.getConstant(1, MVT::i32));
5858 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5860 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5861 cpInH, cpInL.getValue(1));
5862 SDValue swapInL, swapInH;
5863 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5864 DAG.getConstant(0, MVT::i32));
5865 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5866 DAG.getConstant(1, MVT::i32));
5867 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5868 swapInL, cpInH.getValue(1));
5869 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5870 swapInH, swapInL.getValue(1));
5871 SDValue Ops[] = { swapInH.getValue(0),
5873 swapInH.getValue(1)};
5874 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5875 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5876 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5877 Result.getValue(1));
5878 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5879 cpOutL.getValue(2));
5880 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5881 SDValue ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5882 SDValue Vals[2] = { ResultVal, cpOutH.getValue(1) };
5883 return DAG.getMergeValues(Vals, 2).Val;
5886 SDNode* X86TargetLowering::ExpandATOMIC_LOAD_SUB(SDNode* Op, SelectionDAG &DAG) {
5887 MVT T = Op->getValueType(0);
5888 SDValue negOp = DAG.getNode(ISD::SUB, T,
5889 DAG.getConstant(0, T), Op->getOperand(2));
5890 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, Op->getOperand(0),
5891 Op->getOperand(1), negOp,
5892 cast<AtomicSDNode>(Op)->getSrcValue(),
5893 cast<AtomicSDNode>(Op)->getAlignment()).Val;
5896 /// LowerOperation - Provide custom lowering hooks for some operations.
5898 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5899 switch (Op.getOpcode()) {
5900 default: assert(0 && "Should not custom lower this!");
5901 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
5902 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5903 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5904 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5905 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5906 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5907 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5908 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5909 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5910 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5911 case ISD::SHL_PARTS:
5912 case ISD::SRA_PARTS:
5913 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5914 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5915 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5916 case ISD::FABS: return LowerFABS(Op, DAG);
5917 case ISD::FNEG: return LowerFNEG(Op, DAG);
5918 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5919 case ISD::SETCC: return LowerSETCC(Op, DAG);
5920 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
5921 case ISD::SELECT: return LowerSELECT(Op, DAG);
5922 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5923 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5924 case ISD::CALL: return LowerCALL(Op, DAG);
5925 case ISD::RET: return LowerRET(Op, DAG);
5926 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5927 case ISD::VASTART: return LowerVASTART(Op, DAG);
5928 case ISD::VAARG: return LowerVAARG(Op, DAG);
5929 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5930 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5931 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5932 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5933 case ISD::FRAME_TO_ARGS_OFFSET:
5934 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5935 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5936 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5937 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5938 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5939 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5940 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5942 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5943 case ISD::READCYCLECOUNTER:
5944 return SDValue(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5948 /// ReplaceNodeResults - Replace a node with an illegal result type
5949 /// with a new node built out of custom code.
5950 SDNode *X86TargetLowering::ReplaceNodeResults(SDNode *N, SelectionDAG &DAG) {
5951 switch (N->getOpcode()) {
5952 default: assert(0 && "Should not custom lower this!");
5953 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5954 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5955 case ISD::ATOMIC_CMP_SWAP: return ExpandATOMIC_CMP_SWAP(N, DAG);
5956 case ISD::ATOMIC_LOAD_SUB: return ExpandATOMIC_LOAD_SUB(N,DAG);
5960 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5962 default: return NULL;
5963 case X86ISD::BSF: return "X86ISD::BSF";
5964 case X86ISD::BSR: return "X86ISD::BSR";
5965 case X86ISD::SHLD: return "X86ISD::SHLD";
5966 case X86ISD::SHRD: return "X86ISD::SHRD";
5967 case X86ISD::FAND: return "X86ISD::FAND";
5968 case X86ISD::FOR: return "X86ISD::FOR";
5969 case X86ISD::FXOR: return "X86ISD::FXOR";
5970 case X86ISD::FSRL: return "X86ISD::FSRL";
5971 case X86ISD::FILD: return "X86ISD::FILD";
5972 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5973 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5974 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5975 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5976 case X86ISD::FLD: return "X86ISD::FLD";
5977 case X86ISD::FST: return "X86ISD::FST";
5978 case X86ISD::CALL: return "X86ISD::CALL";
5979 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5980 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5981 case X86ISD::CMP: return "X86ISD::CMP";
5982 case X86ISD::COMI: return "X86ISD::COMI";
5983 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5984 case X86ISD::SETCC: return "X86ISD::SETCC";
5985 case X86ISD::CMOV: return "X86ISD::CMOV";
5986 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5987 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5988 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5989 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5990 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5991 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5992 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5993 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5994 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5995 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5996 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5997 case X86ISD::FMAX: return "X86ISD::FMAX";
5998 case X86ISD::FMIN: return "X86ISD::FMIN";
5999 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6000 case X86ISD::FRCP: return "X86ISD::FRCP";
6001 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6002 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6003 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6004 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6005 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6006 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6007 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6008 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6009 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6010 case X86ISD::VSHL: return "X86ISD::VSHL";
6011 case X86ISD::VSRL: return "X86ISD::VSRL";
6012 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6013 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6014 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6015 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6016 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6017 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6018 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6019 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6020 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6021 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6025 // isLegalAddressingMode - Return true if the addressing mode represented
6026 // by AM is legal for this target, for a load/store of the specified type.
6027 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6028 const Type *Ty) const {
6029 // X86 supports extremely general addressing modes.
6031 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6032 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6036 // We can only fold this if we don't need an extra load.
6037 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6040 // X86-64 only supports addr of globals in small code model.
6041 if (Subtarget->is64Bit()) {
6042 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6044 // If lower 4G is not available, then we must use rip-relative addressing.
6045 if (AM.BaseOffs || AM.Scale > 1)
6056 // These scales always work.
6061 // These scales are formed with basereg+scalereg. Only accept if there is
6066 default: // Other stuff never works.
6074 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6075 if (!Ty1->isInteger() || !Ty2->isInteger())
6077 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6078 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6079 if (NumBits1 <= NumBits2)
6081 return Subtarget->is64Bit() || NumBits1 < 64;
6084 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6085 if (!VT1.isInteger() || !VT2.isInteger())
6087 unsigned NumBits1 = VT1.getSizeInBits();
6088 unsigned NumBits2 = VT2.getSizeInBits();
6089 if (NumBits1 <= NumBits2)
6091 return Subtarget->is64Bit() || NumBits1 < 64;
6094 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6095 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6096 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6097 /// are assumed to be legal.
6099 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6100 // Only do shuffles on 128-bit vector types for now.
6101 if (VT.getSizeInBits() == 64) return false;
6102 return (Mask.Val->getNumOperands() <= 4 ||
6103 isIdentityMask(Mask.Val) ||
6104 isIdentityMask(Mask.Val, true) ||
6105 isSplatMask(Mask.Val) ||
6106 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
6107 X86::isUNPCKLMask(Mask.Val) ||
6108 X86::isUNPCKHMask(Mask.Val) ||
6109 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
6110 X86::isUNPCKH_v_undef_Mask(Mask.Val));
6114 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6115 MVT EVT, SelectionDAG &DAG) const {
6116 unsigned NumElts = BVOps.size();
6117 // Only do shuffles on 128-bit vector types for now.
6118 if (EVT.getSizeInBits() * NumElts == 64) return false;
6119 if (NumElts == 2) return true;
6121 return (isMOVLMask(&BVOps[0], 4) ||
6122 isCommutedMOVL(&BVOps[0], 4, true) ||
6123 isSHUFPMask(&BVOps[0], 4) ||
6124 isCommutedSHUFP(&BVOps[0], 4));
6129 //===----------------------------------------------------------------------===//
6130 // X86 Scheduler Hooks
6131 //===----------------------------------------------------------------------===//
6133 // private utility function
6135 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6136 MachineBasicBlock *MBB,
6140 // For the atomic bitwise operator, we generate
6143 // ld t1 = [bitinstr.addr]
6144 // op t2 = t1, [bitinstr.val]
6146 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6148 // fallthrough -->nextMBB
6149 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6150 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6151 MachineFunction::iterator MBBIter = MBB;
6154 /// First build the CFG
6155 MachineFunction *F = MBB->getParent();
6156 MachineBasicBlock *thisMBB = MBB;
6157 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6158 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6159 F->insert(MBBIter, newMBB);
6160 F->insert(MBBIter, nextMBB);
6162 // Move all successors to thisMBB to nextMBB
6163 nextMBB->transferSuccessors(thisMBB);
6165 // Update thisMBB to fall through to newMBB
6166 thisMBB->addSuccessor(newMBB);
6168 // newMBB jumps to itself and fall through to nextMBB
6169 newMBB->addSuccessor(nextMBB);
6170 newMBB->addSuccessor(newMBB);
6172 // Insert instructions into newMBB based on incoming instruction
6173 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6174 MachineOperand& destOper = bInstr->getOperand(0);
6175 MachineOperand* argOpers[6];
6176 int numArgs = bInstr->getNumOperands() - 1;
6177 for (int i=0; i < numArgs; ++i)
6178 argOpers[i] = &bInstr->getOperand(i+1);
6180 // x86 address has 4 operands: base, index, scale, and displacement
6181 int lastAddrIndx = 3; // [0,3]
6184 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6185 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6186 for (int i=0; i <= lastAddrIndx; ++i)
6187 (*MIB).addOperand(*argOpers[i]);
6189 unsigned tt = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6191 MIB = BuildMI(newMBB, TII->get(X86::NOT32r), tt).addReg(t1);
6196 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6197 assert( (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
6198 && "invalid operand");
6199 if (argOpers[valArgIndx]->isReg())
6200 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6202 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6204 (*MIB).addOperand(*argOpers[valArgIndx]);
6206 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6209 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6210 for (int i=0; i <= lastAddrIndx; ++i)
6211 (*MIB).addOperand(*argOpers[i]);
6213 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6214 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6216 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6217 MIB.addReg(X86::EAX);
6220 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6222 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
6226 // private utility function
6228 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
6229 MachineBasicBlock *MBB,
6231 // For the atomic min/max operator, we generate
6234 // ld t1 = [min/max.addr]
6235 // mov t2 = [min/max.val]
6237 // cmov[cond] t2 = t1
6239 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6241 // fallthrough -->nextMBB
6243 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6244 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6245 MachineFunction::iterator MBBIter = MBB;
6248 /// First build the CFG
6249 MachineFunction *F = MBB->getParent();
6250 MachineBasicBlock *thisMBB = MBB;
6251 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6252 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6253 F->insert(MBBIter, newMBB);
6254 F->insert(MBBIter, nextMBB);
6256 // Move all successors to thisMBB to nextMBB
6257 nextMBB->transferSuccessors(thisMBB);
6259 // Update thisMBB to fall through to newMBB
6260 thisMBB->addSuccessor(newMBB);
6262 // newMBB jumps to newMBB and fall through to nextMBB
6263 newMBB->addSuccessor(nextMBB);
6264 newMBB->addSuccessor(newMBB);
6266 // Insert instructions into newMBB based on incoming instruction
6267 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
6268 MachineOperand& destOper = mInstr->getOperand(0);
6269 MachineOperand* argOpers[6];
6270 int numArgs = mInstr->getNumOperands() - 1;
6271 for (int i=0; i < numArgs; ++i)
6272 argOpers[i] = &mInstr->getOperand(i+1);
6274 // x86 address has 4 operands: base, index, scale, and displacement
6275 int lastAddrIndx = 3; // [0,3]
6278 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6279 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6280 for (int i=0; i <= lastAddrIndx; ++i)
6281 (*MIB).addOperand(*argOpers[i]);
6283 // We only support register and immediate values
6284 assert( (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
6285 && "invalid operand");
6287 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6288 if (argOpers[valArgIndx]->isReg())
6289 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6291 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6292 (*MIB).addOperand(*argOpers[valArgIndx]);
6294 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6297 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
6302 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6303 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
6307 // Cmp and exchange if none has modified the memory location
6308 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6309 for (int i=0; i <= lastAddrIndx; ++i)
6310 (*MIB).addOperand(*argOpers[i]);
6312 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6313 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
6315 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6316 MIB.addReg(X86::EAX);
6319 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6321 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
6327 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6328 MachineBasicBlock *BB) {
6329 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6330 switch (MI->getOpcode()) {
6331 default: assert(false && "Unexpected instr type to insert");
6332 case X86::CMOV_FR32:
6333 case X86::CMOV_FR64:
6334 case X86::CMOV_V4F32:
6335 case X86::CMOV_V2F64:
6336 case X86::CMOV_V2I64: {
6337 // To "insert" a SELECT_CC instruction, we actually have to insert the
6338 // diamond control-flow pattern. The incoming instruction knows the
6339 // destination vreg to set, the condition code register to branch on, the
6340 // true/false values to select between, and a branch opcode to use.
6341 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6342 MachineFunction::iterator It = BB;
6348 // cmpTY ccX, r1, r2
6350 // fallthrough --> copy0MBB
6351 MachineBasicBlock *thisMBB = BB;
6352 MachineFunction *F = BB->getParent();
6353 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6354 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6356 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6357 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6358 F->insert(It, copy0MBB);
6359 F->insert(It, sinkMBB);
6360 // Update machine-CFG edges by transferring all successors of the current
6361 // block to the new block which will contain the Phi node for the select.
6362 sinkMBB->transferSuccessors(BB);
6364 // Add the true and fallthrough blocks as its successors.
6365 BB->addSuccessor(copy0MBB);
6366 BB->addSuccessor(sinkMBB);
6369 // %FalseValue = ...
6370 // # fallthrough to sinkMBB
6373 // Update machine-CFG edges
6374 BB->addSuccessor(sinkMBB);
6377 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6380 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6381 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6382 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6384 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
6388 case X86::FP32_TO_INT16_IN_MEM:
6389 case X86::FP32_TO_INT32_IN_MEM:
6390 case X86::FP32_TO_INT64_IN_MEM:
6391 case X86::FP64_TO_INT16_IN_MEM:
6392 case X86::FP64_TO_INT32_IN_MEM:
6393 case X86::FP64_TO_INT64_IN_MEM:
6394 case X86::FP80_TO_INT16_IN_MEM:
6395 case X86::FP80_TO_INT32_IN_MEM:
6396 case X86::FP80_TO_INT64_IN_MEM: {
6397 // Change the floating point control register to use "round towards zero"
6398 // mode when truncating to an integer value.
6399 MachineFunction *F = BB->getParent();
6400 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6401 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6403 // Load the old value of the high byte of the control word...
6405 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6406 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6408 // Set the high part to be round to zero...
6409 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6412 // Reload the modified control word now...
6413 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6415 // Restore the memory image of control word to original value
6416 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6419 // Get the X86 opcode to use.
6421 switch (MI->getOpcode()) {
6422 default: assert(0 && "illegal opcode!");
6423 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6424 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6425 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6426 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6427 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6428 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6429 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6430 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6431 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6435 MachineOperand &Op = MI->getOperand(0);
6436 if (Op.isRegister()) {
6437 AM.BaseType = X86AddressMode::RegBase;
6438 AM.Base.Reg = Op.getReg();
6440 AM.BaseType = X86AddressMode::FrameIndexBase;
6441 AM.Base.FrameIndex = Op.getIndex();
6443 Op = MI->getOperand(1);
6444 if (Op.isImmediate())
6445 AM.Scale = Op.getImm();
6446 Op = MI->getOperand(2);
6447 if (Op.isImmediate())
6448 AM.IndexReg = Op.getImm();
6449 Op = MI->getOperand(3);
6450 if (Op.isGlobalAddress()) {
6451 AM.GV = Op.getGlobal();
6453 AM.Disp = Op.getImm();
6455 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6456 .addReg(MI->getOperand(4).getReg());
6458 // Reload the original control word now.
6459 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6461 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
6464 case X86::ATOMAND32:
6465 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6468 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
6470 case X86::ATOMXOR32:
6471 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
6473 case X86::ATOMNAND32:
6474 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6475 X86::AND32ri, true);
6476 case X86::ATOMMIN32:
6477 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
6478 case X86::ATOMMAX32:
6479 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
6480 case X86::ATOMUMIN32:
6481 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
6482 case X86::ATOMUMAX32:
6483 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
6487 //===----------------------------------------------------------------------===//
6488 // X86 Optimization Hooks
6489 //===----------------------------------------------------------------------===//
6491 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6495 const SelectionDAG &DAG,
6496 unsigned Depth) const {
6497 unsigned Opc = Op.getOpcode();
6498 assert((Opc >= ISD::BUILTIN_OP_END ||
6499 Opc == ISD::INTRINSIC_WO_CHAIN ||
6500 Opc == ISD::INTRINSIC_W_CHAIN ||
6501 Opc == ISD::INTRINSIC_VOID) &&
6502 "Should use MaskedValueIsZero if you don't know whether Op"
6503 " is a target node!");
6505 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
6509 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
6510 Mask.getBitWidth() - 1);
6515 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
6516 /// node is a GlobalAddress + offset.
6517 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
6518 GlobalValue* &GA, int64_t &Offset) const{
6519 if (N->getOpcode() == X86ISD::Wrapper) {
6520 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
6521 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
6525 return TargetLowering::isGAPlusOffset(N, GA, Offset);
6528 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
6529 const TargetLowering &TLI) {
6532 if (TLI.isGAPlusOffset(Base, GV, Offset))
6533 return (GV->getAlignment() >= N && (Offset % N) == 0);
6534 // DAG combine handles the stack object case.
6538 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
6539 unsigned NumElems, MVT EVT,
6541 SelectionDAG &DAG, MachineFrameInfo *MFI,
6542 const TargetLowering &TLI) {
6544 for (unsigned i = 0; i < NumElems; ++i) {
6545 SDValue Idx = PermMask.getOperand(i);
6546 if (Idx.getOpcode() == ISD::UNDEF) {
6552 SDValue Elt = DAG.getShuffleScalarElt(N, i);
6554 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.Val)))
6558 if (Base->getOpcode() == ISD::UNDEF)
6562 if (Elt.getOpcode() == ISD::UNDEF)
6565 if (!TLI.isConsecutiveLoad(Elt.Val, Base,
6566 EVT.getSizeInBits()/8, i, MFI))
6572 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6573 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6574 /// if the load addresses are consecutive, non-overlapping, and in the right
6576 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6577 const TargetLowering &TLI) {
6578 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6579 MVT VT = N->getValueType(0);
6580 MVT EVT = VT.getVectorElementType();
6581 SDValue PermMask = N->getOperand(2);
6582 unsigned NumElems = PermMask.getNumOperands();
6583 SDNode *Base = NULL;
6584 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
6588 LoadSDNode *LD = cast<LoadSDNode>(Base);
6589 if (isBaseAlignmentOfN(16, Base->getOperand(1).Val, TLI))
6590 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6591 LD->getSrcValueOffset(), LD->isVolatile());
6592 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6593 LD->getSrcValueOffset(), LD->isVolatile(),
6594 LD->getAlignment());
6597 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
6598 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
6599 const X86Subtarget *Subtarget,
6600 const TargetLowering &TLI) {
6601 unsigned NumOps = N->getNumOperands();
6603 // Ignore single operand BUILD_VECTOR.
6607 MVT VT = N->getValueType(0);
6608 MVT EVT = VT.getVectorElementType();
6609 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
6610 // We are looking for load i64 and zero extend. We want to transform
6611 // it before legalizer has a chance to expand it. Also look for i64
6612 // BUILD_PAIR bit casted to f64.
6614 // This must be an insertion into a zero vector.
6615 SDValue HighElt = N->getOperand(1);
6616 if (!isZeroNode(HighElt))
6619 // Value must be a load.
6620 SDNode *Base = N->getOperand(0).Val;
6621 if (!isa<LoadSDNode>(Base)) {
6622 if (Base->getOpcode() != ISD::BIT_CONVERT)
6624 Base = Base->getOperand(0).Val;
6625 if (!isa<LoadSDNode>(Base))
6629 // Transform it into VZEXT_LOAD addr.
6630 LoadSDNode *LD = cast<LoadSDNode>(Base);
6632 // Load must not be an extload.
6633 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
6636 return DAG.getNode(X86ISD::VZEXT_LOAD, VT, LD->getChain(), LD->getBasePtr());
6639 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6640 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6641 const X86Subtarget *Subtarget) {
6642 SDValue Cond = N->getOperand(0);
6644 // If we have SSE[12] support, try to form min/max nodes.
6645 if (Subtarget->hasSSE2() &&
6646 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6647 if (Cond.getOpcode() == ISD::SETCC) {
6648 // Get the LHS/RHS of the select.
6649 SDValue LHS = N->getOperand(1);
6650 SDValue RHS = N->getOperand(2);
6651 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6653 unsigned Opcode = 0;
6654 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6657 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6660 if (!UnsafeFPMath) break;
6662 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6664 Opcode = X86ISD::FMIN;
6667 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6670 if (!UnsafeFPMath) break;
6672 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6674 Opcode = X86ISD::FMAX;
6677 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6680 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6683 if (!UnsafeFPMath) break;
6685 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6687 Opcode = X86ISD::FMIN;
6690 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6693 if (!UnsafeFPMath) break;
6695 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6697 Opcode = X86ISD::FMAX;
6703 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6711 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6712 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
6713 const X86Subtarget *Subtarget) {
6714 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
6715 // the FP state in cases where an emms may be missing.
6716 // A preferable solution to the general problem is to figure out the right
6717 // places to insert EMMS. This qualifies as a quick hack.
6718 StoreSDNode *St = cast<StoreSDNode>(N);
6719 if (St->getValue().getValueType().isVector() &&
6720 St->getValue().getValueType().getSizeInBits() == 64 &&
6721 isa<LoadSDNode>(St->getValue()) &&
6722 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6723 St->getChain().hasOneUse() && !St->isVolatile()) {
6724 SDNode* LdVal = St->getValue().Val;
6726 int TokenFactorIndex = -1;
6727 SmallVector<SDValue, 8> Ops;
6728 SDNode* ChainVal = St->getChain().Val;
6729 // Must be a store of a load. We currently handle two cases: the load
6730 // is a direct child, and it's under an intervening TokenFactor. It is
6731 // possible to dig deeper under nested TokenFactors.
6732 if (ChainVal == LdVal)
6733 Ld = cast<LoadSDNode>(St->getChain());
6734 else if (St->getValue().hasOneUse() &&
6735 ChainVal->getOpcode() == ISD::TokenFactor) {
6736 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6737 if (ChainVal->getOperand(i).Val == LdVal) {
6738 TokenFactorIndex = i;
6739 Ld = cast<LoadSDNode>(St->getValue());
6741 Ops.push_back(ChainVal->getOperand(i));
6745 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6746 if (Subtarget->is64Bit()) {
6747 SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6748 Ld->getBasePtr(), Ld->getSrcValue(),
6749 Ld->getSrcValueOffset(), Ld->isVolatile(),
6750 Ld->getAlignment());
6751 SDValue NewChain = NewLd.getValue(1);
6752 if (TokenFactorIndex != -1) {
6753 Ops.push_back(NewChain);
6754 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6757 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6758 St->getSrcValue(), St->getSrcValueOffset(),
6759 St->isVolatile(), St->getAlignment());
6762 // Otherwise, lower to two 32-bit copies.
6763 SDValue LoAddr = Ld->getBasePtr();
6764 SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6765 DAG.getConstant(4, MVT::i32));
6767 SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6768 Ld->getSrcValue(), Ld->getSrcValueOffset(),
6769 Ld->isVolatile(), Ld->getAlignment());
6770 SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6771 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6773 MinAlign(Ld->getAlignment(), 4));
6775 SDValue NewChain = LoLd.getValue(1);
6776 if (TokenFactorIndex != -1) {
6777 Ops.push_back(LoLd);
6778 Ops.push_back(HiLd);
6779 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6783 LoAddr = St->getBasePtr();
6784 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6785 DAG.getConstant(4, MVT::i32));
6787 SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6788 St->getSrcValue(), St->getSrcValueOffset(),
6789 St->isVolatile(), St->getAlignment());
6790 SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6791 St->getSrcValue(), St->getSrcValueOffset()+4,
6793 MinAlign(St->getAlignment(), 4));
6794 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6800 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6801 /// X86ISD::FXOR nodes.
6802 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6803 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6804 // F[X]OR(0.0, x) -> x
6805 // F[X]OR(x, 0.0) -> x
6806 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6807 if (C->getValueAPF().isPosZero())
6808 return N->getOperand(1);
6809 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6810 if (C->getValueAPF().isPosZero())
6811 return N->getOperand(0);
6815 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6816 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6817 // FAND(0.0, x) -> 0.0
6818 // FAND(x, 0.0) -> 0.0
6819 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6820 if (C->getValueAPF().isPosZero())
6821 return N->getOperand(0);
6822 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6823 if (C->getValueAPF().isPosZero())
6824 return N->getOperand(1);
6829 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
6830 DAGCombinerInfo &DCI) const {
6831 SelectionDAG &DAG = DCI.DAG;
6832 switch (N->getOpcode()) {
6834 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
6835 case ISD::BUILD_VECTOR:
6836 return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
6837 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6838 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
6840 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6841 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6847 //===----------------------------------------------------------------------===//
6848 // X86 Inline Assembly Support
6849 //===----------------------------------------------------------------------===//
6851 /// getConstraintType - Given a constraint letter, return the type of
6852 /// constraint it is for this target.
6853 X86TargetLowering::ConstraintType
6854 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6855 if (Constraint.size() == 1) {
6856 switch (Constraint[0]) {
6867 return C_RegisterClass;
6872 return TargetLowering::getConstraintType(Constraint);
6875 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6876 /// with another that has more specific requirements based on the type of the
6877 /// corresponding operand.
6878 const char *X86TargetLowering::
6879 LowerXConstraint(MVT ConstraintVT) const {
6880 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
6881 // 'f' like normal targets.
6882 if (ConstraintVT.isFloatingPoint()) {
6883 if (Subtarget->hasSSE2())
6885 if (Subtarget->hasSSE1())
6889 return TargetLowering::LowerXConstraint(ConstraintVT);
6892 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6893 /// vector. If it is invalid, don't add anything to Ops.
6894 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
6896 std::vector<SDValue>&Ops,
6897 SelectionDAG &DAG) const {
6898 SDValue Result(0, 0);
6900 switch (Constraint) {
6903 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6904 if (C->getValue() <= 31) {
6905 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6911 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6912 if (C->getValue() <= 255) {
6913 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6919 // Literal immediates are always ok.
6920 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6921 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6925 // If we are in non-pic codegen mode, we allow the address of a global (with
6926 // an optional displacement) to be used with 'i'.
6927 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6930 // Match either (GA) or (GA+C)
6932 Offset = GA->getOffset();
6933 } else if (Op.getOpcode() == ISD::ADD) {
6934 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6935 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6937 Offset = GA->getOffset()+C->getValue();
6939 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6940 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6942 Offset = GA->getOffset()+C->getValue();
6949 // If addressing this global requires a load (e.g. in PIC mode), we can't
6951 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6955 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6961 // Otherwise, not valid for this mode.
6967 Ops.push_back(Result);
6970 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6973 std::vector<unsigned> X86TargetLowering::
6974 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6976 if (Constraint.size() == 1) {
6977 // FIXME: not handling fp-stack yet!
6978 switch (Constraint[0]) { // GCC X86 Constraint Letters
6979 default: break; // Unknown constraint letter
6980 case 'A': // EAX/EDX
6981 if (VT == MVT::i32 || VT == MVT::i64)
6982 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6984 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6987 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6988 else if (VT == MVT::i16)
6989 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6990 else if (VT == MVT::i8)
6991 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6992 else if (VT == MVT::i64)
6993 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6998 return std::vector<unsigned>();
7001 std::pair<unsigned, const TargetRegisterClass*>
7002 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7004 // First, see if this is a constraint that directly corresponds to an LLVM
7006 if (Constraint.size() == 1) {
7007 // GCC Constraint Letters
7008 switch (Constraint[0]) {
7010 case 'r': // GENERAL_REGS
7011 case 'R': // LEGACY_REGS
7012 case 'l': // INDEX_REGS
7013 if (VT == MVT::i64 && Subtarget->is64Bit())
7014 return std::make_pair(0U, X86::GR64RegisterClass);
7016 return std::make_pair(0U, X86::GR32RegisterClass);
7017 else if (VT == MVT::i16)
7018 return std::make_pair(0U, X86::GR16RegisterClass);
7019 else if (VT == MVT::i8)
7020 return std::make_pair(0U, X86::GR8RegisterClass);
7022 case 'f': // FP Stack registers.
7023 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
7024 // value to the correct fpstack register class.
7025 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
7026 return std::make_pair(0U, X86::RFP32RegisterClass);
7027 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
7028 return std::make_pair(0U, X86::RFP64RegisterClass);
7029 return std::make_pair(0U, X86::RFP80RegisterClass);
7030 case 'y': // MMX_REGS if MMX allowed.
7031 if (!Subtarget->hasMMX()) break;
7032 return std::make_pair(0U, X86::VR64RegisterClass);
7034 case 'Y': // SSE_REGS if SSE2 allowed
7035 if (!Subtarget->hasSSE2()) break;
7037 case 'x': // SSE_REGS if SSE1 allowed
7038 if (!Subtarget->hasSSE1()) break;
7040 switch (VT.getSimpleVT()) {
7042 // Scalar SSE types.
7045 return std::make_pair(0U, X86::FR32RegisterClass);
7048 return std::make_pair(0U, X86::FR64RegisterClass);
7056 return std::make_pair(0U, X86::VR128RegisterClass);
7062 // Use the default implementation in TargetLowering to convert the register
7063 // constraint into a member of a register class.
7064 std::pair<unsigned, const TargetRegisterClass*> Res;
7065 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7067 // Not found as a standard register?
7068 if (Res.second == 0) {
7069 // GCC calls "st(0)" just plain "st".
7070 if (StringsEqualNoCase("{st}", Constraint)) {
7071 Res.first = X86::ST0;
7072 Res.second = X86::RFP80RegisterClass;
7078 // Otherwise, check to see if this is a register class of the wrong value
7079 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
7080 // turn into {ax},{dx}.
7081 if (Res.second->hasType(VT))
7082 return Res; // Correct type already, nothing to do.
7084 // All of the single-register GCC register classes map their values onto
7085 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
7086 // really want an 8-bit or 32-bit register, map to the appropriate register
7087 // class and return the appropriate register.
7088 if (Res.second != X86::GR16RegisterClass)
7091 if (VT == MVT::i8) {
7092 unsigned DestReg = 0;
7093 switch (Res.first) {
7095 case X86::AX: DestReg = X86::AL; break;
7096 case X86::DX: DestReg = X86::DL; break;
7097 case X86::CX: DestReg = X86::CL; break;
7098 case X86::BX: DestReg = X86::BL; break;
7101 Res.first = DestReg;
7102 Res.second = Res.second = X86::GR8RegisterClass;
7104 } else if (VT == MVT::i32) {
7105 unsigned DestReg = 0;
7106 switch (Res.first) {
7108 case X86::AX: DestReg = X86::EAX; break;
7109 case X86::DX: DestReg = X86::EDX; break;
7110 case X86::CX: DestReg = X86::ECX; break;
7111 case X86::BX: DestReg = X86::EBX; break;
7112 case X86::SI: DestReg = X86::ESI; break;
7113 case X86::DI: DestReg = X86::EDI; break;
7114 case X86::BP: DestReg = X86::EBP; break;
7115 case X86::SP: DestReg = X86::ESP; break;
7118 Res.first = DestReg;
7119 Res.second = Res.second = X86::GR32RegisterClass;
7121 } else if (VT == MVT::i64) {
7122 unsigned DestReg = 0;
7123 switch (Res.first) {
7125 case X86::AX: DestReg = X86::RAX; break;
7126 case X86::DX: DestReg = X86::RDX; break;
7127 case X86::CX: DestReg = X86::RCX; break;
7128 case X86::BX: DestReg = X86::RBX; break;
7129 case X86::SI: DestReg = X86::RSI; break;
7130 case X86::DI: DestReg = X86::RDI; break;
7131 case X86::BP: DestReg = X86::RBP; break;
7132 case X86::SP: DestReg = X86::RSP; break;
7135 Res.first = DestReg;
7136 Res.second = Res.second = X86::GR64RegisterClass;