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"
41 #include "llvm/Support/CommandLine.h"
45 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
47 // Forward declarations.
48 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
50 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
51 : TargetLowering(TM) {
52 Subtarget = &TM.getSubtarget<X86Subtarget>();
53 X86ScalarSSEf64 = Subtarget->hasSSE2();
54 X86ScalarSSEf32 = Subtarget->hasSSE1();
55 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
59 RegInfo = TM.getRegisterInfo();
62 // Set up the TargetLowering object.
64 // X86 is weird, it always uses i8 for shift amounts and setcc results.
65 setShiftAmountType(MVT::i8);
66 setBooleanContents(ZeroOrOneBooleanContent);
67 setSchedulingPreference(SchedulingForRegPressure);
68 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
69 setStackPointerRegisterToSaveRestore(X86StackPtr);
71 if (Subtarget->isTargetDarwin()) {
72 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
73 setUseUnderscoreSetJmp(false);
74 setUseUnderscoreLongJmp(false);
75 } else if (Subtarget->isTargetMingw()) {
76 // MS runtime is weird: it exports _setjmp, but longjmp!
77 setUseUnderscoreSetJmp(true);
78 setUseUnderscoreLongJmp(false);
80 setUseUnderscoreSetJmp(true);
81 setUseUnderscoreLongJmp(true);
84 // Set up the register classes.
85 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
86 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
87 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
88 if (Subtarget->is64Bit())
89 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
91 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93 // We don't accept any truncstore of integer registers.
94 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
95 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
96 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
97 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
98 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
99 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
101 // SETOEQ and SETUNE require checking two conditions.
102 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
103 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
104 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
105 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
106 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
107 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
109 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
111 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
112 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
115 if (Subtarget->is64Bit()) {
116 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
117 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
119 if (X86ScalarSSEf64) {
120 // We have an impenetrably clever algorithm for ui64->double only.
121 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
123 // We have faster algorithm for ui32->single only.
124 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
126 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
129 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
131 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
132 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
133 // SSE has no i16 to fp conversion, only i32
134 if (X86ScalarSSEf32) {
135 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
136 // f32 and f64 cases are Legal, f80 case is not
137 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
139 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
140 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
143 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
144 // are Legal, f80 is custom lowered.
145 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
146 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
148 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
150 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
151 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
153 if (X86ScalarSSEf32) {
154 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
155 // f32 and f64 cases are Legal, f80 case is not
156 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
158 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
159 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
162 // Handle FP_TO_UINT by promoting the destination to a larger signed
164 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
165 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
166 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
168 if (Subtarget->is64Bit()) {
169 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
170 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
172 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
173 // Expand FP_TO_UINT into a select.
174 // FIXME: We would like to use a Custom expander here eventually to do
175 // the optimal thing for SSE vs. the default expansion in the legalizer.
176 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
178 // With SSE3 we can use fisttpll to convert to a signed i64.
179 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
182 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
183 if (!X86ScalarSSEf64) {
184 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
185 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
188 // Scalar integer divide and remainder are lowered to use operations that
189 // produce two results, to match the available instructions. This exposes
190 // the two-result form to trivial CSE, which is able to combine x/y and x%y
191 // into a single instruction.
193 // Scalar integer multiply-high is also lowered to use two-result
194 // operations, to match the available instructions. However, plain multiply
195 // (low) operations are left as Legal, as there are single-result
196 // instructions for this in x86. Using the two-result multiply instructions
197 // when both high and low results are needed must be arranged by dagcombine.
198 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
199 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
200 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
201 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
202 setOperationAction(ISD::SREM , MVT::i8 , Expand);
203 setOperationAction(ISD::UREM , MVT::i8 , Expand);
204 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
205 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
206 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
207 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
208 setOperationAction(ISD::SREM , MVT::i16 , Expand);
209 setOperationAction(ISD::UREM , MVT::i16 , Expand);
210 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
211 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
212 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
213 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
214 setOperationAction(ISD::SREM , MVT::i32 , Expand);
215 setOperationAction(ISD::UREM , MVT::i32 , Expand);
216 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
217 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
218 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
219 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
220 setOperationAction(ISD::SREM , MVT::i64 , Expand);
221 setOperationAction(ISD::UREM , MVT::i64 , Expand);
223 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
224 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
225 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
226 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
227 if (Subtarget->is64Bit())
228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
232 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
233 setOperationAction(ISD::FREM , MVT::f32 , Expand);
234 setOperationAction(ISD::FREM , MVT::f64 , Expand);
235 setOperationAction(ISD::FREM , MVT::f80 , Expand);
236 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
238 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
239 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
240 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
241 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
242 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
243 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
244 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
245 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
246 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
247 if (Subtarget->is64Bit()) {
248 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
249 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
250 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
253 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
254 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
256 // These should be promoted to a larger select which is supported.
257 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
258 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
259 // X86 wants to expand cmov itself.
260 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
261 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
262 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
263 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
264 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
265 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
266 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
267 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
268 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
269 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
270 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
271 if (Subtarget->is64Bit()) {
272 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
273 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
275 // X86 ret instruction may pop stack.
276 setOperationAction(ISD::RET , MVT::Other, Custom);
277 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
280 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
281 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
282 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
283 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
284 if (Subtarget->is64Bit())
285 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
286 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
287 if (Subtarget->is64Bit()) {
288 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
289 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
290 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
291 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
293 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
294 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
295 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
296 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
297 if (Subtarget->is64Bit()) {
298 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
299 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
300 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
303 if (Subtarget->hasSSE1())
304 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
306 if (!Subtarget->hasSSE2())
307 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
309 // Expand certain atomics
310 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
311 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
312 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
313 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
315 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
316 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
317 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
318 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
320 if (!Subtarget->is64Bit()) {
321 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
322 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
323 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
324 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
325 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
326 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
327 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
330 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
331 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
332 // FIXME - use subtarget debug flags
333 if (!Subtarget->isTargetDarwin() &&
334 !Subtarget->isTargetELF() &&
335 !Subtarget->isTargetCygMing()) {
336 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
337 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
340 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
341 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
342 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
343 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
344 if (Subtarget->is64Bit()) {
345 setExceptionPointerRegister(X86::RAX);
346 setExceptionSelectorRegister(X86::RDX);
348 setExceptionPointerRegister(X86::EAX);
349 setExceptionSelectorRegister(X86::EDX);
351 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
352 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
354 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
356 setOperationAction(ISD::TRAP, MVT::Other, Legal);
358 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
359 setOperationAction(ISD::VASTART , MVT::Other, Custom);
360 setOperationAction(ISD::VAEND , MVT::Other, Expand);
361 if (Subtarget->is64Bit()) {
362 setOperationAction(ISD::VAARG , MVT::Other, Custom);
363 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
365 setOperationAction(ISD::VAARG , MVT::Other, Expand);
366 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
369 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
370 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
371 if (Subtarget->is64Bit())
372 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
373 if (Subtarget->isTargetCygMing())
374 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
376 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
378 if (X86ScalarSSEf64) {
379 // f32 and f64 use SSE.
380 // Set up the FP register classes.
381 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
382 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
384 // Use ANDPD to simulate FABS.
385 setOperationAction(ISD::FABS , MVT::f64, Custom);
386 setOperationAction(ISD::FABS , MVT::f32, Custom);
388 // Use XORP to simulate FNEG.
389 setOperationAction(ISD::FNEG , MVT::f64, Custom);
390 setOperationAction(ISD::FNEG , MVT::f32, Custom);
392 // Use ANDPD and ORPD to simulate FCOPYSIGN.
393 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
394 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
396 // We don't support sin/cos/fmod
397 setOperationAction(ISD::FSIN , MVT::f64, Expand);
398 setOperationAction(ISD::FCOS , MVT::f64, Expand);
399 setOperationAction(ISD::FSIN , MVT::f32, Expand);
400 setOperationAction(ISD::FCOS , MVT::f32, Expand);
402 // Expand FP immediates into loads from the stack, except for the special
404 addLegalFPImmediate(APFloat(+0.0)); // xorpd
405 addLegalFPImmediate(APFloat(+0.0f)); // xorps
407 // Floating truncations from f80 and extensions to f80 go through memory.
408 // If optimizing, we lie about this though and handle it in
409 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
411 setConvertAction(MVT::f32, MVT::f80, Expand);
412 setConvertAction(MVT::f64, MVT::f80, Expand);
413 setConvertAction(MVT::f80, MVT::f32, Expand);
414 setConvertAction(MVT::f80, MVT::f64, Expand);
416 } else if (X86ScalarSSEf32) {
417 // Use SSE for f32, x87 for f64.
418 // Set up the FP register classes.
419 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
420 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
422 // Use ANDPS to simulate FABS.
423 setOperationAction(ISD::FABS , MVT::f32, Custom);
425 // Use XORP to simulate FNEG.
426 setOperationAction(ISD::FNEG , MVT::f32, Custom);
428 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
430 // Use ANDPS and ORPS to simulate FCOPYSIGN.
431 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
432 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
434 // We don't support sin/cos/fmod
435 setOperationAction(ISD::FSIN , MVT::f32, Expand);
436 setOperationAction(ISD::FCOS , MVT::f32, Expand);
438 // Special cases we handle for FP constants.
439 addLegalFPImmediate(APFloat(+0.0f)); // xorps
440 addLegalFPImmediate(APFloat(+0.0)); // FLD0
441 addLegalFPImmediate(APFloat(+1.0)); // FLD1
442 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
443 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
445 // SSE <-> X87 conversions 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::f32, MVT::f64, Expand);
450 setConvertAction(MVT::f32, MVT::f80, Expand);
451 setConvertAction(MVT::f80, MVT::f32, Expand);
452 setConvertAction(MVT::f64, MVT::f32, Expand);
453 // And x87->x87 truncations also.
454 setConvertAction(MVT::f80, MVT::f64, Expand);
458 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
459 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
462 // f32 and f64 in x87.
463 // Set up the FP register classes.
464 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
465 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
467 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
468 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
469 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
470 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
472 // Floating truncations go through memory. If optimizing, we lie about
473 // this though and handle it in InstructionSelectPreprocess so that
474 // dagcombine2 can hack on these.
476 setConvertAction(MVT::f80, MVT::f32, Expand);
477 setConvertAction(MVT::f64, MVT::f32, Expand);
478 setConvertAction(MVT::f80, MVT::f64, Expand);
482 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
483 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
485 addLegalFPImmediate(APFloat(+0.0)); // FLD0
486 addLegalFPImmediate(APFloat(+1.0)); // FLD1
487 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
488 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
489 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
490 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
491 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
492 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
495 // Long double always uses X87.
496 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
497 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
498 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
501 APFloat TmpFlt(+0.0);
502 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
504 addLegalFPImmediate(TmpFlt); // FLD0
506 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
507 APFloat TmpFlt2(+1.0);
508 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
510 addLegalFPImmediate(TmpFlt2); // FLD1
511 TmpFlt2.changeSign();
512 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
516 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
517 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
520 // Always use a library call for pow.
521 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
522 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
523 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
525 setOperationAction(ISD::FLOG, MVT::f80, Expand);
526 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
527 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
528 setOperationAction(ISD::FEXP, MVT::f80, Expand);
529 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
531 // First set operation action for all vector types to either promote
532 // (for widening) or expand (for scalarization). Then we will selectively
533 // turn on ones that can be effectively codegen'd.
534 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
535 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
536 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
551 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
581 if (!DisableMMX && Subtarget->hasMMX()) {
582 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
583 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
584 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
585 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
586 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
588 // FIXME: add MMX packed arithmetics
590 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
591 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
592 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
593 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
595 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
596 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
597 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
598 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
600 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
601 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
603 setOperationAction(ISD::AND, MVT::v8i8, Promote);
604 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
605 setOperationAction(ISD::AND, MVT::v4i16, Promote);
606 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
607 setOperationAction(ISD::AND, MVT::v2i32, Promote);
608 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
609 setOperationAction(ISD::AND, MVT::v1i64, Legal);
611 setOperationAction(ISD::OR, MVT::v8i8, Promote);
612 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
613 setOperationAction(ISD::OR, MVT::v4i16, Promote);
614 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
615 setOperationAction(ISD::OR, MVT::v2i32, Promote);
616 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
617 setOperationAction(ISD::OR, MVT::v1i64, Legal);
619 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
620 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
621 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
622 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
623 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
624 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
625 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
627 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
628 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
629 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
630 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
631 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
632 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
633 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
634 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
635 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
637 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
638 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
639 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
640 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
641 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
643 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
644 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
645 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
646 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
648 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
649 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
650 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
651 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
653 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
655 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
656 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
657 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
658 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
659 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
660 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
663 if (Subtarget->hasSSE1()) {
664 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
666 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
667 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
668 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
669 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
670 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
671 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
672 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
673 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
674 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
675 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
676 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
677 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
680 if (Subtarget->hasSSE2()) {
681 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
682 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
683 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
684 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
685 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
687 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
688 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
689 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
690 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
691 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
692 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
693 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
694 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
695 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
696 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
697 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
698 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
699 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
700 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
701 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
702 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
704 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
705 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
706 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
707 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
709 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
710 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
711 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
712 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
713 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
715 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
716 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
717 MVT VT = (MVT::SimpleValueType)i;
718 // Do not attempt to custom lower non-power-of-2 vectors
719 if (!isPowerOf2_32(VT.getVectorNumElements()))
721 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
722 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
723 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
725 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
726 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
727 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
728 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
729 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
730 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
731 if (Subtarget->is64Bit()) {
732 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
733 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
736 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
737 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
738 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
739 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
740 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
741 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
742 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
743 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
744 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
745 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
746 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
747 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
750 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
752 // Custom lower v2i64 and v2f64 selects.
753 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
754 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
755 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
756 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
760 if (Subtarget->hasSSE41()) {
761 // FIXME: Do we need to handle scalar-to-vector here?
762 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
764 // i8 and i16 vectors are custom , because the source register and source
765 // source memory operand types are not the same width. f32 vectors are
766 // custom since the immediate controlling the insert encodes additional
768 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
769 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
770 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
771 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
773 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
774 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
775 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
776 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
778 if (Subtarget->is64Bit()) {
779 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
780 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
784 if (Subtarget->hasSSE42()) {
785 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
788 // We want to custom lower some of our intrinsics.
789 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
791 // Add/Sub/Mul with overflow operations are custom lowered.
792 setOperationAction(ISD::SADDO, MVT::i32, Custom);
793 setOperationAction(ISD::SADDO, MVT::i64, Custom);
794 setOperationAction(ISD::UADDO, MVT::i32, Custom);
795 setOperationAction(ISD::UADDO, MVT::i64, Custom);
796 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
797 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
798 setOperationAction(ISD::USUBO, MVT::i32, Custom);
799 setOperationAction(ISD::USUBO, MVT::i64, Custom);
800 setOperationAction(ISD::SMULO, MVT::i32, Custom);
801 setOperationAction(ISD::SMULO, MVT::i64, Custom);
802 setOperationAction(ISD::UMULO, MVT::i32, Custom);
803 setOperationAction(ISD::UMULO, MVT::i64, Custom);
805 // We have target-specific dag combine patterns for the following nodes:
806 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
807 setTargetDAGCombine(ISD::BUILD_VECTOR);
808 setTargetDAGCombine(ISD::SELECT);
809 setTargetDAGCombine(ISD::SHL);
810 setTargetDAGCombine(ISD::SRA);
811 setTargetDAGCombine(ISD::SRL);
812 setTargetDAGCombine(ISD::STORE);
814 computeRegisterProperties();
816 // FIXME: These should be based on subtarget info. Plus, the values should
817 // be smaller when we are in optimizing for size mode.
818 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
819 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
820 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
821 allowUnalignedMemoryAccesses = true; // x86 supports it!
822 setPrefLoopAlignment(16);
826 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
831 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
832 /// the desired ByVal argument alignment.
833 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
836 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
837 if (VTy->getBitWidth() == 128)
839 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
840 unsigned EltAlign = 0;
841 getMaxByValAlign(ATy->getElementType(), EltAlign);
842 if (EltAlign > MaxAlign)
844 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
845 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
846 unsigned EltAlign = 0;
847 getMaxByValAlign(STy->getElementType(i), EltAlign);
848 if (EltAlign > MaxAlign)
857 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
858 /// function arguments in the caller parameter area. For X86, aggregates
859 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
860 /// are at 4-byte boundaries.
861 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
862 if (Subtarget->is64Bit()) {
863 // Max of 8 and alignment of type.
864 unsigned TyAlign = TD->getABITypeAlignment(Ty);
871 if (Subtarget->hasSSE1())
872 getMaxByValAlign(Ty, Align);
876 /// getOptimalMemOpType - Returns the target specific optimal type for load
877 /// and store operations as a result of memset, memcpy, and memmove
878 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
881 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
882 bool isSrcConst, bool isSrcStr) const {
883 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
884 // linux. This is because the stack realignment code can't handle certain
885 // cases like PR2962. This should be removed when PR2962 is fixed.
886 if (Subtarget->getStackAlignment() >= 16) {
887 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
889 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
892 if (Subtarget->is64Bit() && Size >= 8)
898 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
900 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
901 SelectionDAG &DAG) const {
902 if (usesGlobalOffsetTable())
903 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
904 if (!Subtarget->isPICStyleRIPRel())
905 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
909 //===----------------------------------------------------------------------===//
910 // Return Value Calling Convention Implementation
911 //===----------------------------------------------------------------------===//
913 #include "X86GenCallingConv.inc"
915 /// LowerRET - Lower an ISD::RET node.
916 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
917 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
919 SmallVector<CCValAssign, 16> RVLocs;
920 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
921 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
922 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
923 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
925 // If this is the first return lowered for this function, add the regs to the
926 // liveout set for the function.
927 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
928 for (unsigned i = 0; i != RVLocs.size(); ++i)
929 if (RVLocs[i].isRegLoc())
930 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
932 SDValue Chain = Op.getOperand(0);
934 // Handle tail call return.
935 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
936 if (Chain.getOpcode() == X86ISD::TAILCALL) {
937 SDValue TailCall = Chain;
938 SDValue TargetAddress = TailCall.getOperand(1);
939 SDValue StackAdjustment = TailCall.getOperand(2);
940 assert(((TargetAddress.getOpcode() == ISD::Register &&
941 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
942 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
943 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
944 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
945 "Expecting an global address, external symbol, or register");
946 assert(StackAdjustment.getOpcode() == ISD::Constant &&
947 "Expecting a const value");
949 SmallVector<SDValue,8> Operands;
950 Operands.push_back(Chain.getOperand(0));
951 Operands.push_back(TargetAddress);
952 Operands.push_back(StackAdjustment);
953 // Copy registers used by the call. Last operand is a flag so it is not
955 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
956 Operands.push_back(Chain.getOperand(i));
958 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
965 SmallVector<SDValue, 6> RetOps;
966 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
967 // Operand #1 = Bytes To Pop
968 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
970 // Copy the result values into the output registers.
971 for (unsigned i = 0; i != RVLocs.size(); ++i) {
972 CCValAssign &VA = RVLocs[i];
973 assert(VA.isRegLoc() && "Can only return in registers!");
974 SDValue ValToCopy = Op.getOperand(i*2+1);
976 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
977 // the RET instruction and handled by the FP Stackifier.
978 if (RVLocs[i].getLocReg() == X86::ST0 ||
979 RVLocs[i].getLocReg() == X86::ST1) {
980 // If this is a copy from an xmm register to ST(0), use an FPExtend to
981 // change the value to the FP stack register class.
982 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
983 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
984 RetOps.push_back(ValToCopy);
985 // Don't emit a copytoreg.
989 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
990 Flag = Chain.getValue(1);
993 // The x86-64 ABI for returning structs by value requires that we copy
994 // the sret argument into %rax for the return. We saved the argument into
995 // a virtual register in the entry block, so now we copy the value out
997 if (Subtarget->is64Bit() &&
998 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
999 MachineFunction &MF = DAG.getMachineFunction();
1000 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1001 unsigned Reg = FuncInfo->getSRetReturnReg();
1003 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1004 FuncInfo->setSRetReturnReg(Reg);
1006 SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
1008 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
1009 Flag = Chain.getValue(1);
1012 RetOps[0] = Chain; // Update chain.
1014 // Add the flag if we have it.
1016 RetOps.push_back(Flag);
1018 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
1022 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1023 /// appropriate copies out of appropriate physical registers. This assumes that
1024 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1025 /// being lowered. The returns a SDNode with the same number of values as the
1027 SDNode *X86TargetLowering::
1028 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1029 unsigned CallingConv, SelectionDAG &DAG) {
1031 // Assign locations to each value returned by this call.
1032 SmallVector<CCValAssign, 16> RVLocs;
1033 bool isVarArg = TheCall->isVarArg();
1034 bool Is64Bit = Subtarget->is64Bit();
1035 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1036 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1038 SmallVector<SDValue, 8> ResultVals;
1040 // Copy all of the result registers out of their specified physreg.
1041 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1042 MVT CopyVT = RVLocs[i].getValVT();
1044 // If this is x86-64, and we disabled SSE, we can't return FP values
1045 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1046 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1047 cerr << "SSE register return with SSE disabled\n";
1051 // If this is a call to a function that returns an fp value on the floating
1052 // point stack, but where we prefer to use the value in xmm registers, copy
1053 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1054 if ((RVLocs[i].getLocReg() == X86::ST0 ||
1055 RVLocs[i].getLocReg() == X86::ST1) &&
1056 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1060 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
1061 CopyVT, InFlag).getValue(1);
1062 SDValue Val = Chain.getValue(0);
1063 InFlag = Chain.getValue(2);
1065 if (CopyVT != RVLocs[i].getValVT()) {
1066 // Round the F80 the right size, which also moves to the appropriate xmm
1068 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
1069 // This truncation won't change the value.
1070 DAG.getIntPtrConstant(1));
1073 ResultVals.push_back(Val);
1076 // Merge everything together with a MERGE_VALUES node.
1077 ResultVals.push_back(Chain);
1078 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(), &ResultVals[0],
1079 ResultVals.size()).getNode();
1083 //===----------------------------------------------------------------------===//
1084 // C & StdCall & Fast Calling Convention implementation
1085 //===----------------------------------------------------------------------===//
1086 // StdCall calling convention seems to be standard for many Windows' API
1087 // routines and around. It differs from C calling convention just a little:
1088 // callee should clean up the stack, not caller. Symbols should be also
1089 // decorated in some fancy way :) It doesn't support any vector arguments.
1090 // For info on fast calling convention see Fast Calling Convention (tail call)
1091 // implementation LowerX86_32FastCCCallTo.
1093 /// AddLiveIn - This helper function adds the specified physical register to the
1094 /// MachineFunction as a live in value. It also creates a corresponding virtual
1095 /// register for it.
1096 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1097 const TargetRegisterClass *RC) {
1098 assert(RC->contains(PReg) && "Not the correct regclass!");
1099 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1100 MF.getRegInfo().addLiveIn(PReg, VReg);
1104 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1106 static bool CallIsStructReturn(CallSDNode *TheCall) {
1107 unsigned NumOps = TheCall->getNumArgs();
1111 return TheCall->getArgFlags(0).isSRet();
1114 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1115 /// return semantics.
1116 static bool ArgsAreStructReturn(SDValue Op) {
1117 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1121 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1124 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1125 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1127 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1131 switch (CallingConv) {
1134 case CallingConv::X86_StdCall:
1135 return !Subtarget->is64Bit();
1136 case CallingConv::X86_FastCall:
1137 return !Subtarget->is64Bit();
1138 case CallingConv::Fast:
1139 return PerformTailCallOpt;
1143 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1144 /// given CallingConvention value.
1145 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1146 if (Subtarget->is64Bit()) {
1147 if (Subtarget->isTargetWin64())
1148 return CC_X86_Win64_C;
1149 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1150 return CC_X86_64_TailCall;
1155 if (CC == CallingConv::X86_FastCall)
1156 return CC_X86_32_FastCall;
1157 else if (CC == CallingConv::Fast)
1158 return CC_X86_32_FastCC;
1163 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1164 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1166 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1167 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1168 if (CC == CallingConv::X86_FastCall)
1170 else if (CC == CallingConv::X86_StdCall)
1176 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1177 /// in a register before calling.
1178 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1179 return !IsTailCall && !Is64Bit &&
1180 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1181 Subtarget->isPICStyleGOT();
1184 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1185 /// address to be loaded in a register.
1187 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1188 return !Is64Bit && IsTailCall &&
1189 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1190 Subtarget->isPICStyleGOT();
1193 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1194 /// by "Src" to address "Dst" with size and alignment information specified by
1195 /// the specific parameter attribute. The copy will be passed as a byval
1196 /// function parameter.
1198 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1199 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1200 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1201 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1202 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1205 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1206 const CCValAssign &VA,
1207 MachineFrameInfo *MFI,
1209 SDValue Root, unsigned i) {
1210 // Create the nodes corresponding to a load from this parameter slot.
1211 ISD::ArgFlagsTy Flags =
1212 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1213 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1214 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1216 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1217 // changed with more analysis.
1218 // In case of tail call optimization mark all arguments mutable. Since they
1219 // could be overwritten by lowering of arguments in case of a tail call.
1220 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1221 VA.getLocMemOffset(), isImmutable);
1222 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1223 if (Flags.isByVal())
1225 return DAG.getLoad(VA.getValVT(), Root, FIN,
1226 PseudoSourceValue::getFixedStack(FI), 0);
1230 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1231 MachineFunction &MF = DAG.getMachineFunction();
1232 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1234 const Function* Fn = MF.getFunction();
1235 if (Fn->hasExternalLinkage() &&
1236 Subtarget->isTargetCygMing() &&
1237 Fn->getName() == "main")
1238 FuncInfo->setForceFramePointer(true);
1240 // Decorate the function name.
1241 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1243 MachineFrameInfo *MFI = MF.getFrameInfo();
1244 SDValue Root = Op.getOperand(0);
1245 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1246 unsigned CC = MF.getFunction()->getCallingConv();
1247 bool Is64Bit = Subtarget->is64Bit();
1248 bool IsWin64 = Subtarget->isTargetWin64();
1250 assert(!(isVarArg && CC == CallingConv::Fast) &&
1251 "Var args not supported with calling convention fastcc");
1253 // Assign locations to all of the incoming arguments.
1254 SmallVector<CCValAssign, 16> ArgLocs;
1255 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1256 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1258 SmallVector<SDValue, 8> ArgValues;
1259 unsigned LastVal = ~0U;
1260 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1261 CCValAssign &VA = ArgLocs[i];
1262 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1264 assert(VA.getValNo() != LastVal &&
1265 "Don't support value assigned to multiple locs yet");
1266 LastVal = VA.getValNo();
1268 if (VA.isRegLoc()) {
1269 MVT RegVT = VA.getLocVT();
1270 TargetRegisterClass *RC = NULL;
1271 if (RegVT == MVT::i32)
1272 RC = X86::GR32RegisterClass;
1273 else if (Is64Bit && RegVT == MVT::i64)
1274 RC = X86::GR64RegisterClass;
1275 else if (RegVT == MVT::f32)
1276 RC = X86::FR32RegisterClass;
1277 else if (RegVT == MVT::f64)
1278 RC = X86::FR64RegisterClass;
1279 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1280 RC = X86::VR128RegisterClass;
1281 else if (RegVT.isVector()) {
1282 assert(RegVT.getSizeInBits() == 64);
1284 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1286 // Darwin calling convention passes MMX values in either GPRs or
1287 // XMMs in x86-64. Other targets pass them in memory.
1288 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1289 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1292 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1297 assert(0 && "Unknown argument type!");
1300 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1301 SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1303 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1304 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1306 if (VA.getLocInfo() == CCValAssign::SExt)
1307 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1308 DAG.getValueType(VA.getValVT()));
1309 else if (VA.getLocInfo() == CCValAssign::ZExt)
1310 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1311 DAG.getValueType(VA.getValVT()));
1313 if (VA.getLocInfo() != CCValAssign::Full)
1314 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1316 // Handle MMX values passed in GPRs.
1317 if (Is64Bit && RegVT != VA.getLocVT()) {
1318 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1319 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1320 else if (RC == X86::VR128RegisterClass) {
1321 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1322 DAG.getConstant(0, MVT::i64));
1323 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1327 ArgValues.push_back(ArgValue);
1329 assert(VA.isMemLoc());
1330 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1334 // The x86-64 ABI for returning structs by value requires that we copy
1335 // the sret argument into %rax for the return. Save the argument into
1336 // a virtual register so that we can access it from the return points.
1337 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1338 MachineFunction &MF = DAG.getMachineFunction();
1339 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1340 unsigned Reg = FuncInfo->getSRetReturnReg();
1342 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1343 FuncInfo->setSRetReturnReg(Reg);
1345 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1346 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1349 unsigned StackSize = CCInfo.getNextStackOffset();
1350 // align stack specially for tail calls
1351 if (PerformTailCallOpt && CC == CallingConv::Fast)
1352 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1354 // If the function takes variable number of arguments, make a frame index for
1355 // the start of the first vararg value... for expansion of llvm.va_start.
1357 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1358 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1361 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1363 // FIXME: We should really autogenerate these arrays
1364 static const unsigned GPR64ArgRegsWin64[] = {
1365 X86::RCX, X86::RDX, X86::R8, X86::R9
1367 static const unsigned XMMArgRegsWin64[] = {
1368 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1370 static const unsigned GPR64ArgRegs64Bit[] = {
1371 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1373 static const unsigned XMMArgRegs64Bit[] = {
1374 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1375 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1377 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1380 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1381 GPR64ArgRegs = GPR64ArgRegsWin64;
1382 XMMArgRegs = XMMArgRegsWin64;
1384 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1385 GPR64ArgRegs = GPR64ArgRegs64Bit;
1386 XMMArgRegs = XMMArgRegs64Bit;
1388 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1390 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1393 assert((Subtarget->hasSSE1() || !NumXMMRegs) &&
1394 "SSE register cannot be used when SSE is disabled!");
1395 if (!Subtarget->hasSSE1()) {
1396 // Kernel mode asks for SSE to be disabled, so don't push them
1398 TotalNumXMMRegs = 0;
1400 // For X86-64, if there are vararg parameters that are passed via
1401 // registers, then we must store them to their spots on the stack so they
1402 // may be loaded by deferencing the result of va_next.
1403 VarArgsGPOffset = NumIntRegs * 8;
1404 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1405 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1406 TotalNumXMMRegs * 16, 16);
1408 // Store the integer parameter registers.
1409 SmallVector<SDValue, 8> MemOps;
1410 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1411 SDValue FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1412 DAG.getIntPtrConstant(VarArgsGPOffset));
1413 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1414 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1415 X86::GR64RegisterClass);
1416 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1418 DAG.getStore(Val.getValue(1), Val, FIN,
1419 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1420 MemOps.push_back(Store);
1421 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1422 DAG.getIntPtrConstant(8));
1425 // Now store the XMM (fp + vector) parameter registers.
1426 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1427 DAG.getIntPtrConstant(VarArgsFPOffset));
1428 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1429 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1430 X86::VR128RegisterClass);
1431 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1433 DAG.getStore(Val.getValue(1), Val, FIN,
1434 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1435 MemOps.push_back(Store);
1436 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1437 DAG.getIntPtrConstant(16));
1439 if (!MemOps.empty())
1440 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1441 &MemOps[0], MemOps.size());
1445 ArgValues.push_back(Root);
1447 // Some CCs need callee pop.
1448 if (IsCalleePop(isVarArg, CC)) {
1449 BytesToPopOnReturn = StackSize; // Callee pops everything.
1450 BytesCallerReserves = 0;
1452 BytesToPopOnReturn = 0; // Callee pops nothing.
1453 // If this is an sret function, the return should pop the hidden pointer.
1454 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1455 BytesToPopOnReturn = 4;
1456 BytesCallerReserves = StackSize;
1460 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1461 if (CC == CallingConv::X86_FastCall)
1462 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1465 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1467 // Return the new list of results.
1468 return DAG.getNode(ISD::MERGE_VALUES, Op.getNode()->getVTList(),
1469 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1473 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1474 const SDValue &StackPtr,
1475 const CCValAssign &VA,
1477 SDValue Arg, ISD::ArgFlagsTy Flags) {
1478 unsigned LocMemOffset = VA.getLocMemOffset();
1479 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1480 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1481 if (Flags.isByVal()) {
1482 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1484 return DAG.getStore(Chain, Arg, PtrOff,
1485 PseudoSourceValue::getStack(), LocMemOffset);
1488 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1489 /// optimization is performed and it is required.
1491 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1492 SDValue &OutRetAddr,
1497 if (!IsTailCall || FPDiff==0) return Chain;
1499 // Adjust the Return address stack slot.
1500 MVT VT = getPointerTy();
1501 OutRetAddr = getReturnAddressFrameIndex(DAG);
1503 // Load the "old" Return address.
1504 OutRetAddr = DAG.getLoad(VT, Chain, OutRetAddr, NULL, 0);
1505 return SDValue(OutRetAddr.getNode(), 1);
1508 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1509 /// optimization is performed and it is required (FPDiff!=0).
1511 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1512 SDValue Chain, SDValue RetAddrFrIdx,
1513 bool Is64Bit, int FPDiff) {
1514 // Store the return address to the appropriate stack slot.
1515 if (!FPDiff) return Chain;
1516 // Calculate the new stack slot for the return address.
1517 int SlotSize = Is64Bit ? 8 : 4;
1518 int NewReturnAddrFI =
1519 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1520 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1521 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1522 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1523 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1527 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1528 MachineFunction &MF = DAG.getMachineFunction();
1529 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1530 SDValue Chain = TheCall->getChain();
1531 unsigned CC = TheCall->getCallingConv();
1532 bool isVarArg = TheCall->isVarArg();
1533 bool IsTailCall = TheCall->isTailCall() &&
1534 CC == CallingConv::Fast && PerformTailCallOpt;
1535 SDValue Callee = TheCall->getCallee();
1536 bool Is64Bit = Subtarget->is64Bit();
1537 bool IsStructRet = CallIsStructReturn(TheCall);
1539 assert(!(isVarArg && CC == CallingConv::Fast) &&
1540 "Var args not supported with calling convention fastcc");
1542 // Analyze operands of the call, assigning locations to each operand.
1543 SmallVector<CCValAssign, 16> ArgLocs;
1544 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1545 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1547 // Get a count of how many bytes are to be pushed on the stack.
1548 unsigned NumBytes = CCInfo.getNextStackOffset();
1549 if (PerformTailCallOpt && CC == CallingConv::Fast)
1550 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1554 // Lower arguments at fp - stackoffset + fpdiff.
1555 unsigned NumBytesCallerPushed =
1556 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1557 FPDiff = NumBytesCallerPushed - NumBytes;
1559 // Set the delta of movement of the returnaddr stackslot.
1560 // But only set if delta is greater than previous delta.
1561 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1562 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1565 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1567 SDValue RetAddrFrIdx;
1568 // Load return adress for tail calls.
1569 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1572 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1573 SmallVector<SDValue, 8> MemOpChains;
1576 // Walk the register/memloc assignments, inserting copies/loads. In the case
1577 // of tail call optimization arguments are handle later.
1578 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1579 CCValAssign &VA = ArgLocs[i];
1580 SDValue Arg = TheCall->getArg(i);
1581 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1582 bool isByVal = Flags.isByVal();
1584 // Promote the value if needed.
1585 switch (VA.getLocInfo()) {
1586 default: assert(0 && "Unknown loc info!");
1587 case CCValAssign::Full: break;
1588 case CCValAssign::SExt:
1589 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1591 case CCValAssign::ZExt:
1592 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1594 case CCValAssign::AExt:
1595 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1599 if (VA.isRegLoc()) {
1601 MVT RegVT = VA.getLocVT();
1602 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1603 switch (VA.getLocReg()) {
1606 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1608 // Special case: passing MMX values in GPR registers.
1609 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1612 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1613 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1614 // Special case: passing MMX values in XMM registers.
1615 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1616 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1617 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1618 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1619 getMOVLMask(2, DAG));
1624 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1626 if (!IsTailCall || (IsTailCall && isByVal)) {
1627 assert(VA.isMemLoc());
1628 if (StackPtr.getNode() == 0)
1629 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1631 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1632 Chain, Arg, Flags));
1637 if (!MemOpChains.empty())
1638 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1639 &MemOpChains[0], MemOpChains.size());
1641 // Build a sequence of copy-to-reg nodes chained together with token chain
1642 // and flag operands which copy the outgoing args into registers.
1644 // Tail call byval lowering might overwrite argument registers so in case of
1645 // tail call optimization the copies to registers are lowered later.
1647 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1648 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1650 InFlag = Chain.getValue(1);
1653 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1655 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1656 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1657 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1659 InFlag = Chain.getValue(1);
1661 // If we are tail calling and generating PIC/GOT style code load the address
1662 // of the callee into ecx. The value in ecx is used as target of the tail
1663 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1664 // calls on PIC/GOT architectures. Normally we would just put the address of
1665 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1666 // restored (since ebx is callee saved) before jumping to the target@PLT.
1667 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1668 // Note: The actual moving to ecx is done further down.
1669 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1670 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1671 !G->getGlobal()->hasProtectedVisibility())
1672 Callee = LowerGlobalAddress(Callee, DAG);
1673 else if (isa<ExternalSymbolSDNode>(Callee))
1674 Callee = LowerExternalSymbol(Callee,DAG);
1677 if (Is64Bit && isVarArg) {
1678 // From AMD64 ABI document:
1679 // For calls that may call functions that use varargs or stdargs
1680 // (prototype-less calls or calls to functions containing ellipsis (...) in
1681 // the declaration) %al is used as hidden argument to specify the number
1682 // of SSE registers used. The contents of %al do not need to match exactly
1683 // the number of registers, but must be an ubound on the number of SSE
1684 // registers used and is in the range 0 - 8 inclusive.
1686 // FIXME: Verify this on Win64
1687 // Count the number of XMM registers allocated.
1688 static const unsigned XMMArgRegs[] = {
1689 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1690 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1692 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1693 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1694 && "SSE registers cannot be used when SSE is disabled");
1696 Chain = DAG.getCopyToReg(Chain, X86::AL,
1697 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1698 InFlag = Chain.getValue(1);
1702 // For tail calls lower the arguments to the 'real' stack slot.
1704 SmallVector<SDValue, 8> MemOpChains2;
1707 // Do not flag preceeding copytoreg stuff together with the following stuff.
1709 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1710 CCValAssign &VA = ArgLocs[i];
1711 if (!VA.isRegLoc()) {
1712 assert(VA.isMemLoc());
1713 SDValue Arg = TheCall->getArg(i);
1714 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1715 // Create frame index.
1716 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1717 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1718 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1719 FIN = DAG.getFrameIndex(FI, getPointerTy());
1721 if (Flags.isByVal()) {
1722 // Copy relative to framepointer.
1723 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1724 if (StackPtr.getNode() == 0)
1725 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1726 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1728 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1731 // Store relative to framepointer.
1732 MemOpChains2.push_back(
1733 DAG.getStore(Chain, Arg, FIN,
1734 PseudoSourceValue::getFixedStack(FI), 0));
1739 if (!MemOpChains2.empty())
1740 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1741 &MemOpChains2[0], MemOpChains2.size());
1743 // Copy arguments to their registers.
1744 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1745 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1747 InFlag = Chain.getValue(1);
1751 // Store the return address to the appropriate stack slot.
1752 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1756 // If the callee is a GlobalAddress node (quite common, every direct call is)
1757 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1758 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1759 // We should use extra load for direct calls to dllimported functions in
1761 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1762 getTargetMachine(), true))
1763 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1765 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1766 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1767 } else if (IsTailCall) {
1768 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1770 Chain = DAG.getCopyToReg(Chain,
1771 DAG.getRegister(Opc, getPointerTy()),
1773 Callee = DAG.getRegister(Opc, getPointerTy());
1774 // Add register as live out.
1775 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1778 // Returns a chain & a flag for retval copy to use.
1779 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1780 SmallVector<SDValue, 8> Ops;
1783 Ops.push_back(Chain);
1784 Ops.push_back(DAG.getIntPtrConstant(NumBytes, true));
1785 Ops.push_back(DAG.getIntPtrConstant(0, true));
1786 if (InFlag.getNode())
1787 Ops.push_back(InFlag);
1788 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1789 InFlag = Chain.getValue(1);
1791 // Returns a chain & a flag for retval copy to use.
1792 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1796 Ops.push_back(Chain);
1797 Ops.push_back(Callee);
1800 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1802 // Add argument registers to the end of the list so that they are known live
1804 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1805 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1806 RegsToPass[i].second.getValueType()));
1808 // Add an implicit use GOT pointer in EBX.
1809 if (!IsTailCall && !Is64Bit &&
1810 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1811 Subtarget->isPICStyleGOT())
1812 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1814 // Add an implicit use of AL for x86 vararg functions.
1815 if (Is64Bit && isVarArg)
1816 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1818 if (InFlag.getNode())
1819 Ops.push_back(InFlag);
1822 assert(InFlag.getNode() &&
1823 "Flag must be set. Depend on flag being set in LowerRET");
1824 Chain = DAG.getNode(X86ISD::TAILCALL,
1825 TheCall->getVTList(), &Ops[0], Ops.size());
1827 return SDValue(Chain.getNode(), Op.getResNo());
1830 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1831 InFlag = Chain.getValue(1);
1833 // Create the CALLSEQ_END node.
1834 unsigned NumBytesForCalleeToPush;
1835 if (IsCalleePop(isVarArg, CC))
1836 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1837 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1838 // If this is is a call to a struct-return function, the callee
1839 // pops the hidden struct pointer, so we have to push it back.
1840 // This is common for Darwin/X86, Linux & Mingw32 targets.
1841 NumBytesForCalleeToPush = 4;
1843 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1845 // Returns a flag for retval copy to use.
1846 Chain = DAG.getCALLSEQ_END(Chain,
1847 DAG.getIntPtrConstant(NumBytes, true),
1848 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1851 InFlag = Chain.getValue(1);
1853 // Handle result values, copying them out of physregs into vregs that we
1855 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1860 //===----------------------------------------------------------------------===//
1861 // Fast Calling Convention (tail call) implementation
1862 //===----------------------------------------------------------------------===//
1864 // Like std call, callee cleans arguments, convention except that ECX is
1865 // reserved for storing the tail called function address. Only 2 registers are
1866 // free for argument passing (inreg). Tail call optimization is performed
1868 // * tailcallopt is enabled
1869 // * caller/callee are fastcc
1870 // On X86_64 architecture with GOT-style position independent code only local
1871 // (within module) calls are supported at the moment.
1872 // To keep the stack aligned according to platform abi the function
1873 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1874 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1875 // If a tail called function callee has more arguments than the caller the
1876 // caller needs to make sure that there is room to move the RETADDR to. This is
1877 // achieved by reserving an area the size of the argument delta right after the
1878 // original REtADDR, but before the saved framepointer or the spilled registers
1879 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1891 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1892 /// for a 16 byte align requirement.
1893 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1894 SelectionDAG& DAG) {
1895 MachineFunction &MF = DAG.getMachineFunction();
1896 const TargetMachine &TM = MF.getTarget();
1897 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1898 unsigned StackAlignment = TFI.getStackAlignment();
1899 uint64_t AlignMask = StackAlignment - 1;
1900 int64_t Offset = StackSize;
1901 uint64_t SlotSize = TD->getPointerSize();
1902 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1903 // Number smaller than 12 so just add the difference.
1904 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1906 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1907 Offset = ((~AlignMask) & Offset) + StackAlignment +
1908 (StackAlignment-SlotSize);
1913 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1914 /// following the call is a return. A function is eligible if caller/callee
1915 /// calling conventions match, currently only fastcc supports tail calls, and
1916 /// the function CALL is immediatly followed by a RET.
1917 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1919 SelectionDAG& DAG) const {
1920 if (!PerformTailCallOpt)
1923 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1924 MachineFunction &MF = DAG.getMachineFunction();
1925 unsigned CallerCC = MF.getFunction()->getCallingConv();
1926 unsigned CalleeCC= TheCall->getCallingConv();
1927 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1928 SDValue Callee = TheCall->getCallee();
1929 // On x86/32Bit PIC/GOT tail calls are supported.
1930 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1931 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1934 // Can only do local tail calls (in same module, hidden or protected) on
1935 // x86_64 PIC/GOT at the moment.
1936 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1937 return G->getGlobal()->hasHiddenVisibility()
1938 || G->getGlobal()->hasProtectedVisibility();
1946 X86TargetLowering::createFastISel(MachineFunction &mf,
1947 MachineModuleInfo *mmo,
1949 DenseMap<const Value *, unsigned> &vm,
1950 DenseMap<const BasicBlock *,
1951 MachineBasicBlock *> &bm,
1952 DenseMap<const AllocaInst *, int> &am
1954 , SmallSet<Instruction*, 8> &cil
1957 return X86::createFastISel(mf, mmo, dw, vm, bm, am
1965 //===----------------------------------------------------------------------===//
1966 // Other Lowering Hooks
1967 //===----------------------------------------------------------------------===//
1970 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1971 MachineFunction &MF = DAG.getMachineFunction();
1972 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1973 int ReturnAddrIndex = FuncInfo->getRAIndex();
1975 if (ReturnAddrIndex == 0) {
1976 // Set up a frame object for the return address.
1977 uint64_t SlotSize = TD->getPointerSize();
1978 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1979 FuncInfo->setRAIndex(ReturnAddrIndex);
1982 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1986 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
1987 /// specific condition code, returning the condition code and the LHS/RHS of the
1988 /// comparison to make.
1989 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1990 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
1992 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1993 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1994 // X > -1 -> X == 0, jump !sign.
1995 RHS = DAG.getConstant(0, RHS.getValueType());
1996 return X86::COND_NS;
1997 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1998 // X < 0 -> X == 0, jump on sign.
2000 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2002 RHS = DAG.getConstant(0, RHS.getValueType());
2003 return X86::COND_LE;
2007 switch (SetCCOpcode) {
2008 default: assert(0 && "Invalid integer condition!");
2009 case ISD::SETEQ: return X86::COND_E;
2010 case ISD::SETGT: return X86::COND_G;
2011 case ISD::SETGE: return X86::COND_GE;
2012 case ISD::SETLT: return X86::COND_L;
2013 case ISD::SETLE: return X86::COND_LE;
2014 case ISD::SETNE: return X86::COND_NE;
2015 case ISD::SETULT: return X86::COND_B;
2016 case ISD::SETUGT: return X86::COND_A;
2017 case ISD::SETULE: return X86::COND_BE;
2018 case ISD::SETUGE: return X86::COND_AE;
2022 // First determine if it is required or is profitable to flip the operands.
2024 // If LHS is a foldable load, but RHS is not, flip the condition.
2025 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2026 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2027 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2028 std::swap(LHS, RHS);
2031 switch (SetCCOpcode) {
2037 std::swap(LHS, RHS);
2041 // On a floating point condition, the flags are set as follows:
2043 // 0 | 0 | 0 | X > Y
2044 // 0 | 0 | 1 | X < Y
2045 // 1 | 0 | 0 | X == Y
2046 // 1 | 1 | 1 | unordered
2047 switch (SetCCOpcode) {
2048 default: assert(0 && "Condcode should be pre-legalized away");
2050 case ISD::SETEQ: return X86::COND_E;
2051 case ISD::SETOLT: // flipped
2053 case ISD::SETGT: return X86::COND_A;
2054 case ISD::SETOLE: // flipped
2056 case ISD::SETGE: return X86::COND_AE;
2057 case ISD::SETUGT: // flipped
2059 case ISD::SETLT: return X86::COND_B;
2060 case ISD::SETUGE: // flipped
2062 case ISD::SETLE: return X86::COND_BE;
2064 case ISD::SETNE: return X86::COND_NE;
2065 case ISD::SETUO: return X86::COND_P;
2066 case ISD::SETO: return X86::COND_NP;
2070 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2071 /// code. Current x86 isa includes the following FP cmov instructions:
2072 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2073 static bool hasFPCMov(unsigned X86CC) {
2089 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2090 /// true if Op is undef or if its value falls within the specified range (L, H].
2091 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2092 if (Op.getOpcode() == ISD::UNDEF)
2095 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2096 return (Val >= Low && Val < Hi);
2099 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2100 /// true if Op is undef or if its value equal to the specified value.
2101 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2102 if (Op.getOpcode() == ISD::UNDEF)
2104 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2107 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2108 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2109 bool X86::isPSHUFDMask(SDNode *N) {
2110 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2112 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2115 // Check if the value doesn't reference the second vector.
2116 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2117 SDValue Arg = N->getOperand(i);
2118 if (Arg.getOpcode() == ISD::UNDEF) continue;
2119 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2120 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2127 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2128 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2129 bool X86::isPSHUFHWMask(SDNode *N) {
2130 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2132 if (N->getNumOperands() != 8)
2135 // Lower quadword copied in order.
2136 for (unsigned i = 0; i != 4; ++i) {
2137 SDValue Arg = N->getOperand(i);
2138 if (Arg.getOpcode() == ISD::UNDEF) continue;
2139 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2140 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2144 // Upper quadword shuffled.
2145 for (unsigned i = 4; i != 8; ++i) {
2146 SDValue Arg = N->getOperand(i);
2147 if (Arg.getOpcode() == ISD::UNDEF) continue;
2148 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2149 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2150 if (Val < 4 || Val > 7)
2157 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2158 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2159 bool X86::isPSHUFLWMask(SDNode *N) {
2160 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2162 if (N->getNumOperands() != 8)
2165 // Upper quadword copied in order.
2166 for (unsigned i = 4; i != 8; ++i)
2167 if (!isUndefOrEqual(N->getOperand(i), i))
2170 // Lower quadword shuffled.
2171 for (unsigned i = 0; i != 4; ++i)
2172 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2178 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2179 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2180 template<class SDOperand>
2181 static bool isSHUFPMask(SDOperand *Elems, unsigned NumElems) {
2182 if (NumElems != 2 && NumElems != 4) return false;
2184 unsigned Half = NumElems / 2;
2185 for (unsigned i = 0; i < Half; ++i)
2186 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2188 for (unsigned i = Half; i < NumElems; ++i)
2189 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2195 bool X86::isSHUFPMask(SDNode *N) {
2196 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2197 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2200 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2201 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2202 /// half elements to come from vector 1 (which would equal the dest.) and
2203 /// the upper half to come from vector 2.
2204 template<class SDOperand>
2205 static bool isCommutedSHUFP(SDOperand *Ops, unsigned NumOps) {
2206 if (NumOps != 2 && NumOps != 4) return false;
2208 unsigned Half = NumOps / 2;
2209 for (unsigned i = 0; i < Half; ++i)
2210 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2212 for (unsigned i = Half; i < NumOps; ++i)
2213 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2218 static bool isCommutedSHUFP(SDNode *N) {
2219 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2220 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2223 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2224 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2225 bool X86::isMOVHLPSMask(SDNode *N) {
2226 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2228 if (N->getNumOperands() != 4)
2231 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2232 return isUndefOrEqual(N->getOperand(0), 6) &&
2233 isUndefOrEqual(N->getOperand(1), 7) &&
2234 isUndefOrEqual(N->getOperand(2), 2) &&
2235 isUndefOrEqual(N->getOperand(3), 3);
2238 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2239 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2241 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2242 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2244 if (N->getNumOperands() != 4)
2247 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2248 return isUndefOrEqual(N->getOperand(0), 2) &&
2249 isUndefOrEqual(N->getOperand(1), 3) &&
2250 isUndefOrEqual(N->getOperand(2), 2) &&
2251 isUndefOrEqual(N->getOperand(3), 3);
2254 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2255 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2256 bool X86::isMOVLPMask(SDNode *N) {
2257 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2259 unsigned NumElems = N->getNumOperands();
2260 if (NumElems != 2 && NumElems != 4)
2263 for (unsigned i = 0; i < NumElems/2; ++i)
2264 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2267 for (unsigned i = NumElems/2; i < NumElems; ++i)
2268 if (!isUndefOrEqual(N->getOperand(i), i))
2274 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2275 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2277 bool X86::isMOVHPMask(SDNode *N) {
2278 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2280 unsigned NumElems = N->getNumOperands();
2281 if (NumElems != 2 && NumElems != 4)
2284 for (unsigned i = 0; i < NumElems/2; ++i)
2285 if (!isUndefOrEqual(N->getOperand(i), i))
2288 for (unsigned i = 0; i < NumElems/2; ++i) {
2289 SDValue Arg = N->getOperand(i + NumElems/2);
2290 if (!isUndefOrEqual(Arg, i + NumElems))
2297 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2298 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2299 template<class SDOperand>
2300 bool static isUNPCKLMask(SDOperand *Elts, unsigned NumElts,
2301 bool V2IsSplat = false) {
2302 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2305 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2306 SDValue BitI = Elts[i];
2307 SDValue BitI1 = Elts[i+1];
2308 if (!isUndefOrEqual(BitI, j))
2311 if (isUndefOrEqual(BitI1, NumElts))
2314 if (!isUndefOrEqual(BitI1, j + NumElts))
2322 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2323 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2324 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2327 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2328 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2329 template<class SDOperand>
2330 bool static isUNPCKHMask(SDOperand *Elts, unsigned NumElts,
2331 bool V2IsSplat = false) {
2332 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2335 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2336 SDValue BitI = Elts[i];
2337 SDValue BitI1 = Elts[i+1];
2338 if (!isUndefOrEqual(BitI, j + NumElts/2))
2341 if (isUndefOrEqual(BitI1, NumElts))
2344 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2352 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2353 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2354 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2357 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2358 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2360 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2361 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2363 unsigned NumElems = N->getNumOperands();
2364 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2367 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2368 SDValue BitI = N->getOperand(i);
2369 SDValue BitI1 = N->getOperand(i+1);
2371 if (!isUndefOrEqual(BitI, j))
2373 if (!isUndefOrEqual(BitI1, j))
2380 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2381 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2383 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2384 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2386 unsigned NumElems = N->getNumOperands();
2387 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2390 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2391 SDValue BitI = N->getOperand(i);
2392 SDValue BitI1 = N->getOperand(i + 1);
2394 if (!isUndefOrEqual(BitI, j))
2396 if (!isUndefOrEqual(BitI1, j))
2403 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2404 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2405 /// MOVSD, and MOVD, i.e. setting the lowest element.
2406 template<class SDOperand>
2407 static bool isMOVLMask(SDOperand *Elts, unsigned NumElts) {
2408 if (NumElts != 2 && NumElts != 4)
2411 if (!isUndefOrEqual(Elts[0], NumElts))
2414 for (unsigned i = 1; i < NumElts; ++i) {
2415 if (!isUndefOrEqual(Elts[i], i))
2422 bool X86::isMOVLMask(SDNode *N) {
2423 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2424 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2427 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2428 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2429 /// element of vector 2 and the other elements to come from vector 1 in order.
2430 template<class SDOperand>
2431 static bool isCommutedMOVL(SDOperand *Ops, unsigned NumOps,
2432 bool V2IsSplat = false,
2433 bool V2IsUndef = false) {
2434 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2437 if (!isUndefOrEqual(Ops[0], 0))
2440 for (unsigned i = 1; i < NumOps; ++i) {
2441 SDValue Arg = Ops[i];
2442 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2443 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2444 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2451 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2452 bool V2IsUndef = false) {
2453 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2454 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2455 V2IsSplat, V2IsUndef);
2458 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2459 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2460 bool X86::isMOVSHDUPMask(SDNode *N) {
2461 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2463 if (N->getNumOperands() != 4)
2466 // Expect 1, 1, 3, 3
2467 for (unsigned i = 0; i < 2; ++i) {
2468 SDValue Arg = N->getOperand(i);
2469 if (Arg.getOpcode() == ISD::UNDEF) continue;
2470 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2471 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2472 if (Val != 1) return false;
2476 for (unsigned i = 2; i < 4; ++i) {
2477 SDValue Arg = N->getOperand(i);
2478 if (Arg.getOpcode() == ISD::UNDEF) continue;
2479 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2480 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2481 if (Val != 3) return false;
2485 // Don't use movshdup if it can be done with a shufps.
2489 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2490 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2491 bool X86::isMOVSLDUPMask(SDNode *N) {
2492 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2494 if (N->getNumOperands() != 4)
2497 // Expect 0, 0, 2, 2
2498 for (unsigned i = 0; i < 2; ++i) {
2499 SDValue Arg = N->getOperand(i);
2500 if (Arg.getOpcode() == ISD::UNDEF) continue;
2501 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2502 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2503 if (Val != 0) return false;
2507 for (unsigned i = 2; i < 4; ++i) {
2508 SDValue Arg = N->getOperand(i);
2509 if (Arg.getOpcode() == ISD::UNDEF) continue;
2510 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2511 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2512 if (Val != 2) return false;
2516 // Don't use movshdup if it can be done with a shufps.
2520 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2521 /// specifies a identity operation on the LHS or RHS.
2522 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2523 unsigned NumElems = N->getNumOperands();
2524 for (unsigned i = 0; i < NumElems; ++i)
2525 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2530 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2531 /// a splat of a single element.
2532 static bool isSplatMask(SDNode *N) {
2533 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2535 // This is a splat operation if each element of the permute is the same, and
2536 // if the value doesn't reference the second vector.
2537 unsigned NumElems = N->getNumOperands();
2538 SDValue ElementBase;
2540 for (; i != NumElems; ++i) {
2541 SDValue Elt = N->getOperand(i);
2542 if (isa<ConstantSDNode>(Elt)) {
2548 if (!ElementBase.getNode())
2551 for (; i != NumElems; ++i) {
2552 SDValue Arg = N->getOperand(i);
2553 if (Arg.getOpcode() == ISD::UNDEF) continue;
2554 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2555 if (Arg != ElementBase) return false;
2558 // Make sure it is a splat of the first vector operand.
2559 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2562 /// getSplatMaskEltNo - Given a splat mask, return the index to the element
2563 /// we want to splat.
2564 static SDValue getSplatMaskEltNo(SDNode *N) {
2565 assert(isSplatMask(N) && "Not a splat mask");
2566 unsigned NumElems = N->getNumOperands();
2567 SDValue ElementBase;
2569 for (; i != NumElems; ++i) {
2570 SDValue Elt = N->getOperand(i);
2571 if (isa<ConstantSDNode>(Elt))
2574 assert(0 && " No splat value found!");
2579 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2580 /// a splat of a single element and it's a 2 or 4 element mask.
2581 bool X86::isSplatMask(SDNode *N) {
2582 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2584 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2585 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2587 return ::isSplatMask(N);
2590 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2591 /// specifies a splat of zero element.
2592 bool X86::isSplatLoMask(SDNode *N) {
2593 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2595 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2596 if (!isUndefOrEqual(N->getOperand(i), 0))
2601 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2602 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2603 bool X86::isMOVDDUPMask(SDNode *N) {
2604 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2606 unsigned e = N->getNumOperands() / 2;
2607 for (unsigned i = 0; i < e; ++i)
2608 if (!isUndefOrEqual(N->getOperand(i), i))
2610 for (unsigned i = 0; i < e; ++i)
2611 if (!isUndefOrEqual(N->getOperand(e+i), i))
2616 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2617 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2619 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2620 unsigned NumOperands = N->getNumOperands();
2621 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2623 for (unsigned i = 0; i < NumOperands; ++i) {
2625 SDValue Arg = N->getOperand(NumOperands-i-1);
2626 if (Arg.getOpcode() != ISD::UNDEF)
2627 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2628 if (Val >= NumOperands) Val -= NumOperands;
2630 if (i != NumOperands - 1)
2637 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2638 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2640 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2642 // 8 nodes, but we only care about the last 4.
2643 for (unsigned i = 7; i >= 4; --i) {
2645 SDValue Arg = N->getOperand(i);
2646 if (Arg.getOpcode() != ISD::UNDEF)
2647 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2656 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2657 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2659 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2661 // 8 nodes, but we only care about the first 4.
2662 for (int i = 3; i >= 0; --i) {
2664 SDValue Arg = N->getOperand(i);
2665 if (Arg.getOpcode() != ISD::UNDEF)
2666 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2675 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2676 /// specifies a 8 element shuffle that can be broken into a pair of
2677 /// PSHUFHW and PSHUFLW.
2678 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2679 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2681 if (N->getNumOperands() != 8)
2684 // Lower quadword shuffled.
2685 for (unsigned i = 0; i != 4; ++i) {
2686 SDValue Arg = N->getOperand(i);
2687 if (Arg.getOpcode() == ISD::UNDEF) continue;
2688 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2689 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2694 // Upper quadword shuffled.
2695 for (unsigned i = 4; i != 8; ++i) {
2696 SDValue Arg = N->getOperand(i);
2697 if (Arg.getOpcode() == ISD::UNDEF) continue;
2698 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2699 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2700 if (Val < 4 || Val > 7)
2707 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2708 /// values in ther permute mask.
2709 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2710 SDValue &V2, SDValue &Mask,
2711 SelectionDAG &DAG) {
2712 MVT VT = Op.getValueType();
2713 MVT MaskVT = Mask.getValueType();
2714 MVT EltVT = MaskVT.getVectorElementType();
2715 unsigned NumElems = Mask.getNumOperands();
2716 SmallVector<SDValue, 8> MaskVec;
2718 for (unsigned i = 0; i != NumElems; ++i) {
2719 SDValue Arg = Mask.getOperand(i);
2720 if (Arg.getOpcode() == ISD::UNDEF) {
2721 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2724 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2725 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2727 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2729 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2733 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2734 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2737 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2738 /// the two vector operands have swapped position.
2740 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2741 MVT MaskVT = Mask.getValueType();
2742 MVT EltVT = MaskVT.getVectorElementType();
2743 unsigned NumElems = Mask.getNumOperands();
2744 SmallVector<SDValue, 8> MaskVec;
2745 for (unsigned i = 0; i != NumElems; ++i) {
2746 SDValue Arg = Mask.getOperand(i);
2747 if (Arg.getOpcode() == ISD::UNDEF) {
2748 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2751 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2752 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2754 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2756 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2758 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2762 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2763 /// match movhlps. The lower half elements should come from upper half of
2764 /// V1 (and in order), and the upper half elements should come from the upper
2765 /// half of V2 (and in order).
2766 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2767 unsigned NumElems = Mask->getNumOperands();
2770 for (unsigned i = 0, e = 2; i != e; ++i)
2771 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2773 for (unsigned i = 2; i != 4; ++i)
2774 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2779 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2780 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2782 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2783 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2785 N = N->getOperand(0).getNode();
2786 if (!ISD::isNON_EXTLoad(N))
2789 *LD = cast<LoadSDNode>(N);
2793 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2794 /// match movlp{s|d}. The lower half elements should come from lower half of
2795 /// V1 (and in order), and the upper half elements should come from the upper
2796 /// half of V2 (and in order). And since V1 will become the source of the
2797 /// MOVLP, it must be either a vector load or a scalar load to vector.
2798 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2799 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2801 // Is V2 is a vector load, don't do this transformation. We will try to use
2802 // load folding shufps op.
2803 if (ISD::isNON_EXTLoad(V2))
2806 unsigned NumElems = Mask->getNumOperands();
2807 if (NumElems != 2 && NumElems != 4)
2809 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2810 if (!isUndefOrEqual(Mask->getOperand(i), i))
2812 for (unsigned i = NumElems/2; i != NumElems; ++i)
2813 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2818 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2820 static bool isSplatVector(SDNode *N) {
2821 if (N->getOpcode() != ISD::BUILD_VECTOR)
2824 SDValue SplatValue = N->getOperand(0);
2825 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2826 if (N->getOperand(i) != SplatValue)
2831 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2833 static bool isUndefShuffle(SDNode *N) {
2834 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2837 SDValue V1 = N->getOperand(0);
2838 SDValue V2 = N->getOperand(1);
2839 SDValue Mask = N->getOperand(2);
2840 unsigned NumElems = Mask.getNumOperands();
2841 for (unsigned i = 0; i != NumElems; ++i) {
2842 SDValue Arg = Mask.getOperand(i);
2843 if (Arg.getOpcode() != ISD::UNDEF) {
2844 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2845 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2847 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2854 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2856 static inline bool isZeroNode(SDValue Elt) {
2857 return ((isa<ConstantSDNode>(Elt) &&
2858 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2859 (isa<ConstantFPSDNode>(Elt) &&
2860 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2863 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2864 /// to an zero vector.
2865 static bool isZeroShuffle(SDNode *N) {
2866 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2869 SDValue V1 = N->getOperand(0);
2870 SDValue V2 = N->getOperand(1);
2871 SDValue Mask = N->getOperand(2);
2872 unsigned NumElems = Mask.getNumOperands();
2873 for (unsigned i = 0; i != NumElems; ++i) {
2874 SDValue Arg = Mask.getOperand(i);
2875 if (Arg.getOpcode() == ISD::UNDEF)
2878 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2879 if (Idx < NumElems) {
2880 unsigned Opc = V1.getNode()->getOpcode();
2881 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2883 if (Opc != ISD::BUILD_VECTOR ||
2884 !isZeroNode(V1.getNode()->getOperand(Idx)))
2886 } else if (Idx >= NumElems) {
2887 unsigned Opc = V2.getNode()->getOpcode();
2888 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2890 if (Opc != ISD::BUILD_VECTOR ||
2891 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2898 /// getZeroVector - Returns a vector of specified type with all zero elements.
2900 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2901 assert(VT.isVector() && "Expected a vector type");
2903 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2904 // type. This ensures they get CSE'd.
2906 if (VT.getSizeInBits() == 64) { // MMX
2907 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2908 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2909 } else if (HasSSE2) { // SSE2
2910 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2911 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2913 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2914 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2916 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2919 /// getOnesVector - Returns a vector of specified type with all bits set.
2921 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2922 assert(VT.isVector() && "Expected a vector type");
2924 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2925 // type. This ensures they get CSE'd.
2926 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2928 if (VT.getSizeInBits() == 64) // MMX
2929 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2931 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2932 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2936 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2937 /// that point to V2 points to its first element.
2938 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2939 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2941 bool Changed = false;
2942 SmallVector<SDValue, 8> MaskVec;
2943 unsigned NumElems = Mask.getNumOperands();
2944 for (unsigned i = 0; i != NumElems; ++i) {
2945 SDValue Arg = Mask.getOperand(i);
2946 if (Arg.getOpcode() != ISD::UNDEF) {
2947 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2948 if (Val > NumElems) {
2949 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2953 MaskVec.push_back(Arg);
2957 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2958 &MaskVec[0], MaskVec.size());
2962 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2963 /// operation of specified width.
2964 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2965 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2966 MVT BaseVT = MaskVT.getVectorElementType();
2968 SmallVector<SDValue, 8> MaskVec;
2969 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2970 for (unsigned i = 1; i != NumElems; ++i)
2971 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2972 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2975 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2976 /// of specified width.
2977 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2978 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2979 MVT BaseVT = MaskVT.getVectorElementType();
2980 SmallVector<SDValue, 8> MaskVec;
2981 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2982 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2983 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2985 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2988 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2989 /// of specified width.
2990 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2991 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2992 MVT BaseVT = MaskVT.getVectorElementType();
2993 unsigned Half = NumElems/2;
2994 SmallVector<SDValue, 8> MaskVec;
2995 for (unsigned i = 0; i != Half; ++i) {
2996 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2997 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2999 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3002 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
3003 /// element #0 of a vector with the specified index, leaving the rest of the
3004 /// elements in place.
3005 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
3006 SelectionDAG &DAG) {
3007 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3008 MVT BaseVT = MaskVT.getVectorElementType();
3009 SmallVector<SDValue, 8> MaskVec;
3010 // Element #0 of the result gets the elt we are replacing.
3011 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
3012 for (unsigned i = 1; i != NumElems; ++i)
3013 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
3014 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3017 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3018 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
3019 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
3020 MVT VT = Op.getValueType();
3023 SDValue V1 = Op.getOperand(0);
3024 SDValue Mask = Op.getOperand(2);
3025 unsigned MaskNumElems = Mask.getNumOperands();
3026 unsigned NumElems = MaskNumElems;
3027 // Special handling of v4f32 -> v4i32.
3028 if (VT != MVT::v4f32) {
3029 // Find which element we want to splat.
3030 SDNode* EltNoNode = getSplatMaskEltNo(Mask.getNode()).getNode();
3031 unsigned EltNo = cast<ConstantSDNode>(EltNoNode)->getZExtValue();
3032 // unpack elements to the correct location
3033 while (NumElems > 4) {
3034 if (EltNo < NumElems/2) {
3035 Mask = getUnpacklMask(MaskNumElems, DAG);
3037 Mask = getUnpackhMask(MaskNumElems, DAG);
3038 EltNo -= NumElems/2;
3040 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
3043 SDValue Cst = DAG.getConstant(EltNo, MVT::i32);
3044 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
3047 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
3048 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
3049 DAG.getNode(ISD::UNDEF, PVT), Mask);
3050 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3053 /// isVectorLoad - Returns true if the node is a vector load, a scalar
3054 /// load that's promoted to vector, or a load bitcasted.
3055 static bool isVectorLoad(SDValue Op) {
3056 assert(Op.getValueType().isVector() && "Expected a vector type");
3057 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
3058 Op.getOpcode() == ISD::BIT_CONVERT) {
3059 return isa<LoadSDNode>(Op.getOperand(0));
3061 return isa<LoadSDNode>(Op);
3065 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3067 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3068 SelectionDAG &DAG, bool HasSSE3) {
3069 // If we have sse3 and shuffle has more than one use or input is a load, then
3070 // use movddup. Otherwise, use movlhps.
3071 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3072 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3073 MVT VT = Op.getValueType();
3076 unsigned NumElems = PVT.getVectorNumElements();
3077 if (NumElems == 2) {
3078 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3079 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
3081 assert(NumElems == 4);
3082 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3083 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3084 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst0, Cst1, Cst0, Cst1);
3087 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
3088 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
3089 DAG.getNode(ISD::UNDEF, PVT), Mask);
3090 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3093 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3094 /// vector of zero or undef vector. This produces a shuffle where the low
3095 /// element of V2 is swizzled into the zero/undef vector, landing at element
3096 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3097 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3098 bool isZero, bool HasSSE2,
3099 SelectionDAG &DAG) {
3100 MVT VT = V2.getValueType();
3102 ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
3103 unsigned NumElems = V2.getValueType().getVectorNumElements();
3104 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3105 MVT EVT = MaskVT.getVectorElementType();
3106 SmallVector<SDValue, 16> MaskVec;
3107 for (unsigned i = 0; i != NumElems; ++i)
3108 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3109 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3111 MaskVec.push_back(DAG.getConstant(i, EVT));
3112 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3113 &MaskVec[0], MaskVec.size());
3114 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3117 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3118 /// a shuffle that is zero.
3120 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3121 unsigned NumElems, bool Low,
3122 SelectionDAG &DAG) {
3123 unsigned NumZeros = 0;
3124 for (unsigned i = 0; i < NumElems; ++i) {
3125 unsigned Index = Low ? i : NumElems-i-1;
3126 SDValue Idx = Mask.getOperand(Index);
3127 if (Idx.getOpcode() == ISD::UNDEF) {
3131 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3132 if (Elt.getNode() && isZeroNode(Elt))
3140 /// isVectorShift - Returns true if the shuffle can be implemented as a
3141 /// logical left or right shift of a vector.
3142 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3143 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3144 unsigned NumElems = Mask.getNumOperands();
3147 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3150 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3155 bool SeenV1 = false;
3156 bool SeenV2 = false;
3157 for (unsigned i = NumZeros; i < NumElems; ++i) {
3158 unsigned Val = isLeft ? (i - NumZeros) : i;
3159 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3160 if (Idx.getOpcode() == ISD::UNDEF)
3162 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3163 if (Index < NumElems)
3172 if (SeenV1 && SeenV2)
3175 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3181 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3183 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3184 unsigned NumNonZero, unsigned NumZero,
3185 SelectionDAG &DAG, TargetLowering &TLI) {
3191 for (unsigned i = 0; i < 16; ++i) {
3192 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3193 if (ThisIsNonZero && First) {
3195 V = getZeroVector(MVT::v8i16, true, DAG);
3197 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3202 SDValue ThisElt(0, 0), LastElt(0, 0);
3203 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3204 if (LastIsNonZero) {
3205 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3207 if (ThisIsNonZero) {
3208 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3209 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3210 ThisElt, DAG.getConstant(8, MVT::i8));
3212 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3216 if (ThisElt.getNode())
3217 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3218 DAG.getIntPtrConstant(i/2));
3222 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3225 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3227 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3228 unsigned NumNonZero, unsigned NumZero,
3229 SelectionDAG &DAG, TargetLowering &TLI) {
3235 for (unsigned i = 0; i < 8; ++i) {
3236 bool isNonZero = (NonZeros & (1 << i)) != 0;
3240 V = getZeroVector(MVT::v8i16, true, DAG);
3242 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3245 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3246 DAG.getIntPtrConstant(i));
3253 /// getVShift - Return a vector logical shift node.
3255 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3256 unsigned NumBits, SelectionDAG &DAG,
3257 const TargetLowering &TLI) {
3258 bool isMMX = VT.getSizeInBits() == 64;
3259 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3260 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3261 SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3262 return DAG.getNode(ISD::BIT_CONVERT, VT,
3263 DAG.getNode(Opc, ShVT, SrcOp,
3264 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3268 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3269 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3270 if (ISD::isBuildVectorAllZeros(Op.getNode())
3271 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3272 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3273 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3274 // eliminated on x86-32 hosts.
3275 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3278 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3279 return getOnesVector(Op.getValueType(), DAG);
3280 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3283 MVT VT = Op.getValueType();
3284 MVT EVT = VT.getVectorElementType();
3285 unsigned EVTBits = EVT.getSizeInBits();
3287 unsigned NumElems = Op.getNumOperands();
3288 unsigned NumZero = 0;
3289 unsigned NumNonZero = 0;
3290 unsigned NonZeros = 0;
3291 bool IsAllConstants = true;
3292 SmallSet<SDValue, 8> Values;
3293 for (unsigned i = 0; i < NumElems; ++i) {
3294 SDValue Elt = Op.getOperand(i);
3295 if (Elt.getOpcode() == ISD::UNDEF)
3298 if (Elt.getOpcode() != ISD::Constant &&
3299 Elt.getOpcode() != ISD::ConstantFP)
3300 IsAllConstants = false;
3301 if (isZeroNode(Elt))
3304 NonZeros |= (1 << i);
3309 if (NumNonZero == 0) {
3310 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3311 return DAG.getNode(ISD::UNDEF, VT);
3314 // Special case for single non-zero, non-undef, element.
3315 if (NumNonZero == 1 && NumElems <= 4) {
3316 unsigned Idx = CountTrailingZeros_32(NonZeros);
3317 SDValue Item = Op.getOperand(Idx);
3319 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3320 // the value are obviously zero, truncate the value to i32 and do the
3321 // insertion that way. Only do this if the value is non-constant or if the
3322 // value is a constant being inserted into element 0. It is cheaper to do
3323 // a constant pool load than it is to do a movd + shuffle.
3324 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3325 (!IsAllConstants || Idx == 0)) {
3326 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3327 // Handle MMX and SSE both.
3328 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3329 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3331 // Truncate the value (which may itself be a constant) to i32, and
3332 // convert it to a vector with movd (S2V+shuffle to zero extend).
3333 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3334 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3335 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3336 Subtarget->hasSSE2(), DAG);
3338 // Now we have our 32-bit value zero extended in the low element of
3339 // a vector. If Idx != 0, swizzle it into place.
3342 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3343 getSwapEltZeroMask(VecElts, Idx, DAG)
3345 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3347 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3351 // If we have a constant or non-constant insertion into the low element of
3352 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3353 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3354 // depending on what the source datatype is. Because we can only get here
3355 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3357 // Don't do this for i64 values on x86-32.
3358 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3359 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3360 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3361 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3362 Subtarget->hasSSE2(), DAG);
3365 // Is it a vector logical left shift?
3366 if (NumElems == 2 && Idx == 1 &&
3367 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3368 unsigned NumBits = VT.getSizeInBits();
3369 return getVShift(true, VT,
3370 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3371 NumBits/2, DAG, *this);
3374 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3377 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3378 // is a non-constant being inserted into an element other than the low one,
3379 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3380 // movd/movss) to move this into the low element, then shuffle it into
3382 if (EVTBits == 32) {
3383 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3385 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3386 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3387 Subtarget->hasSSE2(), DAG);
3388 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3389 MVT MaskEVT = MaskVT.getVectorElementType();
3390 SmallVector<SDValue, 8> MaskVec;
3391 for (unsigned i = 0; i < NumElems; i++)
3392 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3393 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3394 &MaskVec[0], MaskVec.size());
3395 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3396 DAG.getNode(ISD::UNDEF, VT), Mask);
3400 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3401 if (Values.size() == 1)
3404 // A vector full of immediates; various special cases are already
3405 // handled, so this is best done with a single constant-pool load.
3409 // Let legalizer expand 2-wide build_vectors.
3410 if (EVTBits == 64) {
3411 if (NumNonZero == 1) {
3412 // One half is zero or undef.
3413 unsigned Idx = CountTrailingZeros_32(NonZeros);
3414 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3415 Op.getOperand(Idx));
3416 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3417 Subtarget->hasSSE2(), DAG);
3422 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3423 if (EVTBits == 8 && NumElems == 16) {
3424 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3426 if (V.getNode()) return V;
3429 if (EVTBits == 16 && NumElems == 8) {
3430 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3432 if (V.getNode()) return V;
3435 // If element VT is == 32 bits, turn it into a number of shuffles.
3436 SmallVector<SDValue, 8> V;
3438 if (NumElems == 4 && NumZero > 0) {
3439 for (unsigned i = 0; i < 4; ++i) {
3440 bool isZero = !(NonZeros & (1 << i));
3442 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3444 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3447 for (unsigned i = 0; i < 2; ++i) {
3448 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3451 V[i] = V[i*2]; // Must be a zero vector.
3454 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3455 getMOVLMask(NumElems, DAG));
3458 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3459 getMOVLMask(NumElems, DAG));
3462 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3463 getUnpacklMask(NumElems, DAG));
3468 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3469 MVT EVT = MaskVT.getVectorElementType();
3470 SmallVector<SDValue, 8> MaskVec;
3471 bool Reverse = (NonZeros & 0x3) == 2;
3472 for (unsigned i = 0; i < 2; ++i)
3474 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3476 MaskVec.push_back(DAG.getConstant(i, EVT));
3477 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3478 for (unsigned i = 0; i < 2; ++i)
3480 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3482 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3483 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3484 &MaskVec[0], MaskVec.size());
3485 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3488 if (Values.size() > 2) {
3489 // Expand into a number of unpckl*.
3491 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3492 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3493 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3494 SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3495 for (unsigned i = 0; i < NumElems; ++i)
3496 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3498 while (NumElems != 0) {
3499 for (unsigned i = 0; i < NumElems; ++i)
3500 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3511 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3512 SDValue PermMask, SelectionDAG &DAG,
3513 TargetLowering &TLI) {
3515 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3516 MVT MaskEVT = MaskVT.getVectorElementType();
3517 MVT PtrVT = TLI.getPointerTy();
3518 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3519 PermMask.getNode()->op_end());
3521 // First record which half of which vector the low elements come from.
3522 SmallVector<unsigned, 4> LowQuad(4);
3523 for (unsigned i = 0; i < 4; ++i) {
3524 SDValue Elt = MaskElts[i];
3525 if (Elt.getOpcode() == ISD::UNDEF)
3527 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3528 int QuadIdx = EltIdx / 4;
3532 int BestLowQuad = -1;
3533 unsigned MaxQuad = 1;
3534 for (unsigned i = 0; i < 4; ++i) {
3535 if (LowQuad[i] > MaxQuad) {
3537 MaxQuad = LowQuad[i];
3541 // Record which half of which vector the high elements come from.
3542 SmallVector<unsigned, 4> HighQuad(4);
3543 for (unsigned i = 4; i < 8; ++i) {
3544 SDValue Elt = MaskElts[i];
3545 if (Elt.getOpcode() == ISD::UNDEF)
3547 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3548 int QuadIdx = EltIdx / 4;
3549 ++HighQuad[QuadIdx];
3552 int BestHighQuad = -1;
3554 for (unsigned i = 0; i < 4; ++i) {
3555 if (HighQuad[i] > MaxQuad) {
3557 MaxQuad = HighQuad[i];
3561 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3562 if (BestLowQuad != -1 || BestHighQuad != -1) {
3563 // First sort the 4 chunks in order using shufpd.
3564 SmallVector<SDValue, 8> MaskVec;
3566 if (BestLowQuad != -1)
3567 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3569 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3571 if (BestHighQuad != -1)
3572 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3574 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3576 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3577 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3578 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3579 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3580 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3582 // Now sort high and low parts separately.
3583 BitVector InOrder(8);
3584 if (BestLowQuad != -1) {
3585 // Sort lower half in order using PSHUFLW.
3587 bool AnyOutOrder = false;
3589 for (unsigned i = 0; i != 4; ++i) {
3590 SDValue Elt = MaskElts[i];
3591 if (Elt.getOpcode() == ISD::UNDEF) {
3592 MaskVec.push_back(Elt);
3595 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3599 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3601 // If this element is in the right place after this shuffle, then
3603 if ((int)(EltIdx / 4) == BestLowQuad)
3608 for (unsigned i = 4; i != 8; ++i)
3609 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3610 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3611 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3615 if (BestHighQuad != -1) {
3616 // Sort high half in order using PSHUFHW if possible.
3619 for (unsigned i = 0; i != 4; ++i)
3620 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3622 bool AnyOutOrder = false;
3623 for (unsigned i = 4; i != 8; ++i) {
3624 SDValue Elt = MaskElts[i];
3625 if (Elt.getOpcode() == ISD::UNDEF) {
3626 MaskVec.push_back(Elt);
3629 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3633 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3635 // If this element is in the right place after this shuffle, then
3637 if ((int)(EltIdx / 4) == BestHighQuad)
3643 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3644 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3648 // The other elements are put in the right place using pextrw and pinsrw.
3649 for (unsigned i = 0; i != 8; ++i) {
3652 SDValue Elt = MaskElts[i];
3653 if (Elt.getOpcode() == ISD::UNDEF)
3655 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3656 SDValue ExtOp = (EltIdx < 8)
3657 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3658 DAG.getConstant(EltIdx, PtrVT))
3659 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3660 DAG.getConstant(EltIdx - 8, PtrVT));
3661 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3662 DAG.getConstant(i, PtrVT));
3668 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3669 // few as possible. First, let's find out how many elements are already in the
3671 unsigned V1InOrder = 0;
3672 unsigned V1FromV1 = 0;
3673 unsigned V2InOrder = 0;
3674 unsigned V2FromV2 = 0;
3675 SmallVector<SDValue, 8> V1Elts;
3676 SmallVector<SDValue, 8> V2Elts;
3677 for (unsigned i = 0; i < 8; ++i) {
3678 SDValue Elt = MaskElts[i];
3679 if (Elt.getOpcode() == ISD::UNDEF) {
3680 V1Elts.push_back(Elt);
3681 V2Elts.push_back(Elt);
3686 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3688 V1Elts.push_back(Elt);
3689 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3691 } else if (EltIdx == i+8) {
3692 V1Elts.push_back(Elt);
3693 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3695 } else if (EltIdx < 8) {
3696 V1Elts.push_back(Elt);
3697 V2Elts.push_back(DAG.getConstant(EltIdx+8, MaskEVT));
3700 V1Elts.push_back(Elt);
3701 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3706 if (V2InOrder > V1InOrder) {
3707 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3709 std::swap(V1Elts, V2Elts);
3710 std::swap(V1FromV1, V2FromV2);
3713 if ((V1FromV1 + V1InOrder) != 8) {
3714 // Some elements are from V2.
3716 // If there are elements that are from V1 but out of place,
3717 // then first sort them in place
3718 SmallVector<SDValue, 8> MaskVec;
3719 for (unsigned i = 0; i < 8; ++i) {
3720 SDValue Elt = V1Elts[i];
3721 if (Elt.getOpcode() == ISD::UNDEF) {
3722 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3725 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3727 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3729 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3731 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3732 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3736 for (unsigned i = 0; i < 8; ++i) {
3737 SDValue Elt = V1Elts[i];
3738 if (Elt.getOpcode() == ISD::UNDEF)
3740 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3743 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3744 DAG.getConstant(EltIdx - 8, PtrVT));
3745 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3746 DAG.getConstant(i, PtrVT));
3750 // All elements are from V1.
3752 for (unsigned i = 0; i < 8; ++i) {
3753 SDValue Elt = V1Elts[i];
3754 if (Elt.getOpcode() == ISD::UNDEF)
3756 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3757 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3758 DAG.getConstant(EltIdx, PtrVT));
3759 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3760 DAG.getConstant(i, PtrVT));
3766 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3767 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3768 /// done when every pair / quad of shuffle mask elements point to elements in
3769 /// the right sequence. e.g.
3770 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3772 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3774 SDValue PermMask, SelectionDAG &DAG,
3775 TargetLowering &TLI) {
3776 unsigned NumElems = PermMask.getNumOperands();
3777 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3778 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3779 MVT MaskEltVT = MaskVT.getVectorElementType();
3781 switch (VT.getSimpleVT()) {
3782 default: assert(false && "Unexpected!");
3783 case MVT::v4f32: NewVT = MVT::v2f64; break;
3784 case MVT::v4i32: NewVT = MVT::v2i64; break;
3785 case MVT::v8i16: NewVT = MVT::v4i32; break;
3786 case MVT::v16i8: NewVT = MVT::v4i32; break;
3789 if (NewWidth == 2) {
3795 unsigned Scale = NumElems / NewWidth;
3796 SmallVector<SDValue, 8> MaskVec;
3797 for (unsigned i = 0; i < NumElems; i += Scale) {
3798 unsigned StartIdx = ~0U;
3799 for (unsigned j = 0; j < Scale; ++j) {
3800 SDValue Elt = PermMask.getOperand(i+j);
3801 if (Elt.getOpcode() == ISD::UNDEF)
3803 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3804 if (StartIdx == ~0U)
3805 StartIdx = EltIdx - (EltIdx % Scale);
3806 if (EltIdx != StartIdx + j)
3809 if (StartIdx == ~0U)
3810 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3812 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3815 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3816 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3817 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3818 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3819 &MaskVec[0], MaskVec.size()));
3822 /// getVZextMovL - Return a zero-extending vector move low node.
3824 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3825 SDValue SrcOp, SelectionDAG &DAG,
3826 const X86Subtarget *Subtarget) {
3827 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3828 LoadSDNode *LD = NULL;
3829 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3830 LD = dyn_cast<LoadSDNode>(SrcOp);
3832 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3834 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3835 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3836 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3837 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3838 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3840 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3841 return DAG.getNode(ISD::BIT_CONVERT, VT,
3842 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3843 DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3850 return DAG.getNode(ISD::BIT_CONVERT, VT,
3851 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3852 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3855 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3858 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3859 SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3860 MVT MaskVT = PermMask.getValueType();
3861 MVT MaskEVT = MaskVT.getVectorElementType();
3862 SmallVector<std::pair<int, int>, 8> Locs;
3864 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3867 for (unsigned i = 0; i != 4; ++i) {
3868 SDValue Elt = PermMask.getOperand(i);
3869 if (Elt.getOpcode() == ISD::UNDEF) {
3870 Locs[i] = std::make_pair(-1, -1);
3872 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3873 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3875 Locs[i] = std::make_pair(0, NumLo);
3879 Locs[i] = std::make_pair(1, NumHi);
3881 Mask1[2+NumHi] = Elt;
3887 if (NumLo <= 2 && NumHi <= 2) {
3888 // If no more than two elements come from either vector. This can be
3889 // implemented with two shuffles. First shuffle gather the elements.
3890 // The second shuffle, which takes the first shuffle as both of its
3891 // vector operands, put the elements into the right order.
3892 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3893 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3894 &Mask1[0], Mask1.size()));
3896 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3897 for (unsigned i = 0; i != 4; ++i) {
3898 if (Locs[i].first == -1)
3901 unsigned Idx = (i < 2) ? 0 : 4;
3902 Idx += Locs[i].first * 2 + Locs[i].second;
3903 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3907 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3908 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3909 &Mask2[0], Mask2.size()));
3910 } else if (NumLo == 3 || NumHi == 3) {
3911 // Otherwise, we must have three elements from one vector, call it X, and
3912 // one element from the other, call it Y. First, use a shufps to build an
3913 // intermediate vector with the one element from Y and the element from X
3914 // that will be in the same half in the final destination (the indexes don't
3915 // matter). Then, use a shufps to build the final vector, taking the half
3916 // containing the element from Y from the intermediate, and the other half
3919 // Normalize it so the 3 elements come from V1.
3920 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3924 // Find the element from V2.
3926 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3927 SDValue Elt = PermMask.getOperand(HiIndex);
3928 if (Elt.getOpcode() == ISD::UNDEF)
3930 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3935 Mask1[0] = PermMask.getOperand(HiIndex);
3936 Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3937 Mask1[2] = PermMask.getOperand(HiIndex^1);
3938 Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3939 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3940 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3943 Mask1[0] = PermMask.getOperand(0);
3944 Mask1[1] = PermMask.getOperand(1);
3945 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3946 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3947 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3948 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3950 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3951 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3952 Mask1[2] = PermMask.getOperand(2);
3953 Mask1[3] = PermMask.getOperand(3);
3954 if (Mask1[2].getOpcode() != ISD::UNDEF)
3956 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3958 if (Mask1[3].getOpcode() != ISD::UNDEF)
3960 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3962 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3963 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3967 // Break it into (shuffle shuffle_hi, shuffle_lo).
3969 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3970 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3971 SmallVector<SDValue,8> *MaskPtr = &LoMask;
3972 unsigned MaskIdx = 0;
3975 for (unsigned i = 0; i != 4; ++i) {
3982 SDValue Elt = PermMask.getOperand(i);
3983 if (Elt.getOpcode() == ISD::UNDEF) {
3984 Locs[i] = std::make_pair(-1, -1);
3985 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
3986 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3987 (*MaskPtr)[LoIdx] = Elt;
3990 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3991 (*MaskPtr)[HiIdx] = Elt;
3996 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3997 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3998 &LoMask[0], LoMask.size()));
3999 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
4000 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4001 &HiMask[0], HiMask.size()));
4002 SmallVector<SDValue, 8> MaskOps;
4003 for (unsigned i = 0; i != 4; ++i) {
4004 if (Locs[i].first == -1) {
4005 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
4007 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4008 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
4011 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
4012 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4013 &MaskOps[0], MaskOps.size()));
4017 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4018 SDValue V1 = Op.getOperand(0);
4019 SDValue V2 = Op.getOperand(1);
4020 SDValue PermMask = Op.getOperand(2);
4021 MVT VT = Op.getValueType();
4022 unsigned NumElems = PermMask.getNumOperands();
4023 bool isMMX = VT.getSizeInBits() == 64;
4024 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4025 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4026 bool V1IsSplat = false;
4027 bool V2IsSplat = false;
4029 if (isUndefShuffle(Op.getNode()))
4030 return DAG.getNode(ISD::UNDEF, VT);
4032 if (isZeroShuffle(Op.getNode()))
4033 return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
4035 if (isIdentityMask(PermMask.getNode()))
4037 else if (isIdentityMask(PermMask.getNode(), true))
4040 // Canonicalize movddup shuffles.
4041 if (V2IsUndef && Subtarget->hasSSE2() &&
4042 VT.getSizeInBits() == 128 &&
4043 X86::isMOVDDUPMask(PermMask.getNode()))
4044 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
4046 if (isSplatMask(PermMask.getNode())) {
4047 if (isMMX || NumElems < 4) return Op;
4048 // Promote it to a v4{if}32 splat.
4049 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
4052 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4054 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4055 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
4056 if (NewOp.getNode())
4057 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
4058 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4059 // FIXME: Figure out a cleaner way to do this.
4060 // Try to make use of movq to zero out the top part.
4061 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4062 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4064 if (NewOp.getNode()) {
4065 SDValue NewV1 = NewOp.getOperand(0);
4066 SDValue NewV2 = NewOp.getOperand(1);
4067 SDValue NewMask = NewOp.getOperand(2);
4068 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4069 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4070 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
4073 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4074 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4076 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4077 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4082 // Check if this can be converted into a logical shift.
4083 bool isLeft = false;
4086 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4087 if (isShift && ShVal.hasOneUse()) {
4088 // If the shifted value has multiple uses, it may be cheaper to use
4089 // v_set0 + movlhps or movhlps, etc.
4090 MVT EVT = VT.getVectorElementType();
4091 ShAmt *= EVT.getSizeInBits();
4092 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4095 if (X86::isMOVLMask(PermMask.getNode())) {
4098 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4099 return getVZextMovL(VT, VT, V2, DAG, Subtarget);
4104 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4105 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4106 X86::isMOVHLPSMask(PermMask.getNode()) ||
4107 X86::isMOVHPMask(PermMask.getNode()) ||
4108 X86::isMOVLPMask(PermMask.getNode())))
4111 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4112 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4113 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4116 // No better options. Use a vshl / vsrl.
4117 MVT EVT = VT.getVectorElementType();
4118 ShAmt *= EVT.getSizeInBits();
4119 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4122 bool Commuted = false;
4123 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4124 // 1,1,1,1 -> v8i16 though.
4125 V1IsSplat = isSplatVector(V1.getNode());
4126 V2IsSplat = isSplatVector(V2.getNode());
4128 // Canonicalize the splat or undef, if present, to be on the RHS.
4129 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4130 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4131 std::swap(V1IsSplat, V2IsSplat);
4132 std::swap(V1IsUndef, V2IsUndef);
4136 // FIXME: Figure out a cleaner way to do this.
4137 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4138 if (V2IsUndef) return V1;
4139 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4141 // V2 is a splat, so the mask may be malformed. That is, it may point
4142 // to any V2 element. The instruction selectior won't like this. Get
4143 // a corrected mask and commute to form a proper MOVS{S|D}.
4144 SDValue NewMask = getMOVLMask(NumElems, DAG);
4145 if (NewMask.getNode() != PermMask.getNode())
4146 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4151 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4152 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4153 X86::isUNPCKLMask(PermMask.getNode()) ||
4154 X86::isUNPCKHMask(PermMask.getNode()))
4158 // Normalize mask so all entries that point to V2 points to its first
4159 // element then try to match unpck{h|l} again. If match, return a
4160 // new vector_shuffle with the corrected mask.
4161 SDValue NewMask = NormalizeMask(PermMask, DAG);
4162 if (NewMask.getNode() != PermMask.getNode()) {
4163 if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
4164 SDValue NewMask = getUnpacklMask(NumElems, DAG);
4165 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4166 } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
4167 SDValue NewMask = getUnpackhMask(NumElems, DAG);
4168 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4173 // Normalize the node to match x86 shuffle ops if needed
4174 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4175 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4178 // Commute is back and try unpck* again.
4179 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4180 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4181 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4182 X86::isUNPCKLMask(PermMask.getNode()) ||
4183 X86::isUNPCKHMask(PermMask.getNode()))
4187 // Try PSHUF* first, then SHUFP*.
4188 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4189 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4190 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4191 if (V2.getOpcode() != ISD::UNDEF)
4192 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
4193 DAG.getNode(ISD::UNDEF, VT), PermMask);
4198 if (Subtarget->hasSSE2() &&
4199 (X86::isPSHUFDMask(PermMask.getNode()) ||
4200 X86::isPSHUFHWMask(PermMask.getNode()) ||
4201 X86::isPSHUFLWMask(PermMask.getNode()))) {
4203 if (VT == MVT::v4f32) {
4205 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
4206 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
4207 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4208 } else if (V2.getOpcode() != ISD::UNDEF)
4209 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
4210 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4212 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4216 // Binary or unary shufps.
4217 if (X86::isSHUFPMask(PermMask.getNode()) ||
4218 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4222 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4223 if (VT == MVT::v8i16) {
4224 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4225 if (NewOp.getNode())
4229 // Handle all 4 wide cases with a number of shuffles except for MMX.
4230 if (NumElems == 4 && !isMMX)
4231 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4237 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4238 SelectionDAG &DAG) {
4239 MVT VT = Op.getValueType();
4240 if (VT.getSizeInBits() == 8) {
4241 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4242 Op.getOperand(0), Op.getOperand(1));
4243 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4244 DAG.getValueType(VT));
4245 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4246 } else if (VT.getSizeInBits() == 16) {
4247 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4248 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4250 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4251 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4252 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32,
4255 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4256 Op.getOperand(0), Op.getOperand(1));
4257 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4258 DAG.getValueType(VT));
4259 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4260 } else if (VT == MVT::f32) {
4261 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4262 // the result back to FR32 register. It's only worth matching if the
4263 // result has a single use which is a store or a bitcast to i32. And in
4264 // the case of a store, it's not worth it if the index is a constant 0,
4265 // because a MOVSSmr can be used instead, which is smaller and faster.
4266 if (!Op.hasOneUse())
4268 SDNode *User = *Op.getNode()->use_begin();
4269 if ((User->getOpcode() != ISD::STORE ||
4270 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4271 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4272 (User->getOpcode() != ISD::BIT_CONVERT ||
4273 User->getValueType(0) != MVT::i32))
4275 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4276 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4278 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4279 } else if (VT == MVT::i32) {
4280 // ExtractPS works with constant index.
4281 if (isa<ConstantSDNode>(Op.getOperand(1)))
4289 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4290 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4293 if (Subtarget->hasSSE41()) {
4294 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4299 MVT VT = Op.getValueType();
4300 // TODO: handle v16i8.
4301 if (VT.getSizeInBits() == 16) {
4302 SDValue Vec = Op.getOperand(0);
4303 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4305 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4306 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4307 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4309 // Transform it so it match pextrw which produces a 32-bit result.
4310 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4311 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4312 Op.getOperand(0), Op.getOperand(1));
4313 SDValue Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
4314 DAG.getValueType(VT));
4315 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4316 } else if (VT.getSizeInBits() == 32) {
4317 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4320 // SHUFPS the element to the lowest double word, then movss.
4321 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4322 SmallVector<SDValue, 8> IdxVec;
4324 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4326 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4328 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4330 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4331 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4332 &IdxVec[0], IdxVec.size());
4333 SDValue Vec = Op.getOperand(0);
4334 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4335 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4336 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4337 DAG.getIntPtrConstant(0));
4338 } else if (VT.getSizeInBits() == 64) {
4339 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4340 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4341 // to match extract_elt for f64.
4342 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4346 // UNPCKHPD the element to the lowest double word, then movsd.
4347 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4348 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4349 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4350 SmallVector<SDValue, 8> IdxVec;
4351 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4353 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4354 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4355 &IdxVec[0], IdxVec.size());
4356 SDValue Vec = Op.getOperand(0);
4357 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4358 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4359 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4360 DAG.getIntPtrConstant(0));
4367 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4368 MVT VT = Op.getValueType();
4369 MVT EVT = VT.getVectorElementType();
4371 SDValue N0 = Op.getOperand(0);
4372 SDValue N1 = Op.getOperand(1);
4373 SDValue N2 = Op.getOperand(2);
4375 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4376 isa<ConstantSDNode>(N2)) {
4377 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4379 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4381 if (N1.getValueType() != MVT::i32)
4382 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4383 if (N2.getValueType() != MVT::i32)
4384 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4385 return DAG.getNode(Opc, VT, N0, N1, N2);
4386 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4387 // Bits [7:6] of the constant are the source select. This will always be
4388 // zero here. The DAG Combiner may combine an extract_elt index into these
4389 // bits. For example (insert (extract, 3), 2) could be matched by putting
4390 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4391 // Bits [5:4] of the constant are the destination select. This is the
4392 // value of the incoming immediate.
4393 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4394 // combine either bitwise AND or insert of float 0.0 to set these bits.
4395 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4396 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4397 } else if (EVT == MVT::i32) {
4398 // InsertPS works with constant index.
4399 if (isa<ConstantSDNode>(N2))
4406 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4407 MVT VT = Op.getValueType();
4408 MVT EVT = VT.getVectorElementType();
4410 if (Subtarget->hasSSE41())
4411 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4416 SDValue N0 = Op.getOperand(0);
4417 SDValue N1 = Op.getOperand(1);
4418 SDValue N2 = Op.getOperand(2);
4420 if (EVT.getSizeInBits() == 16) {
4421 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4422 // as its second argument.
4423 if (N1.getValueType() != MVT::i32)
4424 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4425 if (N2.getValueType() != MVT::i32)
4426 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4427 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4433 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4434 if (Op.getValueType() == MVT::v2f32)
4435 return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4436 DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4437 DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4438 Op.getOperand(0))));
4440 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4441 MVT VT = MVT::v2i32;
4442 switch (Op.getValueType().getSimpleVT()) {
4449 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4450 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4453 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4454 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4455 // one of the above mentioned nodes. It has to be wrapped because otherwise
4456 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4457 // be used to form addressing mode. These wrapped nodes will be selected
4460 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4461 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4462 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4464 CP->getAlignment());
4465 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4466 // With PIC, the address is actually $g + Offset.
4467 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4468 !Subtarget->isPICStyleRIPRel()) {
4469 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4470 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4478 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
4480 SelectionDAG &DAG) const {
4481 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4482 bool ExtraLoadRequired =
4483 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4485 // Create the TargetGlobalAddress node, folding in the constant
4486 // offset if it is legal.
4488 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4489 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4492 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4493 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4495 // With PIC, the address is actually $g + Offset.
4496 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4497 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4498 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4502 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4503 // load the value at address GV, not the value of GV itself. This means that
4504 // the GlobalAddress must be in the base or index register of the address, not
4505 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4506 // The same applies for external symbols during PIC codegen
4507 if (ExtraLoadRequired)
4508 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4509 PseudoSourceValue::getGOT(), 0);
4511 // If there was a non-zero offset that we didn't fold, create an explicit
4514 Result = DAG.getNode(ISD::ADD, getPointerTy(), Result,
4515 DAG.getConstant(Offset, getPointerTy()));
4521 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4522 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4523 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4524 return LowerGlobalAddress(GV, Offset, DAG);
4527 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4529 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4532 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4533 DAG.getNode(X86ISD::GlobalBaseReg,
4535 InFlag = Chain.getValue(1);
4537 // emit leal symbol@TLSGD(,%ebx,1), %eax
4538 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4539 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4540 GA->getValueType(0),
4542 SDValue Ops[] = { Chain, TGA, InFlag };
4543 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4544 InFlag = Result.getValue(2);
4545 Chain = Result.getValue(1);
4547 // call ___tls_get_addr. This function receives its argument in
4548 // the register EAX.
4549 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4550 InFlag = Chain.getValue(1);
4552 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4553 SDValue Ops1[] = { Chain,
4554 DAG.getTargetExternalSymbol("___tls_get_addr",
4556 DAG.getRegister(X86::EAX, PtrVT),
4557 DAG.getRegister(X86::EBX, PtrVT),
4559 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4560 InFlag = Chain.getValue(1);
4562 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4565 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4567 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4569 SDValue InFlag, Chain;
4571 // emit leaq symbol@TLSGD(%rip), %rdi
4572 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4573 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4574 GA->getValueType(0),
4576 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4577 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4578 Chain = Result.getValue(1);
4579 InFlag = Result.getValue(2);
4581 // call __tls_get_addr. This function receives its argument in
4582 // the register RDI.
4583 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4584 InFlag = Chain.getValue(1);
4586 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4587 SDValue Ops1[] = { Chain,
4588 DAG.getTargetExternalSymbol("__tls_get_addr",
4590 DAG.getRegister(X86::RDI, PtrVT),
4592 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4593 InFlag = Chain.getValue(1);
4595 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4598 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4599 // "local exec" model.
4600 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4602 // Get the Thread Pointer
4603 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4604 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4606 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4607 GA->getValueType(0),
4609 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4611 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4612 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4613 PseudoSourceValue::getGOT(), 0);
4615 // The address of the thread local variable is the add of the thread
4616 // pointer with the offset of the variable.
4617 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4621 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4622 // TODO: implement the "local dynamic" model
4623 // TODO: implement the "initial exec"model for pic executables
4624 assert(Subtarget->isTargetELF() &&
4625 "TLS not implemented for non-ELF targets");
4626 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4627 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4628 // otherwise use the "Local Exec"TLS Model
4629 if (Subtarget->is64Bit()) {
4630 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4632 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4633 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4635 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4640 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4641 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4642 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4643 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4644 // With PIC, the address is actually $g + Offset.
4645 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4646 !Subtarget->isPICStyleRIPRel()) {
4647 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4648 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4655 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4656 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4657 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4658 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4659 // With PIC, the address is actually $g + Offset.
4660 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4661 !Subtarget->isPICStyleRIPRel()) {
4662 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4663 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4670 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4671 /// take a 2 x i32 value to shift plus a shift amount.
4672 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4673 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4674 MVT VT = Op.getValueType();
4675 unsigned VTBits = VT.getSizeInBits();
4676 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4677 SDValue ShOpLo = Op.getOperand(0);
4678 SDValue ShOpHi = Op.getOperand(1);
4679 SDValue ShAmt = Op.getOperand(2);
4680 SDValue Tmp1 = isSRA ?
4681 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4682 DAG.getConstant(0, VT);
4685 if (Op.getOpcode() == ISD::SHL_PARTS) {
4686 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4687 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4689 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4690 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4693 SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4694 DAG.getConstant(VTBits, MVT::i8));
4695 SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4696 AndNode, DAG.getConstant(0, MVT::i8));
4699 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4700 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4701 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4703 if (Op.getOpcode() == ISD::SHL_PARTS) {
4704 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4705 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4707 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4708 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4711 SDValue Ops[2] = { Lo, Hi };
4712 return DAG.getMergeValues(Ops, 2);
4715 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4716 MVT SrcVT = Op.getOperand(0).getValueType();
4717 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4718 "Unknown SINT_TO_FP to lower!");
4720 // These are really Legal; caller falls through into that case.
4721 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4723 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4724 Subtarget->is64Bit())
4727 unsigned Size = SrcVT.getSizeInBits()/8;
4728 MachineFunction &MF = DAG.getMachineFunction();
4729 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4730 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4731 SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4733 PseudoSourceValue::getFixedStack(SSFI), 0);
4737 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4739 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4741 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4742 SmallVector<SDValue, 8> Ops;
4743 Ops.push_back(Chain);
4744 Ops.push_back(StackSlot);
4745 Ops.push_back(DAG.getValueType(SrcVT));
4746 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4747 Tys, &Ops[0], Ops.size());
4750 Chain = Result.getValue(1);
4751 SDValue InFlag = Result.getValue(2);
4753 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4754 // shouldn't be necessary except that RFP cannot be live across
4755 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4756 MachineFunction &MF = DAG.getMachineFunction();
4757 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4758 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4759 Tys = DAG.getVTList(MVT::Other);
4760 SmallVector<SDValue, 8> Ops;
4761 Ops.push_back(Chain);
4762 Ops.push_back(Result);
4763 Ops.push_back(StackSlot);
4764 Ops.push_back(DAG.getValueType(Op.getValueType()));
4765 Ops.push_back(InFlag);
4766 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4767 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4768 PseudoSourceValue::getFixedStack(SSFI), 0);
4774 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4775 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4776 // This algorithm is not obvious. Here it is in C code, more or less:
4778 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4779 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4780 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4782 // Copy ints to xmm registers.
4783 __m128i xh = _mm_cvtsi32_si128( hi );
4784 __m128i xl = _mm_cvtsi32_si128( lo );
4786 // Combine into low half of a single xmm register.
4787 __m128i x = _mm_unpacklo_epi32( xh, xl );
4791 // Merge in appropriate exponents to give the integer bits the right
4793 x = _mm_unpacklo_epi32( x, exp );
4795 // Subtract away the biases to deal with the IEEE-754 double precision
4797 d = _mm_sub_pd( (__m128d) x, bias );
4799 // All conversions up to here are exact. The correctly rounded result is
4800 // calculated using the current rounding mode using the following
4802 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4803 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4804 // store doesn't really need to be here (except
4805 // maybe to zero the other double)
4810 // Build some magic constants.
4811 std::vector<Constant*> CV0;
4812 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4813 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4814 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4815 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4816 Constant *C0 = ConstantVector::get(CV0);
4817 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
4819 std::vector<Constant*> CV1;
4820 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4821 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4822 Constant *C1 = ConstantVector::get(CV1);
4823 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
4825 SmallVector<SDValue, 4> MaskVec;
4826 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
4827 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
4828 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
4829 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
4830 SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, &MaskVec[0],
4832 SmallVector<SDValue, 4> MaskVec2;
4833 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
4834 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
4835 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec2[0],
4838 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4839 DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4841 DAG.getIntPtrConstant(1)));
4842 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4843 DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4845 DAG.getIntPtrConstant(0)));
4846 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
4847 XR1, XR2, UnpcklMask);
4848 SDValue CLod0 = DAG.getLoad(MVT::v4i32, DAG.getEntryNode(), CPIdx0,
4849 PseudoSourceValue::getConstantPool(), 0,
4851 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
4852 Unpck1, CLod0, UnpcklMask);
4853 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, MVT::v2f64, Unpck2);
4854 SDValue CLod1 = DAG.getLoad(MVT::v2f64, CLod0.getValue(1), CPIdx1,
4855 PseudoSourceValue::getConstantPool(), 0,
4857 SDValue Sub = DAG.getNode(ISD::FSUB, MVT::v2f64, XR2F, CLod1);
4859 // Add the halves; easiest way is to swap them into another reg first.
4860 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2f64,
4861 Sub, Sub, ShufMask);
4862 SDValue Add = DAG.getNode(ISD::FADD, MVT::v2f64, Shuf, Sub);
4863 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f64, Add,
4864 DAG.getIntPtrConstant(0));
4867 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4868 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4869 // FP constant to bias correct the final result.
4870 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4873 // Load the 32-bit value into an XMM register.
4874 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4875 DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4877 DAG.getIntPtrConstant(0)));
4879 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f64,
4880 DAG.getNode(ISD::BIT_CONVERT, MVT::v2f64, Load),
4881 DAG.getIntPtrConstant(0));
4883 // Or the load with the bias.
4884 SDValue Or = DAG.getNode(ISD::OR, MVT::v2i64,
4885 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64,
4886 DAG.getNode(ISD::SCALAR_TO_VECTOR,
4888 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64,
4889 DAG.getNode(ISD::SCALAR_TO_VECTOR,
4890 MVT::v2f64, Bias)));
4891 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f64,
4892 DAG.getNode(ISD::BIT_CONVERT, MVT::v2f64, Or),
4893 DAG.getIntPtrConstant(0));
4895 // Subtract the bias.
4896 SDValue Sub = DAG.getNode(ISD::FSUB, MVT::f64, Or, Bias);
4898 // Handle final rounding.
4899 MVT DestVT = Op.getValueType();
4901 if (DestVT.bitsLT(MVT::f64)) {
4902 return DAG.getNode(ISD::FP_ROUND, DestVT, Sub,
4903 DAG.getIntPtrConstant(0));
4904 } else if (DestVT.bitsGT(MVT::f64)) {
4905 return DAG.getNode(ISD::FP_EXTEND, DestVT, Sub);
4908 // Handle final rounding.
4912 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4913 SDValue N0 = Op.getOperand(0);
4915 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4916 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4917 // the optimization here.
4918 if (DAG.SignBitIsZero(N0))
4919 return DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), N0);
4921 MVT SrcVT = N0.getValueType();
4922 if (SrcVT == MVT::i64) {
4923 // We only handle SSE2 f64 target here; caller can handle the rest.
4924 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4927 return LowerUINT_TO_FP_i64(Op, DAG);
4928 } else if (SrcVT == MVT::i32) {
4929 return LowerUINT_TO_FP_i32(Op, DAG);
4932 assert(0 && "Unknown UINT_TO_FP to lower!");
4936 std::pair<SDValue,SDValue> X86TargetLowering::
4937 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4938 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4939 Op.getValueType().getSimpleVT() >= MVT::i16 &&
4940 "Unknown FP_TO_SINT to lower!");
4942 // These are really Legal.
4943 if (Op.getValueType() == MVT::i32 &&
4944 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4945 return std::make_pair(SDValue(), SDValue());
4946 if (Subtarget->is64Bit() &&
4947 Op.getValueType() == MVT::i64 &&
4948 Op.getOperand(0).getValueType() != MVT::f80)
4949 return std::make_pair(SDValue(), SDValue());
4951 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4953 MachineFunction &MF = DAG.getMachineFunction();
4954 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4955 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4956 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4958 switch (Op.getValueType().getSimpleVT()) {
4959 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4960 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4961 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4962 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4965 SDValue Chain = DAG.getEntryNode();
4966 SDValue Value = Op.getOperand(0);
4967 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4968 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4969 Chain = DAG.getStore(Chain, Value, StackSlot,
4970 PseudoSourceValue::getFixedStack(SSFI), 0);
4971 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4973 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4975 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4976 Chain = Value.getValue(1);
4977 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4978 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4981 // Build the FP_TO_INT*_IN_MEM
4982 SDValue Ops[] = { Chain, Value, StackSlot };
4983 SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4985 return std::make_pair(FIST, StackSlot);
4988 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4989 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4990 SDValue FIST = Vals.first, StackSlot = Vals.second;
4991 if (FIST.getNode() == 0) return SDValue();
4994 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4997 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4998 MVT VT = Op.getValueType();
5001 EltVT = VT.getVectorElementType();
5002 std::vector<Constant*> CV;
5003 if (EltVT == MVT::f64) {
5004 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
5008 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
5014 Constant *C = ConstantVector::get(CV);
5015 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5016 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
5017 PseudoSourceValue::getConstantPool(), 0,
5019 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
5022 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5023 MVT VT = Op.getValueType();
5025 unsigned EltNum = 1;
5026 if (VT.isVector()) {
5027 EltVT = VT.getVectorElementType();
5028 EltNum = VT.getVectorNumElements();
5030 std::vector<Constant*> CV;
5031 if (EltVT == MVT::f64) {
5032 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
5036 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
5042 Constant *C = ConstantVector::get(CV);
5043 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5044 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
5045 PseudoSourceValue::getConstantPool(), 0,
5047 if (VT.isVector()) {
5048 return DAG.getNode(ISD::BIT_CONVERT, VT,
5049 DAG.getNode(ISD::XOR, MVT::v2i64,
5050 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
5051 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
5053 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
5057 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5058 SDValue Op0 = Op.getOperand(0);
5059 SDValue Op1 = Op.getOperand(1);
5060 MVT VT = Op.getValueType();
5061 MVT SrcVT = Op1.getValueType();
5063 // If second operand is smaller, extend it first.
5064 if (SrcVT.bitsLT(VT)) {
5065 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
5068 // And if it is bigger, shrink it first.
5069 if (SrcVT.bitsGT(VT)) {
5070 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
5074 // At this point the operands and the result should have the same
5075 // type, and that won't be f80 since that is not custom lowered.
5077 // First get the sign bit of second operand.
5078 std::vector<Constant*> CV;
5079 if (SrcVT == MVT::f64) {
5080 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5081 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5083 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5084 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5085 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5086 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5088 Constant *C = ConstantVector::get(CV);
5089 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5090 SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
5091 PseudoSourceValue::getConstantPool(), 0,
5093 SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
5095 // Shift sign bit right or left if the two operands have different types.
5096 if (SrcVT.bitsGT(VT)) {
5097 // Op0 is MVT::f32, Op1 is MVT::f64.
5098 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
5099 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
5100 DAG.getConstant(32, MVT::i32));
5101 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
5102 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
5103 DAG.getIntPtrConstant(0));
5106 // Clear first operand sign bit.
5108 if (VT == MVT::f64) {
5109 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5110 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5112 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5113 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5114 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5115 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5117 C = ConstantVector::get(CV);
5118 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5119 SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
5120 PseudoSourceValue::getConstantPool(), 0,
5122 SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
5124 // Or the value with the sign bit.
5125 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
5128 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5129 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5130 SDValue Op0 = Op.getOperand(0);
5131 SDValue Op1 = Op.getOperand(1);
5132 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5134 // Lower (X & (1 << N)) == 0 to BT(X, N).
5135 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5136 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5137 if (Op0.getOpcode() == ISD::AND &&
5139 Op1.getOpcode() == ISD::Constant &&
5140 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5141 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5143 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5144 if (ConstantSDNode *Op010C =
5145 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5146 if (Op010C->getZExtValue() == 1) {
5147 LHS = Op0.getOperand(0);
5148 RHS = Op0.getOperand(1).getOperand(1);
5150 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5151 if (ConstantSDNode *Op000C =
5152 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5153 if (Op000C->getZExtValue() == 1) {
5154 LHS = Op0.getOperand(1);
5155 RHS = Op0.getOperand(0).getOperand(1);
5157 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5158 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5159 SDValue AndLHS = Op0.getOperand(0);
5160 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5161 LHS = AndLHS.getOperand(0);
5162 RHS = AndLHS.getOperand(1);
5166 if (LHS.getNode()) {
5167 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5168 // instruction. Since the shift amount is in-range-or-undefined, we know
5169 // that doing a bittest on the i16 value is ok. We extend to i32 because
5170 // the encoding for the i16 version is larger than the i32 version.
5171 if (LHS.getValueType() == MVT::i8)
5172 LHS = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, LHS);
5174 // If the operand types disagree, extend the shift amount to match. Since
5175 // BT ignores high bits (like shifts) we can use anyextend.
5176 if (LHS.getValueType() != RHS.getValueType())
5177 RHS = DAG.getNode(ISD::ANY_EXTEND, LHS.getValueType(), RHS);
5179 SDValue BT = DAG.getNode(X86ISD::BT, MVT::i32, LHS, RHS);
5180 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5181 return DAG.getNode(X86ISD::SETCC, MVT::i8,
5182 DAG.getConstant(Cond, MVT::i8), BT);
5186 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5187 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5189 SDValue Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
5190 return DAG.getNode(X86ISD::SETCC, MVT::i8,
5191 DAG.getConstant(X86CC, MVT::i8), Cond);
5194 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5196 SDValue Op0 = Op.getOperand(0);
5197 SDValue Op1 = Op.getOperand(1);
5198 SDValue CC = Op.getOperand(2);
5199 MVT VT = Op.getValueType();
5200 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5201 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5205 MVT VT0 = Op0.getValueType();
5206 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5207 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5210 switch (SetCCOpcode) {
5213 case ISD::SETEQ: SSECC = 0; break;
5215 case ISD::SETGT: Swap = true; // Fallthrough
5217 case ISD::SETOLT: SSECC = 1; break;
5219 case ISD::SETGE: Swap = true; // Fallthrough
5221 case ISD::SETOLE: SSECC = 2; break;
5222 case ISD::SETUO: SSECC = 3; break;
5224 case ISD::SETNE: SSECC = 4; break;
5225 case ISD::SETULE: Swap = true;
5226 case ISD::SETUGE: SSECC = 5; break;
5227 case ISD::SETULT: Swap = true;
5228 case ISD::SETUGT: SSECC = 6; break;
5229 case ISD::SETO: SSECC = 7; break;
5232 std::swap(Op0, Op1);
5234 // In the two special cases we can't handle, emit two comparisons.
5236 if (SetCCOpcode == ISD::SETUEQ) {
5238 UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5239 EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5240 return DAG.getNode(ISD::OR, VT, UNORD, EQ);
5242 else if (SetCCOpcode == ISD::SETONE) {
5244 ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5245 NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5246 return DAG.getNode(ISD::AND, VT, ORD, NEQ);
5248 assert(0 && "Illegal FP comparison");
5250 // Handle all other FP comparisons here.
5251 return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5254 // We are handling one of the integer comparisons here. Since SSE only has
5255 // GT and EQ comparisons for integer, swapping operands and multiple
5256 // operations may be required for some comparisons.
5257 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5258 bool Swap = false, Invert = false, FlipSigns = false;
5260 switch (VT.getSimpleVT()) {
5262 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5263 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5264 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5265 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5268 switch (SetCCOpcode) {
5270 case ISD::SETNE: Invert = true;
5271 case ISD::SETEQ: Opc = EQOpc; break;
5272 case ISD::SETLT: Swap = true;
5273 case ISD::SETGT: Opc = GTOpc; break;
5274 case ISD::SETGE: Swap = true;
5275 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5276 case ISD::SETULT: Swap = true;
5277 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5278 case ISD::SETUGE: Swap = true;
5279 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5282 std::swap(Op0, Op1);
5284 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5285 // bits of the inputs before performing those operations.
5287 MVT EltVT = VT.getVectorElementType();
5288 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5290 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5291 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
5293 Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
5294 Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
5297 SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
5299 // If the logical-not of the result is required, perform that now.
5301 Result = DAG.getNOT(Op.getDebugLoc(), Result, VT);
5306 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5307 static bool isX86LogicalCmp(unsigned Opc) {
5308 return Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI;
5311 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5312 bool addTest = true;
5313 SDValue Cond = Op.getOperand(0);
5316 if (Cond.getOpcode() == ISD::SETCC)
5317 Cond = LowerSETCC(Cond, DAG);
5319 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5320 // setting operand in place of the X86ISD::SETCC.
5321 if (Cond.getOpcode() == X86ISD::SETCC) {
5322 CC = Cond.getOperand(0);
5324 SDValue Cmp = Cond.getOperand(1);
5325 unsigned Opc = Cmp.getOpcode();
5326 MVT VT = Op.getValueType();
5328 bool IllegalFPCMov = false;
5329 if (VT.isFloatingPoint() && !VT.isVector() &&
5330 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5331 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5333 if ((isX86LogicalCmp(Opc) && !IllegalFPCMov) || Opc == X86ISD::BT) { // FIXME
5340 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5341 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5344 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5346 SmallVector<SDValue, 4> Ops;
5347 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5348 // condition is true.
5349 Ops.push_back(Op.getOperand(2));
5350 Ops.push_back(Op.getOperand(1));
5352 Ops.push_back(Cond);
5353 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
5356 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5357 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5358 // from the AND / OR.
5359 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5360 Opc = Op.getOpcode();
5361 if (Opc != ISD::OR && Opc != ISD::AND)
5363 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5364 Op.getOperand(0).hasOneUse() &&
5365 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5366 Op.getOperand(1).hasOneUse());
5369 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5370 bool addTest = true;
5371 SDValue Chain = Op.getOperand(0);
5372 SDValue Cond = Op.getOperand(1);
5373 SDValue Dest = Op.getOperand(2);
5376 if (Cond.getOpcode() == ISD::SETCC)
5377 Cond = LowerSETCC(Cond, DAG);
5379 // FIXME: LowerXALUO doesn't handle these!!
5380 else if (Cond.getOpcode() == X86ISD::ADD ||
5381 Cond.getOpcode() == X86ISD::SUB ||
5382 Cond.getOpcode() == X86ISD::SMUL ||
5383 Cond.getOpcode() == X86ISD::UMUL)
5384 Cond = LowerXALUO(Cond, DAG);
5387 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5388 // setting operand in place of the X86ISD::SETCC.
5389 if (Cond.getOpcode() == X86ISD::SETCC) {
5390 CC = Cond.getOperand(0);
5392 SDValue Cmp = Cond.getOperand(1);
5393 unsigned Opc = Cmp.getOpcode();
5394 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5395 if (isX86LogicalCmp(Opc) || Opc == X86ISD::BT) {
5399 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5403 // These can only come from an arithmetic instruction with overflow,
5404 // e.g. SADDO, UADDO.
5405 Cond = Cond.getNode()->getOperand(1);
5412 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5413 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5414 unsigned Opc = Cmp.getOpcode();
5415 if (CondOpc == ISD::OR) {
5416 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5417 // two branches instead of an explicit OR instruction with a
5419 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5420 isX86LogicalCmp(Opc)) {
5421 CC = Cond.getOperand(0).getOperand(0);
5422 Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5423 Chain, Dest, CC, Cmp);
5424 CC = Cond.getOperand(1).getOperand(0);
5428 } else { // ISD::AND
5429 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5430 // two branches instead of an explicit AND instruction with a
5431 // separate test. However, we only do this if this block doesn't
5432 // have a fall-through edge, because this requires an explicit
5433 // jmp when the condition is false.
5434 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5435 isX86LogicalCmp(Opc) &&
5436 Op.getNode()->hasOneUse()) {
5437 X86::CondCode CCode =
5438 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5439 CCode = X86::GetOppositeBranchCondition(CCode);
5440 CC = DAG.getConstant(CCode, MVT::i8);
5441 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5442 // Look for an unconditional branch following this conditional branch.
5443 // We need this because we need to reverse the successors in order
5444 // to implement FCMP_OEQ.
5445 if (User.getOpcode() == ISD::BR) {
5446 SDValue FalseBB = User.getOperand(1);
5448 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5449 assert(NewBR == User);
5452 Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5453 Chain, Dest, CC, Cmp);
5454 X86::CondCode CCode =
5455 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5456 CCode = X86::GetOppositeBranchCondition(CCode);
5457 CC = DAG.getConstant(CCode, MVT::i8);
5467 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5468 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5470 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5471 Chain, Dest, CC, Cond);
5475 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5476 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5477 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5478 // that the guard pages used by the OS virtual memory manager are allocated in
5479 // correct sequence.
5481 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5482 SelectionDAG &DAG) {
5483 assert(Subtarget->isTargetCygMing() &&
5484 "This should be used only on Cygwin/Mingw targets");
5487 SDValue Chain = Op.getOperand(0);
5488 SDValue Size = Op.getOperand(1);
5489 // FIXME: Ensure alignment here
5493 MVT IntPtr = getPointerTy();
5494 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5496 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5498 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
5499 Flag = Chain.getValue(1);
5501 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5502 SDValue Ops[] = { Chain,
5503 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5504 DAG.getRegister(X86::EAX, IntPtr),
5505 DAG.getRegister(X86StackPtr, SPTy),
5507 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
5508 Flag = Chain.getValue(1);
5510 Chain = DAG.getCALLSEQ_END(Chain,
5511 DAG.getIntPtrConstant(0, true),
5512 DAG.getIntPtrConstant(0, true),
5515 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5517 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5518 return DAG.getMergeValues(Ops1, 2);
5522 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5524 SDValue Dst, SDValue Src,
5525 SDValue Size, unsigned Align,
5527 uint64_t DstSVOff) {
5528 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5530 // If not DWORD aligned or size is more than the threshold, call the library.
5531 // The libc version is likely to be faster for these cases. It can use the
5532 // address value and run time information about the CPU.
5533 if ((Align & 3) != 0 ||
5535 ConstantSize->getZExtValue() >
5536 getSubtarget()->getMaxInlineSizeThreshold()) {
5537 SDValue InFlag(0, 0);
5539 // Check to see if there is a specialized entry-point for memory zeroing.
5540 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5542 if (const char *bzeroEntry = V &&
5543 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5544 MVT IntPtr = getPointerTy();
5545 const Type *IntPtrTy = TD->getIntPtrType();
5546 TargetLowering::ArgListTy Args;
5547 TargetLowering::ArgListEntry Entry;
5549 Entry.Ty = IntPtrTy;
5550 Args.push_back(Entry);
5552 Args.push_back(Entry);
5553 // FIXME provide DebugLoc info
5554 std::pair<SDValue,SDValue> CallResult =
5555 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5556 CallingConv::C, false,
5557 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG,
5558 DebugLoc::getUnknownLoc());
5559 return CallResult.second;
5562 // Otherwise have the target-independent code call memset.
5566 uint64_t SizeVal = ConstantSize->getZExtValue();
5567 SDValue InFlag(0, 0);
5570 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5571 unsigned BytesLeft = 0;
5572 bool TwoRepStos = false;
5575 uint64_t Val = ValC->getZExtValue() & 255;
5577 // If the value is a constant, then we can potentially use larger sets.
5578 switch (Align & 3) {
5579 case 2: // WORD aligned
5582 Val = (Val << 8) | Val;
5584 case 0: // DWORD aligned
5587 Val = (Val << 8) | Val;
5588 Val = (Val << 16) | Val;
5589 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5592 Val = (Val << 32) | Val;
5595 default: // Byte aligned
5598 Count = DAG.getIntPtrConstant(SizeVal);
5602 if (AVT.bitsGT(MVT::i8)) {
5603 unsigned UBytes = AVT.getSizeInBits() / 8;
5604 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5605 BytesLeft = SizeVal % UBytes;
5608 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5610 InFlag = Chain.getValue(1);
5613 Count = DAG.getIntPtrConstant(SizeVal);
5614 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5615 InFlag = Chain.getValue(1);
5618 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5620 InFlag = Chain.getValue(1);
5621 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5623 InFlag = Chain.getValue(1);
5625 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5626 SmallVector<SDValue, 8> Ops;
5627 Ops.push_back(Chain);
5628 Ops.push_back(DAG.getValueType(AVT));
5629 Ops.push_back(InFlag);
5630 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5633 InFlag = Chain.getValue(1);
5635 MVT CVT = Count.getValueType();
5636 SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5637 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5638 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5640 InFlag = Chain.getValue(1);
5641 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5643 Ops.push_back(Chain);
5644 Ops.push_back(DAG.getValueType(MVT::i8));
5645 Ops.push_back(InFlag);
5646 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5647 } else if (BytesLeft) {
5648 // Handle the last 1 - 7 bytes.
5649 unsigned Offset = SizeVal - BytesLeft;
5650 MVT AddrVT = Dst.getValueType();
5651 MVT SizeVT = Size.getValueType();
5653 Chain = DAG.getMemset(Chain,
5654 DAG.getNode(ISD::ADD, AddrVT, Dst,
5655 DAG.getConstant(Offset, AddrVT)),
5657 DAG.getConstant(BytesLeft, SizeVT),
5658 Align, DstSV, DstSVOff + Offset);
5661 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5666 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5667 SDValue Chain, SDValue Dst, SDValue Src,
5668 SDValue Size, unsigned Align,
5670 const Value *DstSV, uint64_t DstSVOff,
5671 const Value *SrcSV, uint64_t SrcSVOff) {
5672 // This requires the copy size to be a constant, preferrably
5673 // within a subtarget-specific limit.
5674 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5677 uint64_t SizeVal = ConstantSize->getZExtValue();
5678 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5681 /// If not DWORD aligned, call the library.
5682 if ((Align & 3) != 0)
5687 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5690 unsigned UBytes = AVT.getSizeInBits() / 8;
5691 unsigned CountVal = SizeVal / UBytes;
5692 SDValue Count = DAG.getIntPtrConstant(CountVal);
5693 unsigned BytesLeft = SizeVal % UBytes;
5695 SDValue InFlag(0, 0);
5696 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5698 InFlag = Chain.getValue(1);
5699 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5701 InFlag = Chain.getValue(1);
5702 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5704 InFlag = Chain.getValue(1);
5706 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5707 SmallVector<SDValue, 8> Ops;
5708 Ops.push_back(Chain);
5709 Ops.push_back(DAG.getValueType(AVT));
5710 Ops.push_back(InFlag);
5711 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5713 SmallVector<SDValue, 4> Results;
5714 Results.push_back(RepMovs);
5716 // Handle the last 1 - 7 bytes.
5717 unsigned Offset = SizeVal - BytesLeft;
5718 MVT DstVT = Dst.getValueType();
5719 MVT SrcVT = Src.getValueType();
5720 MVT SizeVT = Size.getValueType();
5721 Results.push_back(DAG.getMemcpy(Chain,
5722 DAG.getNode(ISD::ADD, DstVT, Dst,
5723 DAG.getConstant(Offset, DstVT)),
5724 DAG.getNode(ISD::ADD, SrcVT, Src,
5725 DAG.getConstant(Offset, SrcVT)),
5726 DAG.getConstant(BytesLeft, SizeVT),
5727 Align, AlwaysInline,
5728 DstSV, DstSVOff + Offset,
5729 SrcSV, SrcSVOff + Offset));
5732 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5735 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5736 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5738 if (!Subtarget->is64Bit()) {
5739 // vastart just stores the address of the VarArgsFrameIndex slot into the
5740 // memory location argument.
5741 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5742 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5746 // gp_offset (0 - 6 * 8)
5747 // fp_offset (48 - 48 + 8 * 16)
5748 // overflow_arg_area (point to parameters coming in memory).
5750 SmallVector<SDValue, 8> MemOps;
5751 SDValue FIN = Op.getOperand(1);
5753 SDValue Store = DAG.getStore(Op.getOperand(0),
5754 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5756 MemOps.push_back(Store);
5759 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5760 Store = DAG.getStore(Op.getOperand(0),
5761 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5763 MemOps.push_back(Store);
5765 // Store ptr to overflow_arg_area
5766 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5767 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5768 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5769 MemOps.push_back(Store);
5771 // Store ptr to reg_save_area.
5772 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5773 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5774 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5775 MemOps.push_back(Store);
5776 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5779 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5780 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5781 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5782 SDValue Chain = Op.getOperand(0);
5783 SDValue SrcPtr = Op.getOperand(1);
5784 SDValue SrcSV = Op.getOperand(2);
5786 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5791 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5792 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5793 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5794 SDValue Chain = Op.getOperand(0);
5795 SDValue DstPtr = Op.getOperand(1);
5796 SDValue SrcPtr = Op.getOperand(2);
5797 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5798 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5800 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5801 DAG.getIntPtrConstant(24), 8, false,
5802 DstSV, 0, SrcSV, 0);
5806 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5807 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5809 default: return SDValue(); // Don't custom lower most intrinsics.
5810 // Comparison intrinsics.
5811 case Intrinsic::x86_sse_comieq_ss:
5812 case Intrinsic::x86_sse_comilt_ss:
5813 case Intrinsic::x86_sse_comile_ss:
5814 case Intrinsic::x86_sse_comigt_ss:
5815 case Intrinsic::x86_sse_comige_ss:
5816 case Intrinsic::x86_sse_comineq_ss:
5817 case Intrinsic::x86_sse_ucomieq_ss:
5818 case Intrinsic::x86_sse_ucomilt_ss:
5819 case Intrinsic::x86_sse_ucomile_ss:
5820 case Intrinsic::x86_sse_ucomigt_ss:
5821 case Intrinsic::x86_sse_ucomige_ss:
5822 case Intrinsic::x86_sse_ucomineq_ss:
5823 case Intrinsic::x86_sse2_comieq_sd:
5824 case Intrinsic::x86_sse2_comilt_sd:
5825 case Intrinsic::x86_sse2_comile_sd:
5826 case Intrinsic::x86_sse2_comigt_sd:
5827 case Intrinsic::x86_sse2_comige_sd:
5828 case Intrinsic::x86_sse2_comineq_sd:
5829 case Intrinsic::x86_sse2_ucomieq_sd:
5830 case Intrinsic::x86_sse2_ucomilt_sd:
5831 case Intrinsic::x86_sse2_ucomile_sd:
5832 case Intrinsic::x86_sse2_ucomigt_sd:
5833 case Intrinsic::x86_sse2_ucomige_sd:
5834 case Intrinsic::x86_sse2_ucomineq_sd: {
5836 ISD::CondCode CC = ISD::SETCC_INVALID;
5839 case Intrinsic::x86_sse_comieq_ss:
5840 case Intrinsic::x86_sse2_comieq_sd:
5844 case Intrinsic::x86_sse_comilt_ss:
5845 case Intrinsic::x86_sse2_comilt_sd:
5849 case Intrinsic::x86_sse_comile_ss:
5850 case Intrinsic::x86_sse2_comile_sd:
5854 case Intrinsic::x86_sse_comigt_ss:
5855 case Intrinsic::x86_sse2_comigt_sd:
5859 case Intrinsic::x86_sse_comige_ss:
5860 case Intrinsic::x86_sse2_comige_sd:
5864 case Intrinsic::x86_sse_comineq_ss:
5865 case Intrinsic::x86_sse2_comineq_sd:
5869 case Intrinsic::x86_sse_ucomieq_ss:
5870 case Intrinsic::x86_sse2_ucomieq_sd:
5871 Opc = X86ISD::UCOMI;
5874 case Intrinsic::x86_sse_ucomilt_ss:
5875 case Intrinsic::x86_sse2_ucomilt_sd:
5876 Opc = X86ISD::UCOMI;
5879 case Intrinsic::x86_sse_ucomile_ss:
5880 case Intrinsic::x86_sse2_ucomile_sd:
5881 Opc = X86ISD::UCOMI;
5884 case Intrinsic::x86_sse_ucomigt_ss:
5885 case Intrinsic::x86_sse2_ucomigt_sd:
5886 Opc = X86ISD::UCOMI;
5889 case Intrinsic::x86_sse_ucomige_ss:
5890 case Intrinsic::x86_sse2_ucomige_sd:
5891 Opc = X86ISD::UCOMI;
5894 case Intrinsic::x86_sse_ucomineq_ss:
5895 case Intrinsic::x86_sse2_ucomineq_sd:
5896 Opc = X86ISD::UCOMI;
5901 SDValue LHS = Op.getOperand(1);
5902 SDValue RHS = Op.getOperand(2);
5903 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
5904 SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5905 SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5906 DAG.getConstant(X86CC, MVT::i8), Cond);
5907 return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
5910 // Fix vector shift instructions where the last operand is a non-immediate
5912 case Intrinsic::x86_sse2_pslli_w:
5913 case Intrinsic::x86_sse2_pslli_d:
5914 case Intrinsic::x86_sse2_pslli_q:
5915 case Intrinsic::x86_sse2_psrli_w:
5916 case Intrinsic::x86_sse2_psrli_d:
5917 case Intrinsic::x86_sse2_psrli_q:
5918 case Intrinsic::x86_sse2_psrai_w:
5919 case Intrinsic::x86_sse2_psrai_d:
5920 case Intrinsic::x86_mmx_pslli_w:
5921 case Intrinsic::x86_mmx_pslli_d:
5922 case Intrinsic::x86_mmx_pslli_q:
5923 case Intrinsic::x86_mmx_psrli_w:
5924 case Intrinsic::x86_mmx_psrli_d:
5925 case Intrinsic::x86_mmx_psrli_q:
5926 case Intrinsic::x86_mmx_psrai_w:
5927 case Intrinsic::x86_mmx_psrai_d: {
5928 SDValue ShAmt = Op.getOperand(2);
5929 if (isa<ConstantSDNode>(ShAmt))
5932 unsigned NewIntNo = 0;
5933 MVT ShAmtVT = MVT::v4i32;
5935 case Intrinsic::x86_sse2_pslli_w:
5936 NewIntNo = Intrinsic::x86_sse2_psll_w;
5938 case Intrinsic::x86_sse2_pslli_d:
5939 NewIntNo = Intrinsic::x86_sse2_psll_d;
5941 case Intrinsic::x86_sse2_pslli_q:
5942 NewIntNo = Intrinsic::x86_sse2_psll_q;
5944 case Intrinsic::x86_sse2_psrli_w:
5945 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5947 case Intrinsic::x86_sse2_psrli_d:
5948 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5950 case Intrinsic::x86_sse2_psrli_q:
5951 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5953 case Intrinsic::x86_sse2_psrai_w:
5954 NewIntNo = Intrinsic::x86_sse2_psra_w;
5956 case Intrinsic::x86_sse2_psrai_d:
5957 NewIntNo = Intrinsic::x86_sse2_psra_d;
5960 ShAmtVT = MVT::v2i32;
5962 case Intrinsic::x86_mmx_pslli_w:
5963 NewIntNo = Intrinsic::x86_mmx_psll_w;
5965 case Intrinsic::x86_mmx_pslli_d:
5966 NewIntNo = Intrinsic::x86_mmx_psll_d;
5968 case Intrinsic::x86_mmx_pslli_q:
5969 NewIntNo = Intrinsic::x86_mmx_psll_q;
5971 case Intrinsic::x86_mmx_psrli_w:
5972 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5974 case Intrinsic::x86_mmx_psrli_d:
5975 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5977 case Intrinsic::x86_mmx_psrli_q:
5978 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5980 case Intrinsic::x86_mmx_psrai_w:
5981 NewIntNo = Intrinsic::x86_mmx_psra_w;
5983 case Intrinsic::x86_mmx_psrai_d:
5984 NewIntNo = Intrinsic::x86_mmx_psra_d;
5986 default: abort(); // Can't reach here.
5991 MVT VT = Op.getValueType();
5992 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5993 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5994 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5995 DAG.getConstant(NewIntNo, MVT::i32),
5996 Op.getOperand(1), ShAmt);
6001 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6002 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6005 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6007 DAG.getConstant(TD->getPointerSize(),
6008 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6009 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(),
6010 DAG.getNode(ISD::ADD, getPointerTy(), FrameAddr, Offset),
6014 // Just load the return address.
6015 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6016 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
6019 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6020 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6021 MFI->setFrameAddressIsTaken(true);
6022 MVT VT = Op.getValueType();
6023 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6024 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6025 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), FrameReg, VT);
6027 FrameAddr = DAG.getLoad(VT, DAG.getEntryNode(), FrameAddr, NULL, 0);
6031 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6032 SelectionDAG &DAG) {
6033 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6036 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6038 MachineFunction &MF = DAG.getMachineFunction();
6039 SDValue Chain = Op.getOperand(0);
6040 SDValue Offset = Op.getOperand(1);
6041 SDValue Handler = Op.getOperand(2);
6043 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6045 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6047 SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
6048 DAG.getIntPtrConstant(-TD->getPointerSize()));
6049 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
6050 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
6051 Chain = DAG.getCopyToReg(Chain, StoreAddrReg, StoreAddr);
6052 MF.getRegInfo().addLiveOut(StoreAddrReg);
6054 return DAG.getNode(X86ISD::EH_RETURN,
6056 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6059 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6060 SelectionDAG &DAG) {
6061 SDValue Root = Op.getOperand(0);
6062 SDValue Trmp = Op.getOperand(1); // trampoline
6063 SDValue FPtr = Op.getOperand(2); // nested function
6064 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6066 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6068 const X86InstrInfo *TII =
6069 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6071 if (Subtarget->is64Bit()) {
6072 SDValue OutChains[6];
6074 // Large code-model.
6076 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6077 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6079 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6080 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6082 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6084 // Load the pointer to the nested function into R11.
6085 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6086 SDValue Addr = Trmp;
6087 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
6090 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
6091 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
6093 // Load the 'nest' parameter value into R10.
6094 // R10 is specified in X86CallingConv.td
6095 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6096 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
6097 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
6100 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
6101 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
6103 // Jump to the nested function.
6104 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6105 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
6106 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
6109 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6110 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
6111 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
6115 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
6116 return DAG.getMergeValues(Ops, 2);
6118 const Function *Func =
6119 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6120 unsigned CC = Func->getCallingConv();
6125 assert(0 && "Unsupported calling convention");
6126 case CallingConv::C:
6127 case CallingConv::X86_StdCall: {
6128 // Pass 'nest' parameter in ECX.
6129 // Must be kept in sync with X86CallingConv.td
6132 // Check that ECX wasn't needed by an 'inreg' parameter.
6133 const FunctionType *FTy = Func->getFunctionType();
6134 const AttrListPtr &Attrs = Func->getAttributes();
6136 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6137 unsigned InRegCount = 0;
6140 for (FunctionType::param_iterator I = FTy->param_begin(),
6141 E = FTy->param_end(); I != E; ++I, ++Idx)
6142 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6143 // FIXME: should only count parameters that are lowered to integers.
6144 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6146 if (InRegCount > 2) {
6147 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6153 case CallingConv::X86_FastCall:
6154 case CallingConv::Fast:
6155 // Pass 'nest' parameter in EAX.
6156 // Must be kept in sync with X86CallingConv.td
6161 SDValue OutChains[4];
6164 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
6165 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
6167 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6168 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6169 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6172 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
6173 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
6175 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6176 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
6177 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
6178 TrmpAddr, 5, false, 1);
6180 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
6181 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
6184 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
6185 return DAG.getMergeValues(Ops, 2);
6189 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6191 The rounding mode is in bits 11:10 of FPSR, and has the following
6198 FLT_ROUNDS, on the other hand, expects the following:
6205 To perform the conversion, we do:
6206 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6209 MachineFunction &MF = DAG.getMachineFunction();
6210 const TargetMachine &TM = MF.getTarget();
6211 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6212 unsigned StackAlignment = TFI.getStackAlignment();
6213 MVT VT = Op.getValueType();
6215 // Save FP Control Word to stack slot
6216 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6217 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6219 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
6220 DAG.getEntryNode(), StackSlot);
6222 // Load FP Control Word from stack slot
6223 SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
6225 // Transform as necessary
6227 DAG.getNode(ISD::SRL, MVT::i16,
6228 DAG.getNode(ISD::AND, MVT::i16,
6229 CWD, DAG.getConstant(0x800, MVT::i16)),
6230 DAG.getConstant(11, MVT::i8));
6232 DAG.getNode(ISD::SRL, MVT::i16,
6233 DAG.getNode(ISD::AND, MVT::i16,
6234 CWD, DAG.getConstant(0x400, MVT::i16)),
6235 DAG.getConstant(9, MVT::i8));
6238 DAG.getNode(ISD::AND, MVT::i16,
6239 DAG.getNode(ISD::ADD, MVT::i16,
6240 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
6241 DAG.getConstant(1, MVT::i16)),
6242 DAG.getConstant(3, MVT::i16));
6245 return DAG.getNode((VT.getSizeInBits() < 16 ?
6246 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
6249 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6250 MVT VT = Op.getValueType();
6252 unsigned NumBits = VT.getSizeInBits();
6254 Op = Op.getOperand(0);
6255 if (VT == MVT::i8) {
6256 // Zero extend to i32 since there is not an i8 bsr.
6258 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6261 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6262 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6263 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
6265 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6266 SmallVector<SDValue, 4> Ops;
6268 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6269 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6270 Ops.push_back(Op.getValue(1));
6271 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6273 // Finally xor with NumBits-1.
6274 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6277 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6281 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6282 MVT VT = Op.getValueType();
6284 unsigned NumBits = VT.getSizeInBits();
6286 Op = Op.getOperand(0);
6287 if (VT == MVT::i8) {
6289 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6292 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6293 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6294 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
6296 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6297 SmallVector<SDValue, 4> Ops;
6299 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6300 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6301 Ops.push_back(Op.getValue(1));
6302 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6305 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6309 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6310 MVT VT = Op.getValueType();
6311 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6313 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6314 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6315 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6316 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6317 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6319 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6320 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6321 // return AloBlo + AloBhi + AhiBlo;
6323 SDValue A = Op.getOperand(0);
6324 SDValue B = Op.getOperand(1);
6326 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6327 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6328 A, DAG.getConstant(32, MVT::i32));
6329 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6330 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6331 B, DAG.getConstant(32, MVT::i32));
6332 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6333 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6335 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6336 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6338 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6339 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6341 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6342 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6343 AloBhi, DAG.getConstant(32, MVT::i32));
6344 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6345 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6346 AhiBlo, DAG.getConstant(32, MVT::i32));
6347 SDValue Res = DAG.getNode(ISD::ADD, VT, AloBlo, AloBhi);
6348 Res = DAG.getNode(ISD::ADD, VT, Res, AhiBlo);
6353 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6354 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6355 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6356 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6357 // has only one use.
6358 SDNode *N = Op.getNode();
6359 SDValue LHS = N->getOperand(0);
6360 SDValue RHS = N->getOperand(1);
6361 unsigned BaseOp = 0;
6364 switch (Op.getOpcode()) {
6365 default: assert(0 && "Unknown ovf instruction!");
6367 BaseOp = X86ISD::ADD;
6371 BaseOp = X86ISD::ADD;
6375 BaseOp = X86ISD::SUB;
6379 BaseOp = X86ISD::SUB;
6383 BaseOp = X86ISD::SMUL;
6387 BaseOp = X86ISD::UMUL;
6392 // Also sets EFLAGS.
6393 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6394 SDValue Sum = DAG.getNode(BaseOp, VTs, LHS, RHS);
6397 DAG.getNode(X86ISD::SETCC, N->getValueType(1),
6398 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6400 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6404 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6405 MVT T = Op.getValueType();
6408 switch(T.getSimpleVT()) {
6410 assert(false && "Invalid value type!");
6411 case MVT::i8: Reg = X86::AL; size = 1; break;
6412 case MVT::i16: Reg = X86::AX; size = 2; break;
6413 case MVT::i32: Reg = X86::EAX; size = 4; break;
6415 assert(Subtarget->is64Bit() && "Node not type legal!");
6416 Reg = X86::RAX; size = 8;
6419 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
6420 Op.getOperand(2), SDValue());
6421 SDValue Ops[] = { cpIn.getValue(0),
6424 DAG.getTargetConstant(size, MVT::i8),
6426 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6427 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
6429 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
6433 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6434 SelectionDAG &DAG) {
6435 assert(Subtarget->is64Bit() && "Result not type legalized?");
6436 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6437 SDValue TheChain = Op.getOperand(0);
6438 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
6439 SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
6440 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX, MVT::i64,
6442 SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
6443 DAG.getConstant(32, MVT::i8));
6445 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp),
6448 return DAG.getMergeValues(Ops, 2);
6451 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6452 SDNode *Node = Op.getNode();
6453 MVT T = Node->getValueType(0);
6454 SDValue negOp = DAG.getNode(ISD::SUB, T,
6455 DAG.getConstant(0, T), Node->getOperand(2));
6456 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD,
6457 cast<AtomicSDNode>(Node)->getMemoryVT(),
6458 Node->getOperand(0),
6459 Node->getOperand(1), negOp,
6460 cast<AtomicSDNode>(Node)->getSrcValue(),
6461 cast<AtomicSDNode>(Node)->getAlignment());
6464 /// LowerOperation - Provide custom lowering hooks for some operations.
6466 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6467 switch (Op.getOpcode()) {
6468 default: assert(0 && "Should not custom lower this!");
6469 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6470 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6471 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6472 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6473 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6474 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6475 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6476 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6477 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6478 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6479 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6480 case ISD::SHL_PARTS:
6481 case ISD::SRA_PARTS:
6482 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6483 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6484 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6485 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6486 case ISD::FABS: return LowerFABS(Op, DAG);
6487 case ISD::FNEG: return LowerFNEG(Op, DAG);
6488 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6489 case ISD::SETCC: return LowerSETCC(Op, DAG);
6490 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6491 case ISD::SELECT: return LowerSELECT(Op, DAG);
6492 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6493 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6494 case ISD::CALL: return LowerCALL(Op, DAG);
6495 case ISD::RET: return LowerRET(Op, DAG);
6496 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6497 case ISD::VASTART: return LowerVASTART(Op, DAG);
6498 case ISD::VAARG: return LowerVAARG(Op, DAG);
6499 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6500 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6501 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6502 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6503 case ISD::FRAME_TO_ARGS_OFFSET:
6504 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6505 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6506 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6507 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6508 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6509 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6510 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6511 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6517 case ISD::UMULO: return LowerXALUO(Op, DAG);
6518 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6522 void X86TargetLowering::
6523 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6524 SelectionDAG &DAG, unsigned NewOp) {
6525 MVT T = Node->getValueType(0);
6526 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6528 SDValue Chain = Node->getOperand(0);
6529 SDValue In1 = Node->getOperand(1);
6530 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6531 Node->getOperand(2), DAG.getIntPtrConstant(0));
6532 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6533 Node->getOperand(2), DAG.getIntPtrConstant(1));
6534 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6535 // have a MemOperand. Pass the info through as a normal operand.
6536 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6537 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6538 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6539 SDValue Result = DAG.getNode(NewOp, Tys, Ops, 5);
6540 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6541 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2));
6542 Results.push_back(Result.getValue(2));
6545 /// ReplaceNodeResults - Replace a node with an illegal result type
6546 /// with a new node built out of custom code.
6547 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6548 SmallVectorImpl<SDValue>&Results,
6549 SelectionDAG &DAG) {
6550 switch (N->getOpcode()) {
6552 assert(false && "Do not know how to custom type legalize this operation!");
6554 case ISD::FP_TO_SINT: {
6555 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
6556 SDValue FIST = Vals.first, StackSlot = Vals.second;
6557 if (FIST.getNode() != 0) {
6558 MVT VT = N->getValueType(0);
6559 // Return a load from the stack slot.
6560 Results.push_back(DAG.getLoad(VT, FIST, StackSlot, NULL, 0));
6564 case ISD::READCYCLECOUNTER: {
6565 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6566 SDValue TheChain = N->getOperand(0);
6567 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
6568 SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
6569 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX, MVT::i32,
6571 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6572 SDValue Ops[] = { eax, edx };
6573 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2));
6574 Results.push_back(edx.getValue(1));
6577 case ISD::ATOMIC_CMP_SWAP: {
6578 MVT T = N->getValueType(0);
6579 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6580 SDValue cpInL, cpInH;
6581 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(2),
6582 DAG.getConstant(0, MVT::i32));
6583 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(2),
6584 DAG.getConstant(1, MVT::i32));
6585 cpInL = DAG.getCopyToReg(N->getOperand(0), X86::EAX, cpInL, SDValue());
6586 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX, cpInH,
6588 SDValue swapInL, swapInH;
6589 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(3),
6590 DAG.getConstant(0, MVT::i32));
6591 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(3),
6592 DAG.getConstant(1, MVT::i32));
6593 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX, swapInL,
6595 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX, swapInH,
6596 swapInL.getValue(1));
6597 SDValue Ops[] = { swapInH.getValue(0),
6599 swapInH.getValue(1) };
6600 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6601 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
6602 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
6603 Result.getValue(1));
6604 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
6605 cpOutL.getValue(2));
6606 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6607 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2));
6608 Results.push_back(cpOutH.getValue(1));
6611 case ISD::ATOMIC_LOAD_ADD:
6612 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6614 case ISD::ATOMIC_LOAD_AND:
6615 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6617 case ISD::ATOMIC_LOAD_NAND:
6618 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6620 case ISD::ATOMIC_LOAD_OR:
6621 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6623 case ISD::ATOMIC_LOAD_SUB:
6624 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6626 case ISD::ATOMIC_LOAD_XOR:
6627 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6629 case ISD::ATOMIC_SWAP:
6630 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6635 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6637 default: return NULL;
6638 case X86ISD::BSF: return "X86ISD::BSF";
6639 case X86ISD::BSR: return "X86ISD::BSR";
6640 case X86ISD::SHLD: return "X86ISD::SHLD";
6641 case X86ISD::SHRD: return "X86ISD::SHRD";
6642 case X86ISD::FAND: return "X86ISD::FAND";
6643 case X86ISD::FOR: return "X86ISD::FOR";
6644 case X86ISD::FXOR: return "X86ISD::FXOR";
6645 case X86ISD::FSRL: return "X86ISD::FSRL";
6646 case X86ISD::FILD: return "X86ISD::FILD";
6647 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6648 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6649 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6650 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6651 case X86ISD::FLD: return "X86ISD::FLD";
6652 case X86ISD::FST: return "X86ISD::FST";
6653 case X86ISD::CALL: return "X86ISD::CALL";
6654 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6655 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6656 case X86ISD::BT: return "X86ISD::BT";
6657 case X86ISD::CMP: return "X86ISD::CMP";
6658 case X86ISD::COMI: return "X86ISD::COMI";
6659 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6660 case X86ISD::SETCC: return "X86ISD::SETCC";
6661 case X86ISD::CMOV: return "X86ISD::CMOV";
6662 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6663 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6664 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6665 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6666 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6667 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6668 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6669 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6670 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6671 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6672 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6673 case X86ISD::FMAX: return "X86ISD::FMAX";
6674 case X86ISD::FMIN: return "X86ISD::FMIN";
6675 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6676 case X86ISD::FRCP: return "X86ISD::FRCP";
6677 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6678 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6679 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6680 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6681 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6682 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6683 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6684 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6685 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6686 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6687 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6688 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6689 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6690 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6691 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6692 case X86ISD::VSHL: return "X86ISD::VSHL";
6693 case X86ISD::VSRL: return "X86ISD::VSRL";
6694 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6695 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6696 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6697 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6698 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6699 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6700 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6701 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6702 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6703 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6704 case X86ISD::ADD: return "X86ISD::ADD";
6705 case X86ISD::SUB: return "X86ISD::SUB";
6706 case X86ISD::SMUL: return "X86ISD::SMUL";
6707 case X86ISD::UMUL: return "X86ISD::UMUL";
6711 // isLegalAddressingMode - Return true if the addressing mode represented
6712 // by AM is legal for this target, for a load/store of the specified type.
6713 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6714 const Type *Ty) const {
6715 // X86 supports extremely general addressing modes.
6717 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6718 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6722 // We can only fold this if we don't need an extra load.
6723 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6725 // If BaseGV requires a register, we cannot also have a BaseReg.
6726 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6730 // X86-64 only supports addr of globals in small code model.
6731 if (Subtarget->is64Bit()) {
6732 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6734 // If lower 4G is not available, then we must use rip-relative addressing.
6735 if (AM.BaseOffs || AM.Scale > 1)
6746 // These scales always work.
6751 // These scales are formed with basereg+scalereg. Only accept if there is
6756 default: // Other stuff never works.
6764 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6765 if (!Ty1->isInteger() || !Ty2->isInteger())
6767 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6768 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6769 if (NumBits1 <= NumBits2)
6771 return Subtarget->is64Bit() || NumBits1 < 64;
6774 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6775 if (!VT1.isInteger() || !VT2.isInteger())
6777 unsigned NumBits1 = VT1.getSizeInBits();
6778 unsigned NumBits2 = VT2.getSizeInBits();
6779 if (NumBits1 <= NumBits2)
6781 return Subtarget->is64Bit() || NumBits1 < 64;
6784 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6785 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6786 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6787 /// are assumed to be legal.
6789 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6790 // Only do shuffles on 128-bit vector types for now.
6791 if (VT.getSizeInBits() == 64) return false;
6792 return (Mask.getNode()->getNumOperands() <= 4 ||
6793 isIdentityMask(Mask.getNode()) ||
6794 isIdentityMask(Mask.getNode(), true) ||
6795 isSplatMask(Mask.getNode()) ||
6796 isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6797 X86::isUNPCKLMask(Mask.getNode()) ||
6798 X86::isUNPCKHMask(Mask.getNode()) ||
6799 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6800 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6804 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6805 MVT EVT, SelectionDAG &DAG) const {
6806 unsigned NumElts = BVOps.size();
6807 // Only do shuffles on 128-bit vector types for now.
6808 if (EVT.getSizeInBits() * NumElts == 64) return false;
6809 if (NumElts == 2) return true;
6811 return (isMOVLMask(&BVOps[0], 4) ||
6812 isCommutedMOVL(&BVOps[0], 4, true) ||
6813 isSHUFPMask(&BVOps[0], 4) ||
6814 isCommutedSHUFP(&BVOps[0], 4));
6819 //===----------------------------------------------------------------------===//
6820 // X86 Scheduler Hooks
6821 //===----------------------------------------------------------------------===//
6823 // private utility function
6825 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6826 MachineBasicBlock *MBB,
6834 TargetRegisterClass *RC,
6836 // For the atomic bitwise operator, we generate
6839 // ld t1 = [bitinstr.addr]
6840 // op t2 = t1, [bitinstr.val]
6842 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6844 // fallthrough -->nextMBB
6845 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6846 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6847 MachineFunction::iterator MBBIter = MBB;
6850 /// First build the CFG
6851 MachineFunction *F = MBB->getParent();
6852 MachineBasicBlock *thisMBB = MBB;
6853 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6854 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6855 F->insert(MBBIter, newMBB);
6856 F->insert(MBBIter, nextMBB);
6858 // Move all successors to thisMBB to nextMBB
6859 nextMBB->transferSuccessors(thisMBB);
6861 // Update thisMBB to fall through to newMBB
6862 thisMBB->addSuccessor(newMBB);
6864 // newMBB jumps to itself and fall through to nextMBB
6865 newMBB->addSuccessor(nextMBB);
6866 newMBB->addSuccessor(newMBB);
6868 // Insert instructions into newMBB based on incoming instruction
6869 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6870 MachineOperand& destOper = bInstr->getOperand(0);
6871 MachineOperand* argOpers[6];
6872 int numArgs = bInstr->getNumOperands() - 1;
6873 for (int i=0; i < numArgs; ++i)
6874 argOpers[i] = &bInstr->getOperand(i+1);
6876 // x86 address has 4 operands: base, index, scale, and displacement
6877 int lastAddrIndx = 3; // [0,3]
6880 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6881 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
6882 for (int i=0; i <= lastAddrIndx; ++i)
6883 (*MIB).addOperand(*argOpers[i]);
6885 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6887 MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
6892 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6893 assert((argOpers[valArgIndx]->isReg() ||
6894 argOpers[valArgIndx]->isImm()) &&
6896 if (argOpers[valArgIndx]->isReg())
6897 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6899 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6901 (*MIB).addOperand(*argOpers[valArgIndx]);
6903 MIB = BuildMI(newMBB, TII->get(copyOpc), EAXreg);
6906 MIB = BuildMI(newMBB, TII->get(CXchgOpc));
6907 for (int i=0; i <= lastAddrIndx; ++i)
6908 (*MIB).addOperand(*argOpers[i]);
6910 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6911 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6913 MIB = BuildMI(newMBB, TII->get(copyOpc), destOper.getReg());
6917 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6919 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
6923 // private utility function: 64 bit atomics on 32 bit host.
6925 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
6926 MachineBasicBlock *MBB,
6932 // For the atomic bitwise operator, we generate
6933 // thisMBB (instructions are in pairs, except cmpxchg8b)
6934 // ld t1,t2 = [bitinstr.addr]
6936 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
6937 // op t5, t6 <- out1, out2, [bitinstr.val]
6938 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
6939 // mov ECX, EBX <- t5, t6
6940 // mov EAX, EDX <- t1, t2
6941 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
6942 // mov t3, t4 <- EAX, EDX
6944 // result in out1, out2
6945 // fallthrough -->nextMBB
6947 const TargetRegisterClass *RC = X86::GR32RegisterClass;
6948 const unsigned LoadOpc = X86::MOV32rm;
6949 const unsigned copyOpc = X86::MOV32rr;
6950 const unsigned NotOpc = X86::NOT32r;
6951 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6952 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6953 MachineFunction::iterator MBBIter = MBB;
6956 /// First build the CFG
6957 MachineFunction *F = MBB->getParent();
6958 MachineBasicBlock *thisMBB = MBB;
6959 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6960 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6961 F->insert(MBBIter, newMBB);
6962 F->insert(MBBIter, nextMBB);
6964 // Move all successors to thisMBB to nextMBB
6965 nextMBB->transferSuccessors(thisMBB);
6967 // Update thisMBB to fall through to newMBB
6968 thisMBB->addSuccessor(newMBB);
6970 // newMBB jumps to itself and fall through to nextMBB
6971 newMBB->addSuccessor(nextMBB);
6972 newMBB->addSuccessor(newMBB);
6974 // Insert instructions into newMBB based on incoming instruction
6975 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
6976 assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
6977 MachineOperand& dest1Oper = bInstr->getOperand(0);
6978 MachineOperand& dest2Oper = bInstr->getOperand(1);
6979 MachineOperand* argOpers[6];
6980 for (int i=0; i < 6; ++i)
6981 argOpers[i] = &bInstr->getOperand(i+2);
6983 // x86 address has 4 operands: base, index, scale, and displacement
6984 int lastAddrIndx = 3; // [0,3]
6986 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6987 MachineInstrBuilder MIB = BuildMI(thisMBB, TII->get(LoadOpc), t1);
6988 for (int i=0; i <= lastAddrIndx; ++i)
6989 (*MIB).addOperand(*argOpers[i]);
6990 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6991 MIB = BuildMI(thisMBB, TII->get(LoadOpc), t2);
6992 // add 4 to displacement.
6993 for (int i=0; i <= lastAddrIndx-1; ++i)
6994 (*MIB).addOperand(*argOpers[i]);
6995 MachineOperand newOp3 = *(argOpers[3]);
6997 newOp3.setImm(newOp3.getImm()+4);
6999 newOp3.setOffset(newOp3.getOffset()+4);
7000 (*MIB).addOperand(newOp3);
7002 // t3/4 are defined later, at the bottom of the loop
7003 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7004 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7005 BuildMI(newMBB, TII->get(X86::PHI), dest1Oper.getReg())
7006 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7007 BuildMI(newMBB, TII->get(X86::PHI), dest2Oper.getReg())
7008 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7010 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7011 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7013 MIB = BuildMI(newMBB, TII->get(NotOpc), tt1).addReg(t1);
7014 MIB = BuildMI(newMBB, TII->get(NotOpc), tt2).addReg(t2);
7020 assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
7022 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7023 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7024 if (argOpers[4]->isReg())
7025 MIB = BuildMI(newMBB, TII->get(regOpcL), t5);
7027 MIB = BuildMI(newMBB, TII->get(immOpcL), t5);
7028 if (regOpcL != X86::MOV32rr)
7030 (*MIB).addOperand(*argOpers[4]);
7031 assert(argOpers[5]->isReg() == argOpers[4]->isReg());
7032 assert(argOpers[5]->isImm() == argOpers[4]->isImm());
7033 if (argOpers[5]->isReg())
7034 MIB = BuildMI(newMBB, TII->get(regOpcH), t6);
7036 MIB = BuildMI(newMBB, TII->get(immOpcH), t6);
7037 if (regOpcH != X86::MOV32rr)
7039 (*MIB).addOperand(*argOpers[5]);
7041 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EAX);
7043 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EDX);
7046 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EBX);
7048 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::ECX);
7051 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG8B));
7052 for (int i=0; i <= lastAddrIndx; ++i)
7053 (*MIB).addOperand(*argOpers[i]);
7055 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7056 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7058 MIB = BuildMI(newMBB, TII->get(copyOpc), t3);
7059 MIB.addReg(X86::EAX);
7060 MIB = BuildMI(newMBB, TII->get(copyOpc), t4);
7061 MIB.addReg(X86::EDX);
7064 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
7066 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7070 // private utility function
7072 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7073 MachineBasicBlock *MBB,
7075 // For the atomic min/max operator, we generate
7078 // ld t1 = [min/max.addr]
7079 // mov t2 = [min/max.val]
7081 // cmov[cond] t2 = t1
7083 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7085 // fallthrough -->nextMBB
7087 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7088 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7089 MachineFunction::iterator MBBIter = MBB;
7092 /// First build the CFG
7093 MachineFunction *F = MBB->getParent();
7094 MachineBasicBlock *thisMBB = MBB;
7095 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7096 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7097 F->insert(MBBIter, newMBB);
7098 F->insert(MBBIter, nextMBB);
7100 // Move all successors to thisMBB to nextMBB
7101 nextMBB->transferSuccessors(thisMBB);
7103 // Update thisMBB to fall through to newMBB
7104 thisMBB->addSuccessor(newMBB);
7106 // newMBB jumps to newMBB and fall through to nextMBB
7107 newMBB->addSuccessor(nextMBB);
7108 newMBB->addSuccessor(newMBB);
7110 // Insert instructions into newMBB based on incoming instruction
7111 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
7112 MachineOperand& destOper = mInstr->getOperand(0);
7113 MachineOperand* argOpers[6];
7114 int numArgs = mInstr->getNumOperands() - 1;
7115 for (int i=0; i < numArgs; ++i)
7116 argOpers[i] = &mInstr->getOperand(i+1);
7118 // x86 address has 4 operands: base, index, scale, and displacement
7119 int lastAddrIndx = 3; // [0,3]
7122 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7123 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
7124 for (int i=0; i <= lastAddrIndx; ++i)
7125 (*MIB).addOperand(*argOpers[i]);
7127 // We only support register and immediate values
7128 assert((argOpers[valArgIndx]->isReg() ||
7129 argOpers[valArgIndx]->isImm()) &&
7132 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7133 if (argOpers[valArgIndx]->isReg())
7134 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
7136 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
7137 (*MIB).addOperand(*argOpers[valArgIndx]);
7139 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
7142 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
7147 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7148 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
7152 // Cmp and exchange if none has modified the memory location
7153 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
7154 for (int i=0; i <= lastAddrIndx; ++i)
7155 (*MIB).addOperand(*argOpers[i]);
7157 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7158 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7160 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
7161 MIB.addReg(X86::EAX);
7164 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
7166 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7172 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7173 MachineBasicBlock *BB) {
7174 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7175 switch (MI->getOpcode()) {
7176 default: assert(false && "Unexpected instr type to insert");
7177 case X86::CMOV_V1I64:
7178 case X86::CMOV_FR32:
7179 case X86::CMOV_FR64:
7180 case X86::CMOV_V4F32:
7181 case X86::CMOV_V2F64:
7182 case X86::CMOV_V2I64: {
7183 // To "insert" a SELECT_CC instruction, we actually have to insert the
7184 // diamond control-flow pattern. The incoming instruction knows the
7185 // destination vreg to set, the condition code register to branch on, the
7186 // true/false values to select between, and a branch opcode to use.
7187 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7188 MachineFunction::iterator It = BB;
7194 // cmpTY ccX, r1, r2
7196 // fallthrough --> copy0MBB
7197 MachineBasicBlock *thisMBB = BB;
7198 MachineFunction *F = BB->getParent();
7199 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7200 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7202 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7203 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
7204 F->insert(It, copy0MBB);
7205 F->insert(It, sinkMBB);
7206 // Update machine-CFG edges by transferring all successors of the current
7207 // block to the new block which will contain the Phi node for the select.
7208 sinkMBB->transferSuccessors(BB);
7210 // Add the true and fallthrough blocks as its successors.
7211 BB->addSuccessor(copy0MBB);
7212 BB->addSuccessor(sinkMBB);
7215 // %FalseValue = ...
7216 // # fallthrough to sinkMBB
7219 // Update machine-CFG edges
7220 BB->addSuccessor(sinkMBB);
7223 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7226 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
7227 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7228 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7230 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7234 case X86::FP32_TO_INT16_IN_MEM:
7235 case X86::FP32_TO_INT32_IN_MEM:
7236 case X86::FP32_TO_INT64_IN_MEM:
7237 case X86::FP64_TO_INT16_IN_MEM:
7238 case X86::FP64_TO_INT32_IN_MEM:
7239 case X86::FP64_TO_INT64_IN_MEM:
7240 case X86::FP80_TO_INT16_IN_MEM:
7241 case X86::FP80_TO_INT32_IN_MEM:
7242 case X86::FP80_TO_INT64_IN_MEM: {
7243 // Change the floating point control register to use "round towards zero"
7244 // mode when truncating to an integer value.
7245 MachineFunction *F = BB->getParent();
7246 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7247 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7249 // Load the old value of the high byte of the control word...
7251 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7252 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
7254 // Set the high part to be round to zero...
7255 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
7258 // Reload the modified control word now...
7259 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
7261 // Restore the memory image of control word to original value
7262 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
7265 // Get the X86 opcode to use.
7267 switch (MI->getOpcode()) {
7268 default: assert(0 && "illegal opcode!");
7269 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7270 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7271 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7272 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7273 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7274 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7275 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7276 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7277 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7281 MachineOperand &Op = MI->getOperand(0);
7283 AM.BaseType = X86AddressMode::RegBase;
7284 AM.Base.Reg = Op.getReg();
7286 AM.BaseType = X86AddressMode::FrameIndexBase;
7287 AM.Base.FrameIndex = Op.getIndex();
7289 Op = MI->getOperand(1);
7291 AM.Scale = Op.getImm();
7292 Op = MI->getOperand(2);
7294 AM.IndexReg = Op.getImm();
7295 Op = MI->getOperand(3);
7296 if (Op.isGlobal()) {
7297 AM.GV = Op.getGlobal();
7299 AM.Disp = Op.getImm();
7301 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
7302 .addReg(MI->getOperand(4).getReg());
7304 // Reload the original control word now.
7305 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
7307 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7310 case X86::ATOMAND32:
7311 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7312 X86::AND32ri, X86::MOV32rm,
7313 X86::LCMPXCHG32, X86::MOV32rr,
7314 X86::NOT32r, X86::EAX,
7315 X86::GR32RegisterClass);
7317 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7318 X86::OR32ri, X86::MOV32rm,
7319 X86::LCMPXCHG32, X86::MOV32rr,
7320 X86::NOT32r, X86::EAX,
7321 X86::GR32RegisterClass);
7322 case X86::ATOMXOR32:
7323 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7324 X86::XOR32ri, X86::MOV32rm,
7325 X86::LCMPXCHG32, X86::MOV32rr,
7326 X86::NOT32r, X86::EAX,
7327 X86::GR32RegisterClass);
7328 case X86::ATOMNAND32:
7329 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7330 X86::AND32ri, X86::MOV32rm,
7331 X86::LCMPXCHG32, X86::MOV32rr,
7332 X86::NOT32r, X86::EAX,
7333 X86::GR32RegisterClass, true);
7334 case X86::ATOMMIN32:
7335 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7336 case X86::ATOMMAX32:
7337 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7338 case X86::ATOMUMIN32:
7339 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7340 case X86::ATOMUMAX32:
7341 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7343 case X86::ATOMAND16:
7344 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7345 X86::AND16ri, X86::MOV16rm,
7346 X86::LCMPXCHG16, X86::MOV16rr,
7347 X86::NOT16r, X86::AX,
7348 X86::GR16RegisterClass);
7350 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7351 X86::OR16ri, X86::MOV16rm,
7352 X86::LCMPXCHG16, X86::MOV16rr,
7353 X86::NOT16r, X86::AX,
7354 X86::GR16RegisterClass);
7355 case X86::ATOMXOR16:
7356 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7357 X86::XOR16ri, X86::MOV16rm,
7358 X86::LCMPXCHG16, X86::MOV16rr,
7359 X86::NOT16r, X86::AX,
7360 X86::GR16RegisterClass);
7361 case X86::ATOMNAND16:
7362 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7363 X86::AND16ri, X86::MOV16rm,
7364 X86::LCMPXCHG16, X86::MOV16rr,
7365 X86::NOT16r, X86::AX,
7366 X86::GR16RegisterClass, true);
7367 case X86::ATOMMIN16:
7368 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7369 case X86::ATOMMAX16:
7370 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7371 case X86::ATOMUMIN16:
7372 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7373 case X86::ATOMUMAX16:
7374 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7377 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7378 X86::AND8ri, X86::MOV8rm,
7379 X86::LCMPXCHG8, X86::MOV8rr,
7380 X86::NOT8r, X86::AL,
7381 X86::GR8RegisterClass);
7383 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7384 X86::OR8ri, X86::MOV8rm,
7385 X86::LCMPXCHG8, X86::MOV8rr,
7386 X86::NOT8r, X86::AL,
7387 X86::GR8RegisterClass);
7389 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7390 X86::XOR8ri, X86::MOV8rm,
7391 X86::LCMPXCHG8, X86::MOV8rr,
7392 X86::NOT8r, X86::AL,
7393 X86::GR8RegisterClass);
7394 case X86::ATOMNAND8:
7395 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7396 X86::AND8ri, X86::MOV8rm,
7397 X86::LCMPXCHG8, X86::MOV8rr,
7398 X86::NOT8r, X86::AL,
7399 X86::GR8RegisterClass, true);
7400 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7401 // This group is for 64-bit host.
7402 case X86::ATOMAND64:
7403 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7404 X86::AND64ri32, X86::MOV64rm,
7405 X86::LCMPXCHG64, X86::MOV64rr,
7406 X86::NOT64r, X86::RAX,
7407 X86::GR64RegisterClass);
7409 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7410 X86::OR64ri32, X86::MOV64rm,
7411 X86::LCMPXCHG64, X86::MOV64rr,
7412 X86::NOT64r, X86::RAX,
7413 X86::GR64RegisterClass);
7414 case X86::ATOMXOR64:
7415 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7416 X86::XOR64ri32, X86::MOV64rm,
7417 X86::LCMPXCHG64, X86::MOV64rr,
7418 X86::NOT64r, X86::RAX,
7419 X86::GR64RegisterClass);
7420 case X86::ATOMNAND64:
7421 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7422 X86::AND64ri32, X86::MOV64rm,
7423 X86::LCMPXCHG64, X86::MOV64rr,
7424 X86::NOT64r, X86::RAX,
7425 X86::GR64RegisterClass, true);
7426 case X86::ATOMMIN64:
7427 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7428 case X86::ATOMMAX64:
7429 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7430 case X86::ATOMUMIN64:
7431 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7432 case X86::ATOMUMAX64:
7433 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7435 // This group does 64-bit operations on a 32-bit host.
7436 case X86::ATOMAND6432:
7437 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7438 X86::AND32rr, X86::AND32rr,
7439 X86::AND32ri, X86::AND32ri,
7441 case X86::ATOMOR6432:
7442 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7443 X86::OR32rr, X86::OR32rr,
7444 X86::OR32ri, X86::OR32ri,
7446 case X86::ATOMXOR6432:
7447 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7448 X86::XOR32rr, X86::XOR32rr,
7449 X86::XOR32ri, X86::XOR32ri,
7451 case X86::ATOMNAND6432:
7452 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7453 X86::AND32rr, X86::AND32rr,
7454 X86::AND32ri, X86::AND32ri,
7456 case X86::ATOMADD6432:
7457 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7458 X86::ADD32rr, X86::ADC32rr,
7459 X86::ADD32ri, X86::ADC32ri,
7461 case X86::ATOMSUB6432:
7462 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7463 X86::SUB32rr, X86::SBB32rr,
7464 X86::SUB32ri, X86::SBB32ri,
7466 case X86::ATOMSWAP6432:
7467 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7468 X86::MOV32rr, X86::MOV32rr,
7469 X86::MOV32ri, X86::MOV32ri,
7474 //===----------------------------------------------------------------------===//
7475 // X86 Optimization Hooks
7476 //===----------------------------------------------------------------------===//
7478 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7482 const SelectionDAG &DAG,
7483 unsigned Depth) const {
7484 unsigned Opc = Op.getOpcode();
7485 assert((Opc >= ISD::BUILTIN_OP_END ||
7486 Opc == ISD::INTRINSIC_WO_CHAIN ||
7487 Opc == ISD::INTRINSIC_W_CHAIN ||
7488 Opc == ISD::INTRINSIC_VOID) &&
7489 "Should use MaskedValueIsZero if you don't know whether Op"
7490 " is a target node!");
7492 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7496 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7497 Mask.getBitWidth() - 1);
7502 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7503 /// node is a GlobalAddress + offset.
7504 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7505 GlobalValue* &GA, int64_t &Offset) const{
7506 if (N->getOpcode() == X86ISD::Wrapper) {
7507 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7508 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7509 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7513 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7516 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7517 const TargetLowering &TLI) {
7520 if (TLI.isGAPlusOffset(Base, GV, Offset))
7521 return (GV->getAlignment() >= N && (Offset % N) == 0);
7522 // DAG combine handles the stack object case.
7526 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
7527 unsigned NumElems, MVT EVT,
7529 SelectionDAG &DAG, MachineFrameInfo *MFI,
7530 const TargetLowering &TLI) {
7532 for (unsigned i = 0; i < NumElems; ++i) {
7533 SDValue Idx = PermMask.getOperand(i);
7534 if (Idx.getOpcode() == ISD::UNDEF) {
7540 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7541 if (!Elt.getNode() ||
7542 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7545 Base = Elt.getNode();
7546 if (Base->getOpcode() == ISD::UNDEF)
7550 if (Elt.getOpcode() == ISD::UNDEF)
7553 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7554 EVT.getSizeInBits()/8, i, MFI))
7560 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7561 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7562 /// if the load addresses are consecutive, non-overlapping, and in the right
7564 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7565 const TargetLowering &TLI) {
7566 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7567 MVT VT = N->getValueType(0);
7568 MVT EVT = VT.getVectorElementType();
7569 SDValue PermMask = N->getOperand(2);
7570 unsigned NumElems = PermMask.getNumOperands();
7571 SDNode *Base = NULL;
7572 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
7576 LoadSDNode *LD = cast<LoadSDNode>(Base);
7577 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7578 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7579 LD->getSrcValueOffset(), LD->isVolatile());
7580 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7581 LD->getSrcValueOffset(), LD->isVolatile(),
7582 LD->getAlignment());
7585 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7586 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7587 TargetLowering::DAGCombinerInfo &DCI,
7588 const X86Subtarget *Subtarget,
7589 const TargetLowering &TLI) {
7590 unsigned NumOps = N->getNumOperands();
7592 // Ignore single operand BUILD_VECTOR.
7596 MVT VT = N->getValueType(0);
7597 MVT EVT = VT.getVectorElementType();
7598 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7599 // We are looking for load i64 and zero extend. We want to transform
7600 // it before legalizer has a chance to expand it. Also look for i64
7601 // BUILD_PAIR bit casted to f64.
7603 // This must be an insertion into a zero vector.
7604 SDValue HighElt = N->getOperand(1);
7605 if (!isZeroNode(HighElt))
7608 // Value must be a load.
7609 SDNode *Base = N->getOperand(0).getNode();
7610 if (!isa<LoadSDNode>(Base)) {
7611 if (Base->getOpcode() != ISD::BIT_CONVERT)
7613 Base = Base->getOperand(0).getNode();
7614 if (!isa<LoadSDNode>(Base))
7618 // Transform it into VZEXT_LOAD addr.
7619 LoadSDNode *LD = cast<LoadSDNode>(Base);
7621 // Load must not be an extload.
7622 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7625 // Load type should legal type so we don't have to legalize it.
7626 if (!TLI.isTypeLegal(VT))
7629 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7630 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7631 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, Tys, Ops, 2);
7632 TargetLowering::TargetLoweringOpt TLO(DAG);
7633 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
7634 DCI.CommitTargetLoweringOpt(TLO);
7638 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7639 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7640 const X86Subtarget *Subtarget) {
7641 SDValue Cond = N->getOperand(0);
7643 // If we have SSE[12] support, try to form min/max nodes.
7644 if (Subtarget->hasSSE2() &&
7645 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
7646 if (Cond.getOpcode() == ISD::SETCC) {
7647 // Get the LHS/RHS of the select.
7648 SDValue LHS = N->getOperand(1);
7649 SDValue RHS = N->getOperand(2);
7650 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7652 unsigned Opcode = 0;
7653 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7656 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7659 if (!UnsafeFPMath) break;
7661 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7663 Opcode = X86ISD::FMIN;
7666 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7669 if (!UnsafeFPMath) break;
7671 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7673 Opcode = X86ISD::FMAX;
7676 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7679 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7682 if (!UnsafeFPMath) break;
7684 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7686 Opcode = X86ISD::FMIN;
7689 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7692 if (!UnsafeFPMath) break;
7694 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7696 Opcode = X86ISD::FMAX;
7702 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
7710 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
7712 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
7713 const X86Subtarget *Subtarget) {
7714 // On X86 with SSE2 support, we can transform this to a vector shift if
7715 // all elements are shifted by the same amount. We can't do this in legalize
7716 // because the a constant vector is typically transformed to a constant pool
7717 // so we have no knowledge of the shift amount.
7718 if (!Subtarget->hasSSE2())
7721 MVT VT = N->getValueType(0);
7722 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
7725 SDValue ShAmtOp = N->getOperand(1);
7726 MVT EltVT = VT.getVectorElementType();
7728 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
7729 unsigned NumElts = VT.getVectorNumElements();
7731 for (; i != NumElts; ++i) {
7732 SDValue Arg = ShAmtOp.getOperand(i);
7733 if (Arg.getOpcode() == ISD::UNDEF) continue;
7737 for (; i != NumElts; ++i) {
7738 SDValue Arg = ShAmtOp.getOperand(i);
7739 if (Arg.getOpcode() == ISD::UNDEF) continue;
7740 if (Arg != BaseShAmt) {
7744 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
7745 isSplatMask(ShAmtOp.getOperand(2).getNode())) {
7746 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, ShAmtOp,
7747 DAG.getIntPtrConstant(0));
7751 if (EltVT.bitsGT(MVT::i32))
7752 BaseShAmt = DAG.getNode(ISD::TRUNCATE, MVT::i32, BaseShAmt);
7753 else if (EltVT.bitsLT(MVT::i32))
7754 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, BaseShAmt);
7756 // The shift amount is identical so we can do a vector shift.
7757 SDValue ValOp = N->getOperand(0);
7758 switch (N->getOpcode()) {
7760 assert(0 && "Unknown shift opcode!");
7763 if (VT == MVT::v2i64)
7764 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7765 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7767 if (VT == MVT::v4i32)
7768 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7769 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
7771 if (VT == MVT::v8i16)
7772 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7773 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
7777 if (VT == MVT::v4i32)
7778 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7779 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
7781 if (VT == MVT::v8i16)
7782 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7783 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
7787 if (VT == MVT::v2i64)
7788 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7789 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7791 if (VT == MVT::v4i32)
7792 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7793 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
7795 if (VT == MVT::v8i16)
7796 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7797 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
7804 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
7805 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
7806 const X86Subtarget *Subtarget) {
7807 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
7808 // the FP state in cases where an emms may be missing.
7809 // A preferable solution to the general problem is to figure out the right
7810 // places to insert EMMS. This qualifies as a quick hack.
7811 StoreSDNode *St = cast<StoreSDNode>(N);
7812 if (St->getValue().getValueType().isVector() &&
7813 St->getValue().getValueType().getSizeInBits() == 64 &&
7814 isa<LoadSDNode>(St->getValue()) &&
7815 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
7816 St->getChain().hasOneUse() && !St->isVolatile()) {
7817 SDNode* LdVal = St->getValue().getNode();
7819 int TokenFactorIndex = -1;
7820 SmallVector<SDValue, 8> Ops;
7821 SDNode* ChainVal = St->getChain().getNode();
7822 // Must be a store of a load. We currently handle two cases: the load
7823 // is a direct child, and it's under an intervening TokenFactor. It is
7824 // possible to dig deeper under nested TokenFactors.
7825 if (ChainVal == LdVal)
7826 Ld = cast<LoadSDNode>(St->getChain());
7827 else if (St->getValue().hasOneUse() &&
7828 ChainVal->getOpcode() == ISD::TokenFactor) {
7829 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
7830 if (ChainVal->getOperand(i).getNode() == LdVal) {
7831 TokenFactorIndex = i;
7832 Ld = cast<LoadSDNode>(St->getValue());
7834 Ops.push_back(ChainVal->getOperand(i));
7838 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
7839 if (Subtarget->is64Bit()) {
7840 SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
7841 Ld->getBasePtr(), Ld->getSrcValue(),
7842 Ld->getSrcValueOffset(), Ld->isVolatile(),
7843 Ld->getAlignment());
7844 SDValue NewChain = NewLd.getValue(1);
7845 if (TokenFactorIndex != -1) {
7846 Ops.push_back(NewChain);
7847 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7850 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
7851 St->getSrcValue(), St->getSrcValueOffset(),
7852 St->isVolatile(), St->getAlignment());
7855 // Otherwise, lower to two 32-bit copies.
7856 SDValue LoAddr = Ld->getBasePtr();
7857 SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7858 DAG.getConstant(4, MVT::i32));
7860 SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
7861 Ld->getSrcValue(), Ld->getSrcValueOffset(),
7862 Ld->isVolatile(), Ld->getAlignment());
7863 SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
7864 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
7866 MinAlign(Ld->getAlignment(), 4));
7868 SDValue NewChain = LoLd.getValue(1);
7869 if (TokenFactorIndex != -1) {
7870 Ops.push_back(LoLd);
7871 Ops.push_back(HiLd);
7872 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7876 LoAddr = St->getBasePtr();
7877 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7878 DAG.getConstant(4, MVT::i32));
7880 SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
7881 St->getSrcValue(), St->getSrcValueOffset(),
7882 St->isVolatile(), St->getAlignment());
7883 SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
7885 St->getSrcValueOffset() + 4,
7887 MinAlign(St->getAlignment(), 4));
7888 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
7894 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
7895 /// X86ISD::FXOR nodes.
7896 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
7897 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
7898 // F[X]OR(0.0, x) -> x
7899 // F[X]OR(x, 0.0) -> x
7900 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7901 if (C->getValueAPF().isPosZero())
7902 return N->getOperand(1);
7903 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7904 if (C->getValueAPF().isPosZero())
7905 return N->getOperand(0);
7909 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
7910 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
7911 // FAND(0.0, x) -> 0.0
7912 // FAND(x, 0.0) -> 0.0
7913 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7914 if (C->getValueAPF().isPosZero())
7915 return N->getOperand(0);
7916 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7917 if (C->getValueAPF().isPosZero())
7918 return N->getOperand(1);
7922 static SDValue PerformBTCombine(SDNode *N,
7924 TargetLowering::DAGCombinerInfo &DCI) {
7925 // BT ignores high bits in the bit index operand.
7926 SDValue Op1 = N->getOperand(1);
7927 if (Op1.hasOneUse()) {
7928 unsigned BitWidth = Op1.getValueSizeInBits();
7929 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
7930 APInt KnownZero, KnownOne;
7931 TargetLowering::TargetLoweringOpt TLO(DAG);
7932 TargetLowering &TLI = DAG.getTargetLoweringInfo();
7933 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
7934 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
7935 DCI.CommitTargetLoweringOpt(TLO);
7940 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
7941 DAGCombinerInfo &DCI) const {
7942 SelectionDAG &DAG = DCI.DAG;
7943 switch (N->getOpcode()) {
7945 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
7946 case ISD::BUILD_VECTOR:
7947 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
7948 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
7951 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
7952 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
7954 case X86ISD::FOR: return PerformFORCombine(N, DAG);
7955 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
7956 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
7962 //===----------------------------------------------------------------------===//
7963 // X86 Inline Assembly Support
7964 //===----------------------------------------------------------------------===//
7966 /// getConstraintType - Given a constraint letter, return the type of
7967 /// constraint it is for this target.
7968 X86TargetLowering::ConstraintType
7969 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
7970 if (Constraint.size() == 1) {
7971 switch (Constraint[0]) {
7983 return C_RegisterClass;
7988 return TargetLowering::getConstraintType(Constraint);
7991 /// LowerXConstraint - try to replace an X constraint, which matches anything,
7992 /// with another that has more specific requirements based on the type of the
7993 /// corresponding operand.
7994 const char *X86TargetLowering::
7995 LowerXConstraint(MVT ConstraintVT) const {
7996 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
7997 // 'f' like normal targets.
7998 if (ConstraintVT.isFloatingPoint()) {
7999 if (Subtarget->hasSSE2())
8001 if (Subtarget->hasSSE1())
8005 return TargetLowering::LowerXConstraint(ConstraintVT);
8008 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8009 /// vector. If it is invalid, don't add anything to Ops.
8010 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8013 std::vector<SDValue>&Ops,
8014 SelectionDAG &DAG) const {
8015 SDValue Result(0, 0);
8017 switch (Constraint) {
8020 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8021 if (C->getZExtValue() <= 31) {
8022 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8028 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8029 if (C->getZExtValue() <= 63) {
8030 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8036 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8037 if (C->getZExtValue() <= 255) {
8038 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8044 // Literal immediates are always ok.
8045 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8046 Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
8050 // If we are in non-pic codegen mode, we allow the address of a global (with
8051 // an optional displacement) to be used with 'i'.
8052 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
8055 // Match either (GA) or (GA+C)
8057 Offset = GA->getOffset();
8058 } else if (Op.getOpcode() == ISD::ADD) {
8059 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8060 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8062 Offset = GA->getOffset()+C->getZExtValue();
8064 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8065 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8067 Offset = GA->getOffset()+C->getZExtValue();
8075 Op = LowerGlobalAddress(GA->getGlobal(), Offset, DAG);
8077 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8083 // Otherwise, not valid for this mode.
8088 if (Result.getNode()) {
8089 Ops.push_back(Result);
8092 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8096 std::vector<unsigned> X86TargetLowering::
8097 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8099 if (Constraint.size() == 1) {
8100 // FIXME: not handling fp-stack yet!
8101 switch (Constraint[0]) { // GCC X86 Constraint Letters
8102 default: break; // Unknown constraint letter
8103 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8106 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8107 else if (VT == MVT::i16)
8108 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8109 else if (VT == MVT::i8)
8110 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8111 else if (VT == MVT::i64)
8112 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8117 return std::vector<unsigned>();
8120 std::pair<unsigned, const TargetRegisterClass*>
8121 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8123 // First, see if this is a constraint that directly corresponds to an LLVM
8125 if (Constraint.size() == 1) {
8126 // GCC Constraint Letters
8127 switch (Constraint[0]) {
8129 case 'r': // GENERAL_REGS
8130 case 'R': // LEGACY_REGS
8131 case 'l': // INDEX_REGS
8133 return std::make_pair(0U, X86::GR8RegisterClass);
8135 return std::make_pair(0U, X86::GR16RegisterClass);
8136 if (VT == MVT::i32 || !Subtarget->is64Bit())
8137 return std::make_pair(0U, X86::GR32RegisterClass);
8138 return std::make_pair(0U, X86::GR64RegisterClass);
8139 case 'f': // FP Stack registers.
8140 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8141 // value to the correct fpstack register class.
8142 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8143 return std::make_pair(0U, X86::RFP32RegisterClass);
8144 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8145 return std::make_pair(0U, X86::RFP64RegisterClass);
8146 return std::make_pair(0U, X86::RFP80RegisterClass);
8147 case 'y': // MMX_REGS if MMX allowed.
8148 if (!Subtarget->hasMMX()) break;
8149 return std::make_pair(0U, X86::VR64RegisterClass);
8150 case 'Y': // SSE_REGS if SSE2 allowed
8151 if (!Subtarget->hasSSE2()) break;
8153 case 'x': // SSE_REGS if SSE1 allowed
8154 if (!Subtarget->hasSSE1()) break;
8156 switch (VT.getSimpleVT()) {
8158 // Scalar SSE types.
8161 return std::make_pair(0U, X86::FR32RegisterClass);
8164 return std::make_pair(0U, X86::FR64RegisterClass);
8172 return std::make_pair(0U, X86::VR128RegisterClass);
8178 // Use the default implementation in TargetLowering to convert the register
8179 // constraint into a member of a register class.
8180 std::pair<unsigned, const TargetRegisterClass*> Res;
8181 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8183 // Not found as a standard register?
8184 if (Res.second == 0) {
8185 // GCC calls "st(0)" just plain "st".
8186 if (StringsEqualNoCase("{st}", Constraint)) {
8187 Res.first = X86::ST0;
8188 Res.second = X86::RFP80RegisterClass;
8190 // 'A' means EAX + EDX.
8191 if (Constraint == "A") {
8192 Res.first = X86::EAX;
8193 Res.second = X86::GRADRegisterClass;
8198 // Otherwise, check to see if this is a register class of the wrong value
8199 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8200 // turn into {ax},{dx}.
8201 if (Res.second->hasType(VT))
8202 return Res; // Correct type already, nothing to do.
8204 // All of the single-register GCC register classes map their values onto
8205 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8206 // really want an 8-bit or 32-bit register, map to the appropriate register
8207 // class and return the appropriate register.
8208 if (Res.second == X86::GR16RegisterClass) {
8209 if (VT == MVT::i8) {
8210 unsigned DestReg = 0;
8211 switch (Res.first) {
8213 case X86::AX: DestReg = X86::AL; break;
8214 case X86::DX: DestReg = X86::DL; break;
8215 case X86::CX: DestReg = X86::CL; break;
8216 case X86::BX: DestReg = X86::BL; break;
8219 Res.first = DestReg;
8220 Res.second = Res.second = X86::GR8RegisterClass;
8222 } else if (VT == MVT::i32) {
8223 unsigned DestReg = 0;
8224 switch (Res.first) {
8226 case X86::AX: DestReg = X86::EAX; break;
8227 case X86::DX: DestReg = X86::EDX; break;
8228 case X86::CX: DestReg = X86::ECX; break;
8229 case X86::BX: DestReg = X86::EBX; break;
8230 case X86::SI: DestReg = X86::ESI; break;
8231 case X86::DI: DestReg = X86::EDI; break;
8232 case X86::BP: DestReg = X86::EBP; break;
8233 case X86::SP: DestReg = X86::ESP; break;
8236 Res.first = DestReg;
8237 Res.second = Res.second = X86::GR32RegisterClass;
8239 } else if (VT == MVT::i64) {
8240 unsigned DestReg = 0;
8241 switch (Res.first) {
8243 case X86::AX: DestReg = X86::RAX; break;
8244 case X86::DX: DestReg = X86::RDX; break;
8245 case X86::CX: DestReg = X86::RCX; break;
8246 case X86::BX: DestReg = X86::RBX; break;
8247 case X86::SI: DestReg = X86::RSI; break;
8248 case X86::DI: DestReg = X86::RDI; break;
8249 case X86::BP: DestReg = X86::RBP; break;
8250 case X86::SP: DestReg = X86::RSP; break;
8253 Res.first = DestReg;
8254 Res.second = Res.second = X86::GR64RegisterClass;
8257 } else if (Res.second == X86::FR32RegisterClass ||
8258 Res.second == X86::FR64RegisterClass ||
8259 Res.second == X86::VR128RegisterClass) {
8260 // Handle references to XMM physical registers that got mapped into the
8261 // wrong class. This can happen with constraints like {xmm0} where the
8262 // target independent register mapper will just pick the first match it can
8263 // find, ignoring the required type.
8265 Res.second = X86::FR32RegisterClass;
8266 else if (VT == MVT::f64)
8267 Res.second = X86::FR64RegisterClass;
8268 else if (X86::VR128RegisterClass->hasType(VT))
8269 Res.second = X86::VR128RegisterClass;
8275 //===----------------------------------------------------------------------===//
8276 // X86 Widen vector type
8277 //===----------------------------------------------------------------------===//
8279 /// getWidenVectorType: given a vector type, returns the type to widen
8280 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8281 /// If there is no vector type that we want to widen to, returns MVT::Other
8282 /// When and where to widen is target dependent based on the cost of
8283 /// scalarizing vs using the wider vector type.
8285 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8286 assert(VT.isVector());
8287 if (isTypeLegal(VT))
8290 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8291 // type based on element type. This would speed up our search (though
8292 // it may not be worth it since the size of the list is relatively
8294 MVT EltVT = VT.getVectorElementType();
8295 unsigned NElts = VT.getVectorNumElements();
8297 // On X86, it make sense to widen any vector wider than 1
8301 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8302 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8303 MVT SVT = (MVT::SimpleValueType)nVT;
8305 if (isTypeLegal(SVT) &&
8306 SVT.getVectorElementType() == EltVT &&
8307 SVT.getVectorNumElements() > NElts)