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);
122 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
123 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
125 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
128 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
130 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
131 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
132 // SSE has no i16 to fp conversion, only i32
133 if (X86ScalarSSEf32) {
134 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
135 // f32 and f64 cases are Legal, f80 case is not
136 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
138 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
139 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
142 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
143 // are Legal, f80 is custom lowered.
144 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
145 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
147 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
149 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
150 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
152 if (X86ScalarSSEf32) {
153 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
154 // f32 and f64 cases are Legal, f80 case is not
155 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
157 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
158 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
161 // Handle FP_TO_UINT by promoting the destination to a larger signed
163 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
164 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
165 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
167 if (Subtarget->is64Bit()) {
168 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
169 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
171 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
172 // Expand FP_TO_UINT into a select.
173 // FIXME: We would like to use a Custom expander here eventually to do
174 // the optimal thing for SSE vs. the default expansion in the legalizer.
175 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
177 // With SSE3 we can use fisttpll to convert to a signed i64.
178 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
181 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
182 if (!X86ScalarSSEf64) {
183 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
184 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
187 // Scalar integer divide and remainder are lowered to use operations that
188 // produce two results, to match the available instructions. This exposes
189 // the two-result form to trivial CSE, which is able to combine x/y and x%y
190 // into a single instruction.
192 // Scalar integer multiply-high is also lowered to use two-result
193 // operations, to match the available instructions. However, plain multiply
194 // (low) operations are left as Legal, as there are single-result
195 // instructions for this in x86. Using the two-result multiply instructions
196 // when both high and low results are needed must be arranged by dagcombine.
197 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
198 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
199 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
200 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
201 setOperationAction(ISD::SREM , MVT::i8 , Expand);
202 setOperationAction(ISD::UREM , MVT::i8 , Expand);
203 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
204 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
205 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
206 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
207 setOperationAction(ISD::SREM , MVT::i16 , Expand);
208 setOperationAction(ISD::UREM , MVT::i16 , Expand);
209 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
210 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
211 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
212 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
213 setOperationAction(ISD::SREM , MVT::i32 , Expand);
214 setOperationAction(ISD::UREM , MVT::i32 , Expand);
215 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
216 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
217 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
218 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
219 setOperationAction(ISD::SREM , MVT::i64 , Expand);
220 setOperationAction(ISD::UREM , MVT::i64 , Expand);
222 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
223 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
224 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
225 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
226 if (Subtarget->is64Bit())
227 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
231 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
232 setOperationAction(ISD::FREM , MVT::f32 , Expand);
233 setOperationAction(ISD::FREM , MVT::f64 , Expand);
234 setOperationAction(ISD::FREM , MVT::f80 , Expand);
235 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
237 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
238 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
239 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
240 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
241 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
242 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
243 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
244 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
245 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
246 if (Subtarget->is64Bit()) {
247 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
248 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
249 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
252 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
253 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
255 // These should be promoted to a larger select which is supported.
256 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
257 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
258 // X86 wants to expand cmov itself.
259 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
260 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
261 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
262 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
263 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
264 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
265 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
266 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
267 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
268 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
269 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
270 if (Subtarget->is64Bit()) {
271 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
272 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
274 // X86 ret instruction may pop stack.
275 setOperationAction(ISD::RET , MVT::Other, Custom);
276 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
279 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
280 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
281 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
282 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
283 if (Subtarget->is64Bit())
284 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
286 if (Subtarget->is64Bit()) {
287 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
288 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
289 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
290 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
292 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
293 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
294 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
295 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
296 if (Subtarget->is64Bit()) {
297 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
298 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
299 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
302 if (Subtarget->hasSSE1())
303 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
305 if (!Subtarget->hasSSE2())
306 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
308 // Expand certain atomics
309 setOperationAction(ISD::ATOMIC_CMP_SWAP_8 , MVT::i8, Custom);
310 setOperationAction(ISD::ATOMIC_CMP_SWAP_16, MVT::i16, Custom);
311 setOperationAction(ISD::ATOMIC_CMP_SWAP_32, MVT::i32, Custom);
312 setOperationAction(ISD::ATOMIC_CMP_SWAP_64, MVT::i64, Custom);
314 setOperationAction(ISD::ATOMIC_LOAD_SUB_8 , MVT::i8, Custom);
315 setOperationAction(ISD::ATOMIC_LOAD_SUB_16, MVT::i16, Custom);
316 setOperationAction(ISD::ATOMIC_LOAD_SUB_32, MVT::i32, Custom);
317 setOperationAction(ISD::ATOMIC_LOAD_SUB_64, MVT::i64, Custom);
319 if (!Subtarget->is64Bit()) {
320 setOperationAction(ISD::ATOMIC_LOAD_ADD_64, MVT::i64, Custom);
321 setOperationAction(ISD::ATOMIC_LOAD_SUB_64, MVT::i64, Custom);
322 setOperationAction(ISD::ATOMIC_LOAD_AND_64, MVT::i64, Custom);
323 setOperationAction(ISD::ATOMIC_LOAD_OR_64, MVT::i64, Custom);
324 setOperationAction(ISD::ATOMIC_LOAD_XOR_64, MVT::i64, Custom);
325 setOperationAction(ISD::ATOMIC_LOAD_NAND_64, MVT::i64, Custom);
326 setOperationAction(ISD::ATOMIC_SWAP_64, MVT::i64, Custom);
329 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
330 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
331 // FIXME - use subtarget debug flags
332 if (!Subtarget->isTargetDarwin() &&
333 !Subtarget->isTargetELF() &&
334 !Subtarget->isTargetCygMing()) {
335 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
336 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
339 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
340 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
341 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
342 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
343 if (Subtarget->is64Bit()) {
344 setExceptionPointerRegister(X86::RAX);
345 setExceptionSelectorRegister(X86::RDX);
347 setExceptionPointerRegister(X86::EAX);
348 setExceptionSelectorRegister(X86::EDX);
350 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
351 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
353 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
355 setOperationAction(ISD::TRAP, MVT::Other, Legal);
357 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
358 setOperationAction(ISD::VASTART , MVT::Other, Custom);
359 setOperationAction(ISD::VAEND , MVT::Other, Expand);
360 if (Subtarget->is64Bit()) {
361 setOperationAction(ISD::VAARG , MVT::Other, Custom);
362 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
364 setOperationAction(ISD::VAARG , MVT::Other, Expand);
365 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
368 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
369 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
370 if (Subtarget->is64Bit())
371 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
372 if (Subtarget->isTargetCygMing())
373 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
375 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
377 if (X86ScalarSSEf64) {
378 // f32 and f64 use SSE.
379 // Set up the FP register classes.
380 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
381 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
383 // Use ANDPD to simulate FABS.
384 setOperationAction(ISD::FABS , MVT::f64, Custom);
385 setOperationAction(ISD::FABS , MVT::f32, Custom);
387 // Use XORP to simulate FNEG.
388 setOperationAction(ISD::FNEG , MVT::f64, Custom);
389 setOperationAction(ISD::FNEG , MVT::f32, Custom);
391 // Use ANDPD and ORPD to simulate FCOPYSIGN.
392 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
393 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
395 // We don't support sin/cos/fmod
396 setOperationAction(ISD::FSIN , MVT::f64, Expand);
397 setOperationAction(ISD::FCOS , MVT::f64, Expand);
398 setOperationAction(ISD::FSIN , MVT::f32, Expand);
399 setOperationAction(ISD::FCOS , MVT::f32, Expand);
401 // Expand FP immediates into loads from the stack, except for the special
403 addLegalFPImmediate(APFloat(+0.0)); // xorpd
404 addLegalFPImmediate(APFloat(+0.0f)); // xorps
406 // Floating truncations from f80 and extensions to f80 go through memory.
407 // If optimizing, we lie about this though and handle it in
408 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
410 setConvertAction(MVT::f32, MVT::f80, Expand);
411 setConvertAction(MVT::f64, MVT::f80, Expand);
412 setConvertAction(MVT::f80, MVT::f32, Expand);
413 setConvertAction(MVT::f80, MVT::f64, Expand);
415 } else if (X86ScalarSSEf32) {
416 // Use SSE for f32, x87 for f64.
417 // Set up the FP register classes.
418 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
419 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
421 // Use ANDPS to simulate FABS.
422 setOperationAction(ISD::FABS , MVT::f32, Custom);
424 // Use XORP to simulate FNEG.
425 setOperationAction(ISD::FNEG , MVT::f32, Custom);
427 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
429 // Use ANDPS and ORPS to simulate FCOPYSIGN.
430 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
431 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
433 // We don't support sin/cos/fmod
434 setOperationAction(ISD::FSIN , MVT::f32, Expand);
435 setOperationAction(ISD::FCOS , MVT::f32, Expand);
437 // Special cases we handle for FP constants.
438 addLegalFPImmediate(APFloat(+0.0f)); // xorps
439 addLegalFPImmediate(APFloat(+0.0)); // FLD0
440 addLegalFPImmediate(APFloat(+1.0)); // FLD1
441 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
442 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
444 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
445 // this though and handle it in InstructionSelectPreprocess so that
446 // dagcombine2 can hack on these.
448 setConvertAction(MVT::f32, MVT::f64, Expand);
449 setConvertAction(MVT::f32, MVT::f80, Expand);
450 setConvertAction(MVT::f80, MVT::f32, Expand);
451 setConvertAction(MVT::f64, MVT::f32, Expand);
452 // And x87->x87 truncations also.
453 setConvertAction(MVT::f80, MVT::f64, Expand);
457 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
458 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
461 // f32 and f64 in x87.
462 // Set up the FP register classes.
463 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
464 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
466 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
467 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
468 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
469 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
471 // Floating truncations go through memory. If optimizing, we lie about
472 // this though and handle it in InstructionSelectPreprocess so that
473 // dagcombine2 can hack on these.
475 setConvertAction(MVT::f80, MVT::f32, Expand);
476 setConvertAction(MVT::f64, MVT::f32, Expand);
477 setConvertAction(MVT::f80, MVT::f64, Expand);
481 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
482 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
484 addLegalFPImmediate(APFloat(+0.0)); // FLD0
485 addLegalFPImmediate(APFloat(+1.0)); // FLD1
486 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
487 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
488 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
489 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
490 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
491 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
494 // Long double always uses X87.
495 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
496 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
497 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
500 APFloat TmpFlt(+0.0);
501 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
503 addLegalFPImmediate(TmpFlt); // FLD0
505 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
506 APFloat TmpFlt2(+1.0);
507 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
509 addLegalFPImmediate(TmpFlt2); // FLD1
510 TmpFlt2.changeSign();
511 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
515 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
516 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
519 // Always use a library call for pow.
520 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
521 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
522 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
524 setOperationAction(ISD::FLOG, MVT::f80, Expand);
525 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
526 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
527 setOperationAction(ISD::FEXP, MVT::f80, Expand);
528 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
530 // First set operation action for all vector types to either promote
531 // (for widening) or expand (for scalarization). Then we will selectively
532 // turn on ones that can be effectively codegen'd.
533 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
534 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
535 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
536 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
550 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
580 if (!DisableMMX && Subtarget->hasMMX()) {
581 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
582 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
583 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
584 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
585 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
587 // FIXME: add MMX packed arithmetics
589 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
590 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
591 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
592 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
594 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
595 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
596 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
597 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
599 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
600 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
602 setOperationAction(ISD::AND, MVT::v8i8, Promote);
603 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
604 setOperationAction(ISD::AND, MVT::v4i16, Promote);
605 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
606 setOperationAction(ISD::AND, MVT::v2i32, Promote);
607 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
608 setOperationAction(ISD::AND, MVT::v1i64, Legal);
610 setOperationAction(ISD::OR, MVT::v8i8, Promote);
611 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
612 setOperationAction(ISD::OR, MVT::v4i16, Promote);
613 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
614 setOperationAction(ISD::OR, MVT::v2i32, Promote);
615 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
616 setOperationAction(ISD::OR, MVT::v1i64, Legal);
618 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
619 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
620 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
621 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
622 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
623 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
624 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
626 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
627 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
628 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
629 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
630 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
631 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
632 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
633 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
634 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
636 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
637 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
638 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
639 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
640 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
642 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
643 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
644 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
645 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
647 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
648 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
649 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
650 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
652 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
655 if (Subtarget->hasSSE1()) {
656 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
658 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
659 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
660 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
661 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
662 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
663 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
664 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
665 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
666 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
667 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
668 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
669 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
672 if (Subtarget->hasSSE2()) {
673 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
674 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
675 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
676 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
677 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
679 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
680 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
681 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
682 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
683 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
684 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
685 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
686 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
687 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
688 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
689 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
690 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
691 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
692 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
693 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
695 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
696 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
697 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
698 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
700 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
701 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
702 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
703 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
704 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
706 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
707 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
708 MVT VT = (MVT::SimpleValueType)i;
709 // Do not attempt to custom lower non-power-of-2 vectors
710 if (!isPowerOf2_32(VT.getVectorNumElements()))
712 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
713 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
714 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
716 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
717 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
718 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
719 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
720 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
721 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
722 if (Subtarget->is64Bit()) {
723 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
724 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
727 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
728 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
729 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
730 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
731 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
732 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
733 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
734 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
735 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
736 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
737 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
738 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
741 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
743 // Custom lower v2i64 and v2f64 selects.
744 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
745 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
746 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
747 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
751 if (Subtarget->hasSSE41()) {
752 // FIXME: Do we need to handle scalar-to-vector here?
753 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
754 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
756 // i8 and i16 vectors are custom , because the source register and source
757 // source memory operand types are not the same width. f32 vectors are
758 // custom since the immediate controlling the insert encodes additional
760 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
761 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
762 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
763 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
765 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
766 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
767 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
768 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
770 if (Subtarget->is64Bit()) {
771 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
772 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
776 if (Subtarget->hasSSE42()) {
777 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
780 // We want to custom lower some of our intrinsics.
781 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
783 // Add with overflow operations are custom lowered.
784 setOperationAction(ISD::SADDO, MVT::i32, Custom);
785 setOperationAction(ISD::SADDO, MVT::i64, Custom);
786 setOperationAction(ISD::UADDO, MVT::i32, Custom);
787 setOperationAction(ISD::UADDO, MVT::i64, Custom);
789 // We have target-specific dag combine patterns for the following nodes:
790 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
791 setTargetDAGCombine(ISD::BUILD_VECTOR);
792 setTargetDAGCombine(ISD::SELECT);
793 setTargetDAGCombine(ISD::STORE);
795 computeRegisterProperties();
797 // FIXME: These should be based on subtarget info. Plus, the values should
798 // be smaller when we are in optimizing for size mode.
799 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
800 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
801 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
802 allowUnalignedMemoryAccesses = true; // x86 supports it!
803 setPrefLoopAlignment(16);
807 MVT X86TargetLowering::getSetCCResultType(const SDValue &) const {
812 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
813 /// the desired ByVal argument alignment.
814 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
817 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
818 if (VTy->getBitWidth() == 128)
820 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
821 unsigned EltAlign = 0;
822 getMaxByValAlign(ATy->getElementType(), EltAlign);
823 if (EltAlign > MaxAlign)
825 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
826 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
827 unsigned EltAlign = 0;
828 getMaxByValAlign(STy->getElementType(i), EltAlign);
829 if (EltAlign > MaxAlign)
838 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
839 /// function arguments in the caller parameter area. For X86, aggregates
840 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
841 /// are at 4-byte boundaries.
842 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
843 if (Subtarget->is64Bit()) {
844 // Max of 8 and alignment of type.
845 unsigned TyAlign = TD->getABITypeAlignment(Ty);
852 if (Subtarget->hasSSE1())
853 getMaxByValAlign(Ty, Align);
857 /// getOptimalMemOpType - Returns the target specific optimal type for load
858 /// and store operations as a result of memset, memcpy, and memmove
859 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
862 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
863 bool isSrcConst, bool isSrcStr) const {
864 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
865 // linux. This is because the stack realignment code can't handle certain
866 // cases like PR2962. This should be removed when PR2962 is fixed.
867 if (Subtarget->getStackAlignment() >= 16) {
868 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
870 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
873 if (Subtarget->is64Bit() && Size >= 8)
879 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
881 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
882 SelectionDAG &DAG) const {
883 if (usesGlobalOffsetTable())
884 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
885 if (!Subtarget->isPICStyleRIPRel())
886 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
890 //===----------------------------------------------------------------------===//
891 // Return Value Calling Convention Implementation
892 //===----------------------------------------------------------------------===//
894 #include "X86GenCallingConv.inc"
896 /// LowerRET - Lower an ISD::RET node.
897 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
898 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
900 SmallVector<CCValAssign, 16> RVLocs;
901 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
902 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
903 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
904 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
906 // If this is the first return lowered for this function, add the regs to the
907 // liveout set for the function.
908 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
909 for (unsigned i = 0; i != RVLocs.size(); ++i)
910 if (RVLocs[i].isRegLoc())
911 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
913 SDValue Chain = Op.getOperand(0);
915 // Handle tail call return.
916 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
917 if (Chain.getOpcode() == X86ISD::TAILCALL) {
918 SDValue TailCall = Chain;
919 SDValue TargetAddress = TailCall.getOperand(1);
920 SDValue StackAdjustment = TailCall.getOperand(2);
921 assert(((TargetAddress.getOpcode() == ISD::Register &&
922 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
923 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
924 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
925 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
926 "Expecting an global address, external symbol, or register");
927 assert(StackAdjustment.getOpcode() == ISD::Constant &&
928 "Expecting a const value");
930 SmallVector<SDValue,8> Operands;
931 Operands.push_back(Chain.getOperand(0));
932 Operands.push_back(TargetAddress);
933 Operands.push_back(StackAdjustment);
934 // Copy registers used by the call. Last operand is a flag so it is not
936 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
937 Operands.push_back(Chain.getOperand(i));
939 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
946 SmallVector<SDValue, 6> RetOps;
947 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
948 // Operand #1 = Bytes To Pop
949 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
951 // Copy the result values into the output registers.
952 for (unsigned i = 0; i != RVLocs.size(); ++i) {
953 CCValAssign &VA = RVLocs[i];
954 assert(VA.isRegLoc() && "Can only return in registers!");
955 SDValue ValToCopy = Op.getOperand(i*2+1);
957 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
958 // the RET instruction and handled by the FP Stackifier.
959 if (RVLocs[i].getLocReg() == X86::ST0 ||
960 RVLocs[i].getLocReg() == X86::ST1) {
961 // If this is a copy from an xmm register to ST(0), use an FPExtend to
962 // change the value to the FP stack register class.
963 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
964 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
965 RetOps.push_back(ValToCopy);
966 // Don't emit a copytoreg.
970 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
971 Flag = Chain.getValue(1);
974 // The x86-64 ABI for returning structs by value requires that we copy
975 // the sret argument into %rax for the return. We saved the argument into
976 // a virtual register in the entry block, so now we copy the value out
978 if (Subtarget->is64Bit() &&
979 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
980 MachineFunction &MF = DAG.getMachineFunction();
981 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
982 unsigned Reg = FuncInfo->getSRetReturnReg();
984 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
985 FuncInfo->setSRetReturnReg(Reg);
987 SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
989 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
990 Flag = Chain.getValue(1);
993 RetOps[0] = Chain; // Update chain.
995 // Add the flag if we have it.
997 RetOps.push_back(Flag);
999 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
1003 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1004 /// appropriate copies out of appropriate physical registers. This assumes that
1005 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1006 /// being lowered. The returns a SDNode with the same number of values as the
1008 SDNode *X86TargetLowering::
1009 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1010 unsigned CallingConv, SelectionDAG &DAG) {
1012 // Assign locations to each value returned by this call.
1013 SmallVector<CCValAssign, 16> RVLocs;
1014 bool isVarArg = TheCall->isVarArg();
1015 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1016 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1018 SmallVector<SDValue, 8> ResultVals;
1020 // Copy all of the result registers out of their specified physreg.
1021 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1022 MVT CopyVT = RVLocs[i].getValVT();
1024 // If this is a call to a function that returns an fp value on the floating
1025 // point stack, but where we prefer to use the value in xmm registers, copy
1026 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1027 if ((RVLocs[i].getLocReg() == X86::ST0 ||
1028 RVLocs[i].getLocReg() == X86::ST1) &&
1029 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1033 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
1034 CopyVT, InFlag).getValue(1);
1035 SDValue Val = Chain.getValue(0);
1036 InFlag = Chain.getValue(2);
1038 if (CopyVT != RVLocs[i].getValVT()) {
1039 // Round the F80 the right size, which also moves to the appropriate xmm
1041 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
1042 // This truncation won't change the value.
1043 DAG.getIntPtrConstant(1));
1046 ResultVals.push_back(Val);
1049 // Merge everything together with a MERGE_VALUES node.
1050 ResultVals.push_back(Chain);
1051 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(), &ResultVals[0],
1052 ResultVals.size()).getNode();
1056 //===----------------------------------------------------------------------===//
1057 // C & StdCall & Fast Calling Convention implementation
1058 //===----------------------------------------------------------------------===//
1059 // StdCall calling convention seems to be standard for many Windows' API
1060 // routines and around. It differs from C calling convention just a little:
1061 // callee should clean up the stack, not caller. Symbols should be also
1062 // decorated in some fancy way :) It doesn't support any vector arguments.
1063 // For info on fast calling convention see Fast Calling Convention (tail call)
1064 // implementation LowerX86_32FastCCCallTo.
1066 /// AddLiveIn - This helper function adds the specified physical register to the
1067 /// MachineFunction as a live in value. It also creates a corresponding virtual
1068 /// register for it.
1069 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1070 const TargetRegisterClass *RC) {
1071 assert(RC->contains(PReg) && "Not the correct regclass!");
1072 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1073 MF.getRegInfo().addLiveIn(PReg, VReg);
1077 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1079 static bool CallIsStructReturn(CallSDNode *TheCall) {
1080 unsigned NumOps = TheCall->getNumArgs();
1084 return TheCall->getArgFlags(0).isSRet();
1087 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1088 /// return semantics.
1089 static bool ArgsAreStructReturn(SDValue Op) {
1090 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1094 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1097 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1098 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1100 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1104 switch (CallingConv) {
1107 case CallingConv::X86_StdCall:
1108 return !Subtarget->is64Bit();
1109 case CallingConv::X86_FastCall:
1110 return !Subtarget->is64Bit();
1111 case CallingConv::Fast:
1112 return PerformTailCallOpt;
1116 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1117 /// given CallingConvention value.
1118 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1119 if (Subtarget->is64Bit()) {
1120 if (Subtarget->isTargetWin64())
1121 return CC_X86_Win64_C;
1122 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1123 return CC_X86_64_TailCall;
1128 if (CC == CallingConv::X86_FastCall)
1129 return CC_X86_32_FastCall;
1130 else if (CC == CallingConv::Fast)
1131 return CC_X86_32_FastCC;
1136 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1137 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1139 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1140 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1141 if (CC == CallingConv::X86_FastCall)
1143 else if (CC == CallingConv::X86_StdCall)
1149 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1150 /// in a register before calling.
1151 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1152 return !IsTailCall && !Is64Bit &&
1153 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1154 Subtarget->isPICStyleGOT();
1157 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1158 /// address to be loaded in a register.
1160 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1161 return !Is64Bit && IsTailCall &&
1162 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1163 Subtarget->isPICStyleGOT();
1166 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1167 /// by "Src" to address "Dst" with size and alignment information specified by
1168 /// the specific parameter attribute. The copy will be passed as a byval
1169 /// function parameter.
1171 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1172 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1173 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1174 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1175 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1178 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1179 const CCValAssign &VA,
1180 MachineFrameInfo *MFI,
1182 SDValue Root, unsigned i) {
1183 // Create the nodes corresponding to a load from this parameter slot.
1184 ISD::ArgFlagsTy Flags =
1185 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1186 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1187 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1189 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1190 // changed with more analysis.
1191 // In case of tail call optimization mark all arguments mutable. Since they
1192 // could be overwritten by lowering of arguments in case of a tail call.
1193 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1194 VA.getLocMemOffset(), isImmutable);
1195 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1196 if (Flags.isByVal())
1198 return DAG.getLoad(VA.getValVT(), Root, FIN,
1199 PseudoSourceValue::getFixedStack(FI), 0);
1203 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1204 MachineFunction &MF = DAG.getMachineFunction();
1205 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1207 const Function* Fn = MF.getFunction();
1208 if (Fn->hasExternalLinkage() &&
1209 Subtarget->isTargetCygMing() &&
1210 Fn->getName() == "main")
1211 FuncInfo->setForceFramePointer(true);
1213 // Decorate the function name.
1214 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1216 MachineFrameInfo *MFI = MF.getFrameInfo();
1217 SDValue Root = Op.getOperand(0);
1218 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1219 unsigned CC = MF.getFunction()->getCallingConv();
1220 bool Is64Bit = Subtarget->is64Bit();
1221 bool IsWin64 = Subtarget->isTargetWin64();
1223 assert(!(isVarArg && CC == CallingConv::Fast) &&
1224 "Var args not supported with calling convention fastcc");
1226 // Assign locations to all of the incoming arguments.
1227 SmallVector<CCValAssign, 16> ArgLocs;
1228 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1229 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1231 SmallVector<SDValue, 8> ArgValues;
1232 unsigned LastVal = ~0U;
1233 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1234 CCValAssign &VA = ArgLocs[i];
1235 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1237 assert(VA.getValNo() != LastVal &&
1238 "Don't support value assigned to multiple locs yet");
1239 LastVal = VA.getValNo();
1241 if (VA.isRegLoc()) {
1242 MVT RegVT = VA.getLocVT();
1243 TargetRegisterClass *RC;
1244 if (RegVT == MVT::i32)
1245 RC = X86::GR32RegisterClass;
1246 else if (Is64Bit && RegVT == MVT::i64)
1247 RC = X86::GR64RegisterClass;
1248 else if (RegVT == MVT::f32)
1249 RC = X86::FR32RegisterClass;
1250 else if (RegVT == MVT::f64)
1251 RC = X86::FR64RegisterClass;
1252 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1253 RC = X86::VR128RegisterClass;
1254 else if (RegVT.isVector()) {
1255 assert(RegVT.getSizeInBits() == 64);
1257 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1259 // Darwin calling convention passes MMX values in either GPRs or
1260 // XMMs in x86-64. Other targets pass them in memory.
1261 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1262 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1265 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1270 assert(0 && "Unknown argument type!");
1273 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1274 SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1276 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1277 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1279 if (VA.getLocInfo() == CCValAssign::SExt)
1280 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1281 DAG.getValueType(VA.getValVT()));
1282 else if (VA.getLocInfo() == CCValAssign::ZExt)
1283 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1284 DAG.getValueType(VA.getValVT()));
1286 if (VA.getLocInfo() != CCValAssign::Full)
1287 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1289 // Handle MMX values passed in GPRs.
1290 if (Is64Bit && RegVT != VA.getLocVT()) {
1291 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1292 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1293 else if (RC == X86::VR128RegisterClass) {
1294 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1295 DAG.getConstant(0, MVT::i64));
1296 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1300 ArgValues.push_back(ArgValue);
1302 assert(VA.isMemLoc());
1303 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1307 // The x86-64 ABI for returning structs by value requires that we copy
1308 // the sret argument into %rax for the return. Save the argument into
1309 // a virtual register so that we can access it from the return points.
1310 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1311 MachineFunction &MF = DAG.getMachineFunction();
1312 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1313 unsigned Reg = FuncInfo->getSRetReturnReg();
1315 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1316 FuncInfo->setSRetReturnReg(Reg);
1318 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1319 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1322 unsigned StackSize = CCInfo.getNextStackOffset();
1323 // align stack specially for tail calls
1324 if (PerformTailCallOpt && CC == CallingConv::Fast)
1325 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1327 // If the function takes variable number of arguments, make a frame index for
1328 // the start of the first vararg value... for expansion of llvm.va_start.
1330 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1331 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1334 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1336 // FIXME: We should really autogenerate these arrays
1337 static const unsigned GPR64ArgRegsWin64[] = {
1338 X86::RCX, X86::RDX, X86::R8, X86::R9
1340 static const unsigned XMMArgRegsWin64[] = {
1341 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1343 static const unsigned GPR64ArgRegs64Bit[] = {
1344 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1346 static const unsigned XMMArgRegs64Bit[] = {
1347 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1348 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1350 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1353 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1354 GPR64ArgRegs = GPR64ArgRegsWin64;
1355 XMMArgRegs = XMMArgRegsWin64;
1357 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1358 GPR64ArgRegs = GPR64ArgRegs64Bit;
1359 XMMArgRegs = XMMArgRegs64Bit;
1361 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1363 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1366 // For X86-64, if there are vararg parameters that are passed via
1367 // registers, then we must store them to their spots on the stack so they
1368 // may be loaded by deferencing the result of va_next.
1369 VarArgsGPOffset = NumIntRegs * 8;
1370 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1371 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1372 TotalNumXMMRegs * 16, 16);
1374 // Store the integer parameter registers.
1375 SmallVector<SDValue, 8> MemOps;
1376 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1377 SDValue FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1378 DAG.getIntPtrConstant(VarArgsGPOffset));
1379 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1380 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1381 X86::GR64RegisterClass);
1382 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1384 DAG.getStore(Val.getValue(1), Val, FIN,
1385 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1386 MemOps.push_back(Store);
1387 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1388 DAG.getIntPtrConstant(8));
1391 // Now store the XMM (fp + vector) parameter registers.
1392 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1393 DAG.getIntPtrConstant(VarArgsFPOffset));
1394 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1395 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1396 X86::VR128RegisterClass);
1397 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1399 DAG.getStore(Val.getValue(1), Val, FIN,
1400 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1401 MemOps.push_back(Store);
1402 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1403 DAG.getIntPtrConstant(16));
1405 if (!MemOps.empty())
1406 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1407 &MemOps[0], MemOps.size());
1411 ArgValues.push_back(Root);
1413 // Some CCs need callee pop.
1414 if (IsCalleePop(isVarArg, CC)) {
1415 BytesToPopOnReturn = StackSize; // Callee pops everything.
1416 BytesCallerReserves = 0;
1418 BytesToPopOnReturn = 0; // Callee pops nothing.
1419 // If this is an sret function, the return should pop the hidden pointer.
1420 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1421 BytesToPopOnReturn = 4;
1422 BytesCallerReserves = StackSize;
1426 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1427 if (CC == CallingConv::X86_FastCall)
1428 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1431 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1433 // Return the new list of results.
1434 return DAG.getNode(ISD::MERGE_VALUES, Op.getNode()->getVTList(),
1435 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1439 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1440 const SDValue &StackPtr,
1441 const CCValAssign &VA,
1443 SDValue Arg, ISD::ArgFlagsTy Flags) {
1444 unsigned LocMemOffset = VA.getLocMemOffset();
1445 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1446 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1447 if (Flags.isByVal()) {
1448 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1450 return DAG.getStore(Chain, Arg, PtrOff,
1451 PseudoSourceValue::getStack(), LocMemOffset);
1454 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1455 /// optimization is performed and it is required.
1457 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1458 SDValue &OutRetAddr,
1463 if (!IsTailCall || FPDiff==0) return Chain;
1465 // Adjust the Return address stack slot.
1466 MVT VT = getPointerTy();
1467 OutRetAddr = getReturnAddressFrameIndex(DAG);
1468 // Load the "old" Return address.
1469 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1470 return SDValue(OutRetAddr.getNode(), 1);
1473 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1474 /// optimization is performed and it is required (FPDiff!=0).
1476 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1477 SDValue Chain, SDValue RetAddrFrIdx,
1478 bool Is64Bit, int FPDiff) {
1479 // Store the return address to the appropriate stack slot.
1480 if (!FPDiff) return Chain;
1481 // Calculate the new stack slot for the return address.
1482 int SlotSize = Is64Bit ? 8 : 4;
1483 int NewReturnAddrFI =
1484 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1485 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1486 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1487 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1488 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1492 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1493 MachineFunction &MF = DAG.getMachineFunction();
1494 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1495 SDValue Chain = TheCall->getChain();
1496 unsigned CC = TheCall->getCallingConv();
1497 bool isVarArg = TheCall->isVarArg();
1498 bool IsTailCall = TheCall->isTailCall() &&
1499 CC == CallingConv::Fast && PerformTailCallOpt;
1500 SDValue Callee = TheCall->getCallee();
1501 bool Is64Bit = Subtarget->is64Bit();
1502 bool IsStructRet = CallIsStructReturn(TheCall);
1504 assert(!(isVarArg && CC == CallingConv::Fast) &&
1505 "Var args not supported with calling convention fastcc");
1507 // Analyze operands of the call, assigning locations to each operand.
1508 SmallVector<CCValAssign, 16> ArgLocs;
1509 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1510 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1512 // Get a count of how many bytes are to be pushed on the stack.
1513 unsigned NumBytes = CCInfo.getNextStackOffset();
1514 if (PerformTailCallOpt && CC == CallingConv::Fast)
1515 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1519 // Lower arguments at fp - stackoffset + fpdiff.
1520 unsigned NumBytesCallerPushed =
1521 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1522 FPDiff = NumBytesCallerPushed - NumBytes;
1524 // Set the delta of movement of the returnaddr stackslot.
1525 // But only set if delta is greater than previous delta.
1526 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1527 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1530 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1532 SDValue RetAddrFrIdx;
1533 // Load return adress for tail calls.
1534 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1537 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1538 SmallVector<SDValue, 8> MemOpChains;
1541 // Walk the register/memloc assignments, inserting copies/loads. In the case
1542 // of tail call optimization arguments are handle later.
1543 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1544 CCValAssign &VA = ArgLocs[i];
1545 SDValue Arg = TheCall->getArg(i);
1546 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1547 bool isByVal = Flags.isByVal();
1549 // Promote the value if needed.
1550 switch (VA.getLocInfo()) {
1551 default: assert(0 && "Unknown loc info!");
1552 case CCValAssign::Full: break;
1553 case CCValAssign::SExt:
1554 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1556 case CCValAssign::ZExt:
1557 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1559 case CCValAssign::AExt:
1560 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1564 if (VA.isRegLoc()) {
1566 MVT RegVT = VA.getLocVT();
1567 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1568 switch (VA.getLocReg()) {
1571 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1573 // Special case: passing MMX values in GPR registers.
1574 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1577 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1578 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1579 // Special case: passing MMX values in XMM registers.
1580 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1581 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1582 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1583 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1584 getMOVLMask(2, DAG));
1589 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1591 if (!IsTailCall || (IsTailCall && isByVal)) {
1592 assert(VA.isMemLoc());
1593 if (StackPtr.getNode() == 0)
1594 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1596 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1597 Chain, Arg, Flags));
1602 if (!MemOpChains.empty())
1603 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1604 &MemOpChains[0], MemOpChains.size());
1606 // Build a sequence of copy-to-reg nodes chained together with token chain
1607 // and flag operands which copy the outgoing args into registers.
1609 // Tail call byval lowering might overwrite argument registers so in case of
1610 // tail call optimization the copies to registers are lowered later.
1612 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1613 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1615 InFlag = Chain.getValue(1);
1618 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1620 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1621 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1622 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1624 InFlag = Chain.getValue(1);
1626 // If we are tail calling and generating PIC/GOT style code load the address
1627 // of the callee into ecx. The value in ecx is used as target of the tail
1628 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1629 // calls on PIC/GOT architectures. Normally we would just put the address of
1630 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1631 // restored (since ebx is callee saved) before jumping to the target@PLT.
1632 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1633 // Note: The actual moving to ecx is done further down.
1634 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1635 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1636 !G->getGlobal()->hasProtectedVisibility())
1637 Callee = LowerGlobalAddress(Callee, DAG);
1638 else if (isa<ExternalSymbolSDNode>(Callee))
1639 Callee = LowerExternalSymbol(Callee,DAG);
1642 if (Is64Bit && isVarArg) {
1643 // From AMD64 ABI document:
1644 // For calls that may call functions that use varargs or stdargs
1645 // (prototype-less calls or calls to functions containing ellipsis (...) in
1646 // the declaration) %al is used as hidden argument to specify the number
1647 // of SSE registers used. The contents of %al do not need to match exactly
1648 // the number of registers, but must be an ubound on the number of SSE
1649 // registers used and is in the range 0 - 8 inclusive.
1651 // FIXME: Verify this on Win64
1652 // Count the number of XMM registers allocated.
1653 static const unsigned XMMArgRegs[] = {
1654 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1655 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1657 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1659 Chain = DAG.getCopyToReg(Chain, X86::AL,
1660 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1661 InFlag = Chain.getValue(1);
1665 // For tail calls lower the arguments to the 'real' stack slot.
1667 SmallVector<SDValue, 8> MemOpChains2;
1670 // Do not flag preceeding copytoreg stuff together with the following stuff.
1672 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1673 CCValAssign &VA = ArgLocs[i];
1674 if (!VA.isRegLoc()) {
1675 assert(VA.isMemLoc());
1676 SDValue Arg = TheCall->getArg(i);
1677 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1678 // Create frame index.
1679 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1680 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1681 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1682 FIN = DAG.getFrameIndex(FI, getPointerTy());
1684 if (Flags.isByVal()) {
1685 // Copy relative to framepointer.
1686 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1687 if (StackPtr.getNode() == 0)
1688 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1689 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1691 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1694 // Store relative to framepointer.
1695 MemOpChains2.push_back(
1696 DAG.getStore(Chain, Arg, FIN,
1697 PseudoSourceValue::getFixedStack(FI), 0));
1702 if (!MemOpChains2.empty())
1703 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1704 &MemOpChains2[0], MemOpChains2.size());
1706 // Copy arguments to their registers.
1707 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1708 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1710 InFlag = Chain.getValue(1);
1714 // Store the return address to the appropriate stack slot.
1715 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1719 // If the callee is a GlobalAddress node (quite common, every direct call is)
1720 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1721 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1722 // We should use extra load for direct calls to dllimported functions in
1724 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1725 getTargetMachine(), true))
1726 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1728 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1729 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1730 } else if (IsTailCall) {
1731 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1733 Chain = DAG.getCopyToReg(Chain,
1734 DAG.getRegister(Opc, getPointerTy()),
1736 Callee = DAG.getRegister(Opc, getPointerTy());
1737 // Add register as live out.
1738 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1741 // Returns a chain & a flag for retval copy to use.
1742 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1743 SmallVector<SDValue, 8> Ops;
1746 Ops.push_back(Chain);
1747 Ops.push_back(DAG.getIntPtrConstant(NumBytes, true));
1748 Ops.push_back(DAG.getIntPtrConstant(0, true));
1749 if (InFlag.getNode())
1750 Ops.push_back(InFlag);
1751 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1752 InFlag = Chain.getValue(1);
1754 // Returns a chain & a flag for retval copy to use.
1755 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1759 Ops.push_back(Chain);
1760 Ops.push_back(Callee);
1763 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1765 // Add argument registers to the end of the list so that they are known live
1767 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1768 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1769 RegsToPass[i].second.getValueType()));
1771 // Add an implicit use GOT pointer in EBX.
1772 if (!IsTailCall && !Is64Bit &&
1773 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1774 Subtarget->isPICStyleGOT())
1775 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1777 // Add an implicit use of AL for x86 vararg functions.
1778 if (Is64Bit && isVarArg)
1779 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1781 if (InFlag.getNode())
1782 Ops.push_back(InFlag);
1785 assert(InFlag.getNode() &&
1786 "Flag must be set. Depend on flag being set in LowerRET");
1787 Chain = DAG.getNode(X86ISD::TAILCALL,
1788 TheCall->getVTList(), &Ops[0], Ops.size());
1790 return SDValue(Chain.getNode(), Op.getResNo());
1793 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1794 InFlag = Chain.getValue(1);
1796 // Create the CALLSEQ_END node.
1797 unsigned NumBytesForCalleeToPush;
1798 if (IsCalleePop(isVarArg, CC))
1799 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1800 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1801 // If this is is a call to a struct-return function, the callee
1802 // pops the hidden struct pointer, so we have to push it back.
1803 // This is common for Darwin/X86, Linux & Mingw32 targets.
1804 NumBytesForCalleeToPush = 4;
1806 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1808 // Returns a flag for retval copy to use.
1809 Chain = DAG.getCALLSEQ_END(Chain,
1810 DAG.getIntPtrConstant(NumBytes, true),
1811 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1814 InFlag = Chain.getValue(1);
1816 // Handle result values, copying them out of physregs into vregs that we
1818 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1823 //===----------------------------------------------------------------------===//
1824 // Fast Calling Convention (tail call) implementation
1825 //===----------------------------------------------------------------------===//
1827 // Like std call, callee cleans arguments, convention except that ECX is
1828 // reserved for storing the tail called function address. Only 2 registers are
1829 // free for argument passing (inreg). Tail call optimization is performed
1831 // * tailcallopt is enabled
1832 // * caller/callee are fastcc
1833 // On X86_64 architecture with GOT-style position independent code only local
1834 // (within module) calls are supported at the moment.
1835 // To keep the stack aligned according to platform abi the function
1836 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1837 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1838 // If a tail called function callee has more arguments than the caller the
1839 // caller needs to make sure that there is room to move the RETADDR to. This is
1840 // achieved by reserving an area the size of the argument delta right after the
1841 // original REtADDR, but before the saved framepointer or the spilled registers
1842 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1854 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1855 /// for a 16 byte align requirement.
1856 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1857 SelectionDAG& DAG) {
1858 MachineFunction &MF = DAG.getMachineFunction();
1859 const TargetMachine &TM = MF.getTarget();
1860 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1861 unsigned StackAlignment = TFI.getStackAlignment();
1862 uint64_t AlignMask = StackAlignment - 1;
1863 int64_t Offset = StackSize;
1864 uint64_t SlotSize = TD->getPointerSize();
1865 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1866 // Number smaller than 12 so just add the difference.
1867 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1869 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1870 Offset = ((~AlignMask) & Offset) + StackAlignment +
1871 (StackAlignment-SlotSize);
1876 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1877 /// following the call is a return. A function is eligible if caller/callee
1878 /// calling conventions match, currently only fastcc supports tail calls, and
1879 /// the function CALL is immediatly followed by a RET.
1880 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1882 SelectionDAG& DAG) const {
1883 if (!PerformTailCallOpt)
1886 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1887 MachineFunction &MF = DAG.getMachineFunction();
1888 unsigned CallerCC = MF.getFunction()->getCallingConv();
1889 unsigned CalleeCC= TheCall->getCallingConv();
1890 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1891 SDValue Callee = TheCall->getCallee();
1892 // On x86/32Bit PIC/GOT tail calls are supported.
1893 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1894 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1897 // Can only do local tail calls (in same module, hidden or protected) on
1898 // x86_64 PIC/GOT at the moment.
1899 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1900 return G->getGlobal()->hasHiddenVisibility()
1901 || G->getGlobal()->hasProtectedVisibility();
1909 X86TargetLowering::createFastISel(MachineFunction &mf,
1910 MachineModuleInfo *mmo,
1911 DenseMap<const Value *, unsigned> &vm,
1912 DenseMap<const BasicBlock *,
1913 MachineBasicBlock *> &bm,
1914 DenseMap<const AllocaInst *, int> &am
1916 , SmallSet<Instruction*, 8> &cil
1919 return X86::createFastISel(mf, mmo, vm, bm, am
1927 //===----------------------------------------------------------------------===//
1928 // Other Lowering Hooks
1929 //===----------------------------------------------------------------------===//
1932 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1933 MachineFunction &MF = DAG.getMachineFunction();
1934 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1935 int ReturnAddrIndex = FuncInfo->getRAIndex();
1936 uint64_t SlotSize = TD->getPointerSize();
1938 if (ReturnAddrIndex == 0) {
1939 // Set up a frame object for the return address.
1940 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1941 FuncInfo->setRAIndex(ReturnAddrIndex);
1944 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1948 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1949 /// specific condition code. It returns a false if it cannot do a direct
1950 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1952 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1953 unsigned &X86CC, SDValue &LHS, SDValue &RHS,
1954 SelectionDAG &DAG) {
1955 X86CC = X86::COND_INVALID;
1957 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1958 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1959 // X > -1 -> X == 0, jump !sign.
1960 RHS = DAG.getConstant(0, RHS.getValueType());
1961 X86CC = X86::COND_NS;
1963 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1964 // X < 0 -> X == 0, jump on sign.
1965 X86CC = X86::COND_S;
1967 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
1969 RHS = DAG.getConstant(0, RHS.getValueType());
1970 X86CC = X86::COND_LE;
1975 switch (SetCCOpcode) {
1977 case ISD::SETEQ: X86CC = X86::COND_E; break;
1978 case ISD::SETGT: X86CC = X86::COND_G; break;
1979 case ISD::SETGE: X86CC = X86::COND_GE; break;
1980 case ISD::SETLT: X86CC = X86::COND_L; break;
1981 case ISD::SETLE: X86CC = X86::COND_LE; break;
1982 case ISD::SETNE: X86CC = X86::COND_NE; break;
1983 case ISD::SETULT: X86CC = X86::COND_B; break;
1984 case ISD::SETUGT: X86CC = X86::COND_A; break;
1985 case ISD::SETULE: X86CC = X86::COND_BE; break;
1986 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1989 // First determine if it is required or is profitable to flip the operands.
1991 // If LHS is a foldable load, but RHS is not, flip the condition.
1992 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
1993 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
1994 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
1995 std::swap(LHS, RHS);
1998 switch (SetCCOpcode) {
2004 std::swap(LHS, RHS);
2008 // On a floating point condition, the flags are set as follows:
2010 // 0 | 0 | 0 | X > Y
2011 // 0 | 0 | 1 | X < Y
2012 // 1 | 0 | 0 | X == Y
2013 // 1 | 1 | 1 | unordered
2014 switch (SetCCOpcode) {
2018 X86CC = X86::COND_E;
2020 case ISD::SETOLT: // flipped
2023 X86CC = X86::COND_A;
2025 case ISD::SETOLE: // flipped
2028 X86CC = X86::COND_AE;
2030 case ISD::SETUGT: // flipped
2033 X86CC = X86::COND_B;
2035 case ISD::SETUGE: // flipped
2038 X86CC = X86::COND_BE;
2042 X86CC = X86::COND_NE;
2045 X86CC = X86::COND_P;
2048 X86CC = X86::COND_NP;
2053 return X86CC != X86::COND_INVALID;
2056 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2057 /// code. Current x86 isa includes the following FP cmov instructions:
2058 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2059 static bool hasFPCMov(unsigned X86CC) {
2075 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2076 /// true if Op is undef or if its value falls within the specified range (L, H].
2077 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2078 if (Op.getOpcode() == ISD::UNDEF)
2081 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2082 return (Val >= Low && Val < Hi);
2085 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2086 /// true if Op is undef or if its value equal to the specified value.
2087 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2088 if (Op.getOpcode() == ISD::UNDEF)
2090 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2093 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2094 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2095 bool X86::isPSHUFDMask(SDNode *N) {
2096 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2098 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2101 // Check if the value doesn't reference the second vector.
2102 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2103 SDValue Arg = N->getOperand(i);
2104 if (Arg.getOpcode() == ISD::UNDEF) continue;
2105 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2106 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2113 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2114 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2115 bool X86::isPSHUFHWMask(SDNode *N) {
2116 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2118 if (N->getNumOperands() != 8)
2121 // Lower quadword copied in order.
2122 for (unsigned i = 0; i != 4; ++i) {
2123 SDValue Arg = N->getOperand(i);
2124 if (Arg.getOpcode() == ISD::UNDEF) continue;
2125 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2126 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2130 // Upper quadword shuffled.
2131 for (unsigned i = 4; i != 8; ++i) {
2132 SDValue Arg = N->getOperand(i);
2133 if (Arg.getOpcode() == ISD::UNDEF) continue;
2134 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2135 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2136 if (Val < 4 || Val > 7)
2143 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2144 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2145 bool X86::isPSHUFLWMask(SDNode *N) {
2146 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2148 if (N->getNumOperands() != 8)
2151 // Upper quadword copied in order.
2152 for (unsigned i = 4; i != 8; ++i)
2153 if (!isUndefOrEqual(N->getOperand(i), i))
2156 // Lower quadword shuffled.
2157 for (unsigned i = 0; i != 4; ++i)
2158 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2164 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2165 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2166 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2167 if (NumElems != 2 && NumElems != 4) return false;
2169 unsigned Half = NumElems / 2;
2170 for (unsigned i = 0; i < Half; ++i)
2171 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2173 for (unsigned i = Half; i < NumElems; ++i)
2174 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2180 bool X86::isSHUFPMask(SDNode *N) {
2181 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2182 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2185 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2186 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2187 /// half elements to come from vector 1 (which would equal the dest.) and
2188 /// the upper half to come from vector 2.
2189 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2190 if (NumOps != 2 && NumOps != 4) return false;
2192 unsigned Half = NumOps / 2;
2193 for (unsigned i = 0; i < Half; ++i)
2194 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2196 for (unsigned i = Half; i < NumOps; ++i)
2197 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2202 static bool isCommutedSHUFP(SDNode *N) {
2203 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2204 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2207 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2208 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2209 bool X86::isMOVHLPSMask(SDNode *N) {
2210 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2212 if (N->getNumOperands() != 4)
2215 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2216 return isUndefOrEqual(N->getOperand(0), 6) &&
2217 isUndefOrEqual(N->getOperand(1), 7) &&
2218 isUndefOrEqual(N->getOperand(2), 2) &&
2219 isUndefOrEqual(N->getOperand(3), 3);
2222 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2223 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2225 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2226 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2228 if (N->getNumOperands() != 4)
2231 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2232 return isUndefOrEqual(N->getOperand(0), 2) &&
2233 isUndefOrEqual(N->getOperand(1), 3) &&
2234 isUndefOrEqual(N->getOperand(2), 2) &&
2235 isUndefOrEqual(N->getOperand(3), 3);
2238 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2239 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2240 bool X86::isMOVLPMask(SDNode *N) {
2241 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2243 unsigned NumElems = N->getNumOperands();
2244 if (NumElems != 2 && NumElems != 4)
2247 for (unsigned i = 0; i < NumElems/2; ++i)
2248 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2251 for (unsigned i = NumElems/2; i < NumElems; ++i)
2252 if (!isUndefOrEqual(N->getOperand(i), i))
2258 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2259 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2261 bool X86::isMOVHPMask(SDNode *N) {
2262 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2264 unsigned NumElems = N->getNumOperands();
2265 if (NumElems != 2 && NumElems != 4)
2268 for (unsigned i = 0; i < NumElems/2; ++i)
2269 if (!isUndefOrEqual(N->getOperand(i), i))
2272 for (unsigned i = 0; i < NumElems/2; ++i) {
2273 SDValue Arg = N->getOperand(i + NumElems/2);
2274 if (!isUndefOrEqual(Arg, i + NumElems))
2281 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2282 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2283 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2284 bool V2IsSplat = false) {
2285 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2288 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2289 SDValue BitI = Elts[i];
2290 SDValue BitI1 = Elts[i+1];
2291 if (!isUndefOrEqual(BitI, j))
2294 if (isUndefOrEqual(BitI1, NumElts))
2297 if (!isUndefOrEqual(BitI1, j + NumElts))
2305 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2306 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2307 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2310 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2311 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2312 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2313 bool V2IsSplat = false) {
2314 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2317 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2318 SDValue BitI = Elts[i];
2319 SDValue BitI1 = Elts[i+1];
2320 if (!isUndefOrEqual(BitI, j + NumElts/2))
2323 if (isUndefOrEqual(BitI1, NumElts))
2326 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2334 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2335 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2336 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2339 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2340 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2342 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2343 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2345 unsigned NumElems = N->getNumOperands();
2346 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2349 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2350 SDValue BitI = N->getOperand(i);
2351 SDValue BitI1 = N->getOperand(i+1);
2353 if (!isUndefOrEqual(BitI, j))
2355 if (!isUndefOrEqual(BitI1, j))
2362 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2363 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2365 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2366 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2368 unsigned NumElems = N->getNumOperands();
2369 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2372 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2373 SDValue BitI = N->getOperand(i);
2374 SDValue BitI1 = N->getOperand(i + 1);
2376 if (!isUndefOrEqual(BitI, j))
2378 if (!isUndefOrEqual(BitI1, j))
2385 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2386 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2387 /// MOVSD, and MOVD, i.e. setting the lowest element.
2388 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2389 if (NumElts != 2 && NumElts != 4)
2392 if (!isUndefOrEqual(Elts[0], NumElts))
2395 for (unsigned i = 1; i < NumElts; ++i) {
2396 if (!isUndefOrEqual(Elts[i], i))
2403 bool X86::isMOVLMask(SDNode *N) {
2404 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2405 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2408 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2409 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2410 /// element of vector 2 and the other elements to come from vector 1 in order.
2411 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2412 bool V2IsSplat = false,
2413 bool V2IsUndef = false) {
2414 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2417 if (!isUndefOrEqual(Ops[0], 0))
2420 for (unsigned i = 1; i < NumOps; ++i) {
2421 SDValue Arg = Ops[i];
2422 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2423 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2424 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2431 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2432 bool V2IsUndef = false) {
2433 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2434 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2435 V2IsSplat, V2IsUndef);
2438 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2439 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2440 bool X86::isMOVSHDUPMask(SDNode *N) {
2441 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2443 if (N->getNumOperands() != 4)
2446 // Expect 1, 1, 3, 3
2447 for (unsigned i = 0; i < 2; ++i) {
2448 SDValue Arg = N->getOperand(i);
2449 if (Arg.getOpcode() == ISD::UNDEF) continue;
2450 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2451 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2452 if (Val != 1) return false;
2456 for (unsigned i = 2; i < 4; ++i) {
2457 SDValue Arg = N->getOperand(i);
2458 if (Arg.getOpcode() == ISD::UNDEF) continue;
2459 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2460 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2461 if (Val != 3) return false;
2465 // Don't use movshdup if it can be done with a shufps.
2469 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2470 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2471 bool X86::isMOVSLDUPMask(SDNode *N) {
2472 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2474 if (N->getNumOperands() != 4)
2477 // Expect 0, 0, 2, 2
2478 for (unsigned i = 0; i < 2; ++i) {
2479 SDValue Arg = N->getOperand(i);
2480 if (Arg.getOpcode() == ISD::UNDEF) continue;
2481 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2482 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2483 if (Val != 0) return false;
2487 for (unsigned i = 2; i < 4; ++i) {
2488 SDValue Arg = N->getOperand(i);
2489 if (Arg.getOpcode() == ISD::UNDEF) continue;
2490 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2491 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2492 if (Val != 2) return false;
2496 // Don't use movshdup if it can be done with a shufps.
2500 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2501 /// specifies a identity operation on the LHS or RHS.
2502 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2503 unsigned NumElems = N->getNumOperands();
2504 for (unsigned i = 0; i < NumElems; ++i)
2505 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2510 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2511 /// a splat of a single element.
2512 static bool isSplatMask(SDNode *N) {
2513 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2515 // This is a splat operation if each element of the permute is the same, and
2516 // if the value doesn't reference the second vector.
2517 unsigned NumElems = N->getNumOperands();
2518 SDValue ElementBase;
2520 for (; i != NumElems; ++i) {
2521 SDValue Elt = N->getOperand(i);
2522 if (isa<ConstantSDNode>(Elt)) {
2528 if (!ElementBase.getNode())
2531 for (; i != NumElems; ++i) {
2532 SDValue Arg = N->getOperand(i);
2533 if (Arg.getOpcode() == ISD::UNDEF) continue;
2534 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2535 if (Arg != ElementBase) return false;
2538 // Make sure it is a splat of the first vector operand.
2539 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2542 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2543 /// a splat of a single element and it's a 2 or 4 element mask.
2544 bool X86::isSplatMask(SDNode *N) {
2545 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2547 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2548 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2550 return ::isSplatMask(N);
2553 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2554 /// specifies a splat of zero element.
2555 bool X86::isSplatLoMask(SDNode *N) {
2556 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2558 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2559 if (!isUndefOrEqual(N->getOperand(i), 0))
2564 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2565 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2566 bool X86::isMOVDDUPMask(SDNode *N) {
2567 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2569 unsigned e = N->getNumOperands() / 2;
2570 for (unsigned i = 0; i < e; ++i)
2571 if (!isUndefOrEqual(N->getOperand(i), i))
2573 for (unsigned i = 0; i < e; ++i)
2574 if (!isUndefOrEqual(N->getOperand(e+i), i))
2579 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2580 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2582 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2583 unsigned NumOperands = N->getNumOperands();
2584 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2586 for (unsigned i = 0; i < NumOperands; ++i) {
2588 SDValue Arg = N->getOperand(NumOperands-i-1);
2589 if (Arg.getOpcode() != ISD::UNDEF)
2590 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2591 if (Val >= NumOperands) Val -= NumOperands;
2593 if (i != NumOperands - 1)
2600 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2601 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2603 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2605 // 8 nodes, but we only care about the last 4.
2606 for (unsigned i = 7; i >= 4; --i) {
2608 SDValue Arg = N->getOperand(i);
2609 if (Arg.getOpcode() != ISD::UNDEF)
2610 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2619 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2620 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2622 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2624 // 8 nodes, but we only care about the first 4.
2625 for (int i = 3; i >= 0; --i) {
2627 SDValue Arg = N->getOperand(i);
2628 if (Arg.getOpcode() != ISD::UNDEF)
2629 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2638 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2639 /// specifies a 8 element shuffle that can be broken into a pair of
2640 /// PSHUFHW and PSHUFLW.
2641 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2642 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2644 if (N->getNumOperands() != 8)
2647 // Lower quadword shuffled.
2648 for (unsigned i = 0; i != 4; ++i) {
2649 SDValue Arg = N->getOperand(i);
2650 if (Arg.getOpcode() == ISD::UNDEF) continue;
2651 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2652 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2657 // Upper quadword shuffled.
2658 for (unsigned i = 4; i != 8; ++i) {
2659 SDValue Arg = N->getOperand(i);
2660 if (Arg.getOpcode() == ISD::UNDEF) continue;
2661 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2662 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2663 if (Val < 4 || Val > 7)
2670 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2671 /// values in ther permute mask.
2672 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2673 SDValue &V2, SDValue &Mask,
2674 SelectionDAG &DAG) {
2675 MVT VT = Op.getValueType();
2676 MVT MaskVT = Mask.getValueType();
2677 MVT EltVT = MaskVT.getVectorElementType();
2678 unsigned NumElems = Mask.getNumOperands();
2679 SmallVector<SDValue, 8> MaskVec;
2681 for (unsigned i = 0; i != NumElems; ++i) {
2682 SDValue Arg = Mask.getOperand(i);
2683 if (Arg.getOpcode() == ISD::UNDEF) {
2684 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2687 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2688 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2690 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2692 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2696 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2697 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2700 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2701 /// the two vector operands have swapped position.
2703 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2704 MVT MaskVT = Mask.getValueType();
2705 MVT EltVT = MaskVT.getVectorElementType();
2706 unsigned NumElems = Mask.getNumOperands();
2707 SmallVector<SDValue, 8> MaskVec;
2708 for (unsigned i = 0; i != NumElems; ++i) {
2709 SDValue Arg = Mask.getOperand(i);
2710 if (Arg.getOpcode() == ISD::UNDEF) {
2711 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2714 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2715 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2717 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2719 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2721 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2725 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2726 /// match movhlps. The lower half elements should come from upper half of
2727 /// V1 (and in order), and the upper half elements should come from the upper
2728 /// half of V2 (and in order).
2729 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2730 unsigned NumElems = Mask->getNumOperands();
2733 for (unsigned i = 0, e = 2; i != e; ++i)
2734 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2736 for (unsigned i = 2; i != 4; ++i)
2737 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2742 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2743 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2745 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2746 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2748 N = N->getOperand(0).getNode();
2749 if (!ISD::isNON_EXTLoad(N))
2752 *LD = cast<LoadSDNode>(N);
2756 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2757 /// match movlp{s|d}. The lower half elements should come from lower half of
2758 /// V1 (and in order), and the upper half elements should come from the upper
2759 /// half of V2 (and in order). And since V1 will become the source of the
2760 /// MOVLP, it must be either a vector load or a scalar load to vector.
2761 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2762 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2764 // Is V2 is a vector load, don't do this transformation. We will try to use
2765 // load folding shufps op.
2766 if (ISD::isNON_EXTLoad(V2))
2769 unsigned NumElems = Mask->getNumOperands();
2770 if (NumElems != 2 && NumElems != 4)
2772 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2773 if (!isUndefOrEqual(Mask->getOperand(i), i))
2775 for (unsigned i = NumElems/2; i != NumElems; ++i)
2776 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2781 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2783 static bool isSplatVector(SDNode *N) {
2784 if (N->getOpcode() != ISD::BUILD_VECTOR)
2787 SDValue SplatValue = N->getOperand(0);
2788 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2789 if (N->getOperand(i) != SplatValue)
2794 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2796 static bool isUndefShuffle(SDNode *N) {
2797 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2800 SDValue V1 = N->getOperand(0);
2801 SDValue V2 = N->getOperand(1);
2802 SDValue Mask = N->getOperand(2);
2803 unsigned NumElems = Mask.getNumOperands();
2804 for (unsigned i = 0; i != NumElems; ++i) {
2805 SDValue Arg = Mask.getOperand(i);
2806 if (Arg.getOpcode() != ISD::UNDEF) {
2807 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2808 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2810 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2817 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2819 static inline bool isZeroNode(SDValue Elt) {
2820 return ((isa<ConstantSDNode>(Elt) &&
2821 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2822 (isa<ConstantFPSDNode>(Elt) &&
2823 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2826 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2827 /// to an zero vector.
2828 static bool isZeroShuffle(SDNode *N) {
2829 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2832 SDValue V1 = N->getOperand(0);
2833 SDValue V2 = N->getOperand(1);
2834 SDValue Mask = N->getOperand(2);
2835 unsigned NumElems = Mask.getNumOperands();
2836 for (unsigned i = 0; i != NumElems; ++i) {
2837 SDValue Arg = Mask.getOperand(i);
2838 if (Arg.getOpcode() == ISD::UNDEF)
2841 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2842 if (Idx < NumElems) {
2843 unsigned Opc = V1.getNode()->getOpcode();
2844 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2846 if (Opc != ISD::BUILD_VECTOR ||
2847 !isZeroNode(V1.getNode()->getOperand(Idx)))
2849 } else if (Idx >= NumElems) {
2850 unsigned Opc = V2.getNode()->getOpcode();
2851 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2853 if (Opc != ISD::BUILD_VECTOR ||
2854 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2861 /// getZeroVector - Returns a vector of specified type with all zero elements.
2863 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2864 assert(VT.isVector() && "Expected a vector type");
2866 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2867 // type. This ensures they get CSE'd.
2869 if (VT.getSizeInBits() == 64) { // MMX
2870 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2871 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2872 } else if (HasSSE2) { // SSE2
2873 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2874 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2876 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2877 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2879 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2882 /// getOnesVector - Returns a vector of specified type with all bits set.
2884 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2885 assert(VT.isVector() && "Expected a vector type");
2887 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2888 // type. This ensures they get CSE'd.
2889 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2891 if (VT.getSizeInBits() == 64) // MMX
2892 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2894 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2895 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2899 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2900 /// that point to V2 points to its first element.
2901 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2902 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2904 bool Changed = false;
2905 SmallVector<SDValue, 8> MaskVec;
2906 unsigned NumElems = Mask.getNumOperands();
2907 for (unsigned i = 0; i != NumElems; ++i) {
2908 SDValue Arg = Mask.getOperand(i);
2909 if (Arg.getOpcode() != ISD::UNDEF) {
2910 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2911 if (Val > NumElems) {
2912 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2916 MaskVec.push_back(Arg);
2920 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2921 &MaskVec[0], MaskVec.size());
2925 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2926 /// operation of specified width.
2927 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2928 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2929 MVT BaseVT = MaskVT.getVectorElementType();
2931 SmallVector<SDValue, 8> MaskVec;
2932 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2933 for (unsigned i = 1; i != NumElems; ++i)
2934 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2935 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2938 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2939 /// of specified width.
2940 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2941 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2942 MVT BaseVT = MaskVT.getVectorElementType();
2943 SmallVector<SDValue, 8> MaskVec;
2944 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2945 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2946 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2948 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2951 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2952 /// of specified width.
2953 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2954 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2955 MVT BaseVT = MaskVT.getVectorElementType();
2956 unsigned Half = NumElems/2;
2957 SmallVector<SDValue, 8> MaskVec;
2958 for (unsigned i = 0; i != Half; ++i) {
2959 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2960 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2962 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2965 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2966 /// element #0 of a vector with the specified index, leaving the rest of the
2967 /// elements in place.
2968 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2969 SelectionDAG &DAG) {
2970 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2971 MVT BaseVT = MaskVT.getVectorElementType();
2972 SmallVector<SDValue, 8> MaskVec;
2973 // Element #0 of the result gets the elt we are replacing.
2974 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2975 for (unsigned i = 1; i != NumElems; ++i)
2976 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2977 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2980 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2981 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
2982 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2983 MVT VT = Op.getValueType();
2986 SDValue V1 = Op.getOperand(0);
2987 SDValue Mask = Op.getOperand(2);
2988 unsigned NumElems = Mask.getNumOperands();
2989 // Special handling of v4f32 -> v4i32.
2990 if (VT != MVT::v4f32) {
2991 Mask = getUnpacklMask(NumElems, DAG);
2992 while (NumElems > 4) {
2993 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2996 Mask = getZeroVector(MVT::v4i32, true, DAG);
2999 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
3000 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
3001 DAG.getNode(ISD::UNDEF, PVT), Mask);
3002 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3005 /// isVectorLoad - Returns true if the node is a vector load, a scalar
3006 /// load that's promoted to vector, or a load bitcasted.
3007 static bool isVectorLoad(SDValue Op) {
3008 assert(Op.getValueType().isVector() && "Expected a vector type");
3009 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
3010 Op.getOpcode() == ISD::BIT_CONVERT) {
3011 return isa<LoadSDNode>(Op.getOperand(0));
3013 return isa<LoadSDNode>(Op);
3017 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3019 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3020 SelectionDAG &DAG, bool HasSSE3) {
3021 // If we have sse3 and shuffle has more than one use or input is a load, then
3022 // use movddup. Otherwise, use movlhps.
3023 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3024 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3025 MVT VT = Op.getValueType();
3028 unsigned NumElems = PVT.getVectorNumElements();
3029 if (NumElems == 2) {
3030 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3031 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
3033 assert(NumElems == 4);
3034 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3035 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3036 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst0, Cst1, Cst0, Cst1);
3039 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
3040 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
3041 DAG.getNode(ISD::UNDEF, PVT), Mask);
3042 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3045 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3046 /// vector of zero or undef vector. This produces a shuffle where the low
3047 /// element of V2 is swizzled into the zero/undef vector, landing at element
3048 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3049 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3050 bool isZero, bool HasSSE2,
3051 SelectionDAG &DAG) {
3052 MVT VT = V2.getValueType();
3054 ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
3055 unsigned NumElems = V2.getValueType().getVectorNumElements();
3056 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3057 MVT EVT = MaskVT.getVectorElementType();
3058 SmallVector<SDValue, 16> MaskVec;
3059 for (unsigned i = 0; i != NumElems; ++i)
3060 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3061 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3063 MaskVec.push_back(DAG.getConstant(i, EVT));
3064 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3065 &MaskVec[0], MaskVec.size());
3066 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3069 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3070 /// a shuffle that is zero.
3072 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3073 unsigned NumElems, bool Low,
3074 SelectionDAG &DAG) {
3075 unsigned NumZeros = 0;
3076 for (unsigned i = 0; i < NumElems; ++i) {
3077 unsigned Index = Low ? i : NumElems-i-1;
3078 SDValue Idx = Mask.getOperand(Index);
3079 if (Idx.getOpcode() == ISD::UNDEF) {
3083 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3084 if (Elt.getNode() && isZeroNode(Elt))
3092 /// isVectorShift - Returns true if the shuffle can be implemented as a
3093 /// logical left or right shift of a vector.
3094 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3095 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3096 unsigned NumElems = Mask.getNumOperands();
3099 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3102 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3107 bool SeenV1 = false;
3108 bool SeenV2 = false;
3109 for (unsigned i = NumZeros; i < NumElems; ++i) {
3110 unsigned Val = isLeft ? (i - NumZeros) : i;
3111 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3112 if (Idx.getOpcode() == ISD::UNDEF)
3114 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3115 if (Index < NumElems)
3124 if (SeenV1 && SeenV2)
3127 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3133 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3135 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3136 unsigned NumNonZero, unsigned NumZero,
3137 SelectionDAG &DAG, TargetLowering &TLI) {
3143 for (unsigned i = 0; i < 16; ++i) {
3144 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3145 if (ThisIsNonZero && First) {
3147 V = getZeroVector(MVT::v8i16, true, DAG);
3149 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3154 SDValue ThisElt(0, 0), LastElt(0, 0);
3155 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3156 if (LastIsNonZero) {
3157 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3159 if (ThisIsNonZero) {
3160 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3161 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3162 ThisElt, DAG.getConstant(8, MVT::i8));
3164 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3168 if (ThisElt.getNode())
3169 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3170 DAG.getIntPtrConstant(i/2));
3174 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3177 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3179 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3180 unsigned NumNonZero, unsigned NumZero,
3181 SelectionDAG &DAG, TargetLowering &TLI) {
3187 for (unsigned i = 0; i < 8; ++i) {
3188 bool isNonZero = (NonZeros & (1 << i)) != 0;
3192 V = getZeroVector(MVT::v8i16, true, DAG);
3194 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3197 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3198 DAG.getIntPtrConstant(i));
3205 /// getVShift - Return a vector logical shift node.
3207 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3208 unsigned NumBits, SelectionDAG &DAG,
3209 const TargetLowering &TLI) {
3210 bool isMMX = VT.getSizeInBits() == 64;
3211 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3212 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3213 SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3214 return DAG.getNode(ISD::BIT_CONVERT, VT,
3215 DAG.getNode(Opc, ShVT, SrcOp,
3216 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3220 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3221 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3222 if (ISD::isBuildVectorAllZeros(Op.getNode())
3223 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3224 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3225 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3226 // eliminated on x86-32 hosts.
3227 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3230 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3231 return getOnesVector(Op.getValueType(), DAG);
3232 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3235 MVT VT = Op.getValueType();
3236 MVT EVT = VT.getVectorElementType();
3237 unsigned EVTBits = EVT.getSizeInBits();
3239 unsigned NumElems = Op.getNumOperands();
3240 unsigned NumZero = 0;
3241 unsigned NumNonZero = 0;
3242 unsigned NonZeros = 0;
3243 bool IsAllConstants = true;
3244 SmallSet<SDValue, 8> Values;
3245 for (unsigned i = 0; i < NumElems; ++i) {
3246 SDValue Elt = Op.getOperand(i);
3247 if (Elt.getOpcode() == ISD::UNDEF)
3250 if (Elt.getOpcode() != ISD::Constant &&
3251 Elt.getOpcode() != ISD::ConstantFP)
3252 IsAllConstants = false;
3253 if (isZeroNode(Elt))
3256 NonZeros |= (1 << i);
3261 if (NumNonZero == 0) {
3262 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3263 return DAG.getNode(ISD::UNDEF, VT);
3266 // Special case for single non-zero, non-undef, element.
3267 if (NumNonZero == 1 && NumElems <= 4) {
3268 unsigned Idx = CountTrailingZeros_32(NonZeros);
3269 SDValue Item = Op.getOperand(Idx);
3271 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3272 // the value are obviously zero, truncate the value to i32 and do the
3273 // insertion that way. Only do this if the value is non-constant or if the
3274 // value is a constant being inserted into element 0. It is cheaper to do
3275 // a constant pool load than it is to do a movd + shuffle.
3276 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3277 (!IsAllConstants || Idx == 0)) {
3278 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3279 // Handle MMX and SSE both.
3280 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3281 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3283 // Truncate the value (which may itself be a constant) to i32, and
3284 // convert it to a vector with movd (S2V+shuffle to zero extend).
3285 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3286 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3287 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3288 Subtarget->hasSSE2(), DAG);
3290 // Now we have our 32-bit value zero extended in the low element of
3291 // a vector. If Idx != 0, swizzle it into place.
3294 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3295 getSwapEltZeroMask(VecElts, Idx, DAG)
3297 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3299 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3303 // If we have a constant or non-constant insertion into the low element of
3304 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3305 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3306 // depending on what the source datatype is. Because we can only get here
3307 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3309 // Don't do this for i64 values on x86-32.
3310 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3311 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3312 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3313 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3314 Subtarget->hasSSE2(), DAG);
3317 // Is it a vector logical left shift?
3318 if (NumElems == 2 && Idx == 1 &&
3319 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3320 unsigned NumBits = VT.getSizeInBits();
3321 return getVShift(true, VT,
3322 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3323 NumBits/2, DAG, *this);
3326 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3329 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3330 // is a non-constant being inserted into an element other than the low one,
3331 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3332 // movd/movss) to move this into the low element, then shuffle it into
3334 if (EVTBits == 32) {
3335 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3337 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3338 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3339 Subtarget->hasSSE2(), DAG);
3340 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3341 MVT MaskEVT = MaskVT.getVectorElementType();
3342 SmallVector<SDValue, 8> MaskVec;
3343 for (unsigned i = 0; i < NumElems; i++)
3344 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3345 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3346 &MaskVec[0], MaskVec.size());
3347 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3348 DAG.getNode(ISD::UNDEF, VT), Mask);
3352 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3353 if (Values.size() == 1)
3356 // A vector full of immediates; various special cases are already
3357 // handled, so this is best done with a single constant-pool load.
3361 // Let legalizer expand 2-wide build_vectors.
3362 if (EVTBits == 64) {
3363 if (NumNonZero == 1) {
3364 // One half is zero or undef.
3365 unsigned Idx = CountTrailingZeros_32(NonZeros);
3366 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3367 Op.getOperand(Idx));
3368 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3369 Subtarget->hasSSE2(), DAG);
3374 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3375 if (EVTBits == 8 && NumElems == 16) {
3376 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3378 if (V.getNode()) return V;
3381 if (EVTBits == 16 && NumElems == 8) {
3382 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3384 if (V.getNode()) return V;
3387 // If element VT is == 32 bits, turn it into a number of shuffles.
3388 SmallVector<SDValue, 8> V;
3390 if (NumElems == 4 && NumZero > 0) {
3391 for (unsigned i = 0; i < 4; ++i) {
3392 bool isZero = !(NonZeros & (1 << i));
3394 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3396 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3399 for (unsigned i = 0; i < 2; ++i) {
3400 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3403 V[i] = V[i*2]; // Must be a zero vector.
3406 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3407 getMOVLMask(NumElems, DAG));
3410 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3411 getMOVLMask(NumElems, DAG));
3414 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3415 getUnpacklMask(NumElems, DAG));
3420 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3421 MVT EVT = MaskVT.getVectorElementType();
3422 SmallVector<SDValue, 8> MaskVec;
3423 bool Reverse = (NonZeros & 0x3) == 2;
3424 for (unsigned i = 0; i < 2; ++i)
3426 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3428 MaskVec.push_back(DAG.getConstant(i, EVT));
3429 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3430 for (unsigned i = 0; i < 2; ++i)
3432 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3434 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3435 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3436 &MaskVec[0], MaskVec.size());
3437 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3440 if (Values.size() > 2) {
3441 // Expand into a number of unpckl*.
3443 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3444 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3445 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3446 SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3447 for (unsigned i = 0; i < NumElems; ++i)
3448 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3450 while (NumElems != 0) {
3451 for (unsigned i = 0; i < NumElems; ++i)
3452 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3463 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3464 SDValue PermMask, SelectionDAG &DAG,
3465 TargetLowering &TLI) {
3467 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3468 MVT MaskEVT = MaskVT.getVectorElementType();
3469 MVT PtrVT = TLI.getPointerTy();
3470 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3471 PermMask.getNode()->op_end());
3473 // First record which half of which vector the low elements come from.
3474 SmallVector<unsigned, 4> LowQuad(4);
3475 for (unsigned i = 0; i < 4; ++i) {
3476 SDValue Elt = MaskElts[i];
3477 if (Elt.getOpcode() == ISD::UNDEF)
3479 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3480 int QuadIdx = EltIdx / 4;
3484 int BestLowQuad = -1;
3485 unsigned MaxQuad = 1;
3486 for (unsigned i = 0; i < 4; ++i) {
3487 if (LowQuad[i] > MaxQuad) {
3489 MaxQuad = LowQuad[i];
3493 // Record which half of which vector the high elements come from.
3494 SmallVector<unsigned, 4> HighQuad(4);
3495 for (unsigned i = 4; i < 8; ++i) {
3496 SDValue Elt = MaskElts[i];
3497 if (Elt.getOpcode() == ISD::UNDEF)
3499 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3500 int QuadIdx = EltIdx / 4;
3501 ++HighQuad[QuadIdx];
3504 int BestHighQuad = -1;
3506 for (unsigned i = 0; i < 4; ++i) {
3507 if (HighQuad[i] > MaxQuad) {
3509 MaxQuad = HighQuad[i];
3513 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3514 if (BestLowQuad != -1 || BestHighQuad != -1) {
3515 // First sort the 4 chunks in order using shufpd.
3516 SmallVector<SDValue, 8> MaskVec;
3518 if (BestLowQuad != -1)
3519 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3521 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3523 if (BestHighQuad != -1)
3524 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3526 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3528 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3529 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3530 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3531 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3532 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3534 // Now sort high and low parts separately.
3535 BitVector InOrder(8);
3536 if (BestLowQuad != -1) {
3537 // Sort lower half in order using PSHUFLW.
3539 bool AnyOutOrder = false;
3541 for (unsigned i = 0; i != 4; ++i) {
3542 SDValue Elt = MaskElts[i];
3543 if (Elt.getOpcode() == ISD::UNDEF) {
3544 MaskVec.push_back(Elt);
3547 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3551 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3553 // If this element is in the right place after this shuffle, then
3555 if ((int)(EltIdx / 4) == BestLowQuad)
3560 for (unsigned i = 4; i != 8; ++i)
3561 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3562 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3563 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3567 if (BestHighQuad != -1) {
3568 // Sort high half in order using PSHUFHW if possible.
3571 for (unsigned i = 0; i != 4; ++i)
3572 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3574 bool AnyOutOrder = false;
3575 for (unsigned i = 4; i != 8; ++i) {
3576 SDValue Elt = MaskElts[i];
3577 if (Elt.getOpcode() == ISD::UNDEF) {
3578 MaskVec.push_back(Elt);
3581 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3585 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3587 // If this element is in the right place after this shuffle, then
3589 if ((int)(EltIdx / 4) == BestHighQuad)
3595 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3596 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3600 // The other elements are put in the right place using pextrw and pinsrw.
3601 for (unsigned i = 0; i != 8; ++i) {
3604 SDValue Elt = MaskElts[i];
3605 if (Elt.getOpcode() == ISD::UNDEF)
3607 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3608 SDValue ExtOp = (EltIdx < 8)
3609 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3610 DAG.getConstant(EltIdx, PtrVT))
3611 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3612 DAG.getConstant(EltIdx - 8, PtrVT));
3613 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3614 DAG.getConstant(i, PtrVT));
3620 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3621 // few as possible. First, let's find out how many elements are already in the
3623 unsigned V1InOrder = 0;
3624 unsigned V1FromV1 = 0;
3625 unsigned V2InOrder = 0;
3626 unsigned V2FromV2 = 0;
3627 SmallVector<SDValue, 8> V1Elts;
3628 SmallVector<SDValue, 8> V2Elts;
3629 for (unsigned i = 0; i < 8; ++i) {
3630 SDValue Elt = MaskElts[i];
3631 if (Elt.getOpcode() == ISD::UNDEF) {
3632 V1Elts.push_back(Elt);
3633 V2Elts.push_back(Elt);
3638 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3640 V1Elts.push_back(Elt);
3641 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3643 } else if (EltIdx == i+8) {
3644 V1Elts.push_back(Elt);
3645 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3647 } else if (EltIdx < 8) {
3648 V1Elts.push_back(Elt);
3651 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3656 if (V2InOrder > V1InOrder) {
3657 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3659 std::swap(V1Elts, V2Elts);
3660 std::swap(V1FromV1, V2FromV2);
3663 if ((V1FromV1 + V1InOrder) != 8) {
3664 // Some elements are from V2.
3666 // If there are elements that are from V1 but out of place,
3667 // then first sort them in place
3668 SmallVector<SDValue, 8> MaskVec;
3669 for (unsigned i = 0; i < 8; ++i) {
3670 SDValue Elt = V1Elts[i];
3671 if (Elt.getOpcode() == ISD::UNDEF) {
3672 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3675 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3677 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3679 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3681 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3682 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3686 for (unsigned i = 0; i < 8; ++i) {
3687 SDValue Elt = V1Elts[i];
3688 if (Elt.getOpcode() == ISD::UNDEF)
3690 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3693 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3694 DAG.getConstant(EltIdx - 8, PtrVT));
3695 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3696 DAG.getConstant(i, PtrVT));
3700 // All elements are from V1.
3702 for (unsigned i = 0; i < 8; ++i) {
3703 SDValue Elt = V1Elts[i];
3704 if (Elt.getOpcode() == ISD::UNDEF)
3706 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3707 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3708 DAG.getConstant(EltIdx, PtrVT));
3709 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3710 DAG.getConstant(i, PtrVT));
3716 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3717 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3718 /// done when every pair / quad of shuffle mask elements point to elements in
3719 /// the right sequence. e.g.
3720 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3722 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3724 SDValue PermMask, SelectionDAG &DAG,
3725 TargetLowering &TLI) {
3726 unsigned NumElems = PermMask.getNumOperands();
3727 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3728 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3729 MVT MaskEltVT = MaskVT.getVectorElementType();
3731 switch (VT.getSimpleVT()) {
3732 default: assert(false && "Unexpected!");
3733 case MVT::v4f32: NewVT = MVT::v2f64; break;
3734 case MVT::v4i32: NewVT = MVT::v2i64; break;
3735 case MVT::v8i16: NewVT = MVT::v4i32; break;
3736 case MVT::v16i8: NewVT = MVT::v4i32; break;
3739 if (NewWidth == 2) {
3745 unsigned Scale = NumElems / NewWidth;
3746 SmallVector<SDValue, 8> MaskVec;
3747 for (unsigned i = 0; i < NumElems; i += Scale) {
3748 unsigned StartIdx = ~0U;
3749 for (unsigned j = 0; j < Scale; ++j) {
3750 SDValue Elt = PermMask.getOperand(i+j);
3751 if (Elt.getOpcode() == ISD::UNDEF)
3753 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3754 if (StartIdx == ~0U)
3755 StartIdx = EltIdx - (EltIdx % Scale);
3756 if (EltIdx != StartIdx + j)
3759 if (StartIdx == ~0U)
3760 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3762 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3765 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3766 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3767 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3768 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3769 &MaskVec[0], MaskVec.size()));
3772 /// getVZextMovL - Return a zero-extending vector move low node.
3774 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3775 SDValue SrcOp, SelectionDAG &DAG,
3776 const X86Subtarget *Subtarget) {
3777 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3778 LoadSDNode *LD = NULL;
3779 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3780 LD = dyn_cast<LoadSDNode>(SrcOp);
3782 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3784 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3785 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3786 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3787 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3788 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3790 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3791 return DAG.getNode(ISD::BIT_CONVERT, VT,
3792 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3793 DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3800 return DAG.getNode(ISD::BIT_CONVERT, VT,
3801 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3802 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3805 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3808 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3809 SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3810 MVT MaskVT = PermMask.getValueType();
3811 MVT MaskEVT = MaskVT.getVectorElementType();
3812 SmallVector<std::pair<int, int>, 8> Locs;
3814 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3817 for (unsigned i = 0; i != 4; ++i) {
3818 SDValue Elt = PermMask.getOperand(i);
3819 if (Elt.getOpcode() == ISD::UNDEF) {
3820 Locs[i] = std::make_pair(-1, -1);
3822 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3823 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3825 Locs[i] = std::make_pair(0, NumLo);
3829 Locs[i] = std::make_pair(1, NumHi);
3831 Mask1[2+NumHi] = Elt;
3837 if (NumLo <= 2 && NumHi <= 2) {
3838 // If no more than two elements come from either vector. This can be
3839 // implemented with two shuffles. First shuffle gather the elements.
3840 // The second shuffle, which takes the first shuffle as both of its
3841 // vector operands, put the elements into the right order.
3842 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3843 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3844 &Mask1[0], Mask1.size()));
3846 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3847 for (unsigned i = 0; i != 4; ++i) {
3848 if (Locs[i].first == -1)
3851 unsigned Idx = (i < 2) ? 0 : 4;
3852 Idx += Locs[i].first * 2 + Locs[i].second;
3853 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3857 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3858 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3859 &Mask2[0], Mask2.size()));
3860 } else if (NumLo == 3 || NumHi == 3) {
3861 // Otherwise, we must have three elements from one vector, call it X, and
3862 // one element from the other, call it Y. First, use a shufps to build an
3863 // intermediate vector with the one element from Y and the element from X
3864 // that will be in the same half in the final destination (the indexes don't
3865 // matter). Then, use a shufps to build the final vector, taking the half
3866 // containing the element from Y from the intermediate, and the other half
3869 // Normalize it so the 3 elements come from V1.
3870 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3874 // Find the element from V2.
3876 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3877 SDValue Elt = PermMask.getOperand(HiIndex);
3878 if (Elt.getOpcode() == ISD::UNDEF)
3880 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3885 Mask1[0] = PermMask.getOperand(HiIndex);
3886 Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3887 Mask1[2] = PermMask.getOperand(HiIndex^1);
3888 Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3889 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3890 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3893 Mask1[0] = PermMask.getOperand(0);
3894 Mask1[1] = PermMask.getOperand(1);
3895 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3896 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3897 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3898 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3900 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3901 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3902 Mask1[2] = PermMask.getOperand(2);
3903 Mask1[3] = PermMask.getOperand(3);
3904 if (Mask1[2].getOpcode() != ISD::UNDEF)
3906 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3908 if (Mask1[3].getOpcode() != ISD::UNDEF)
3910 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3912 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3913 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3917 // Break it into (shuffle shuffle_hi, shuffle_lo).
3919 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3920 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3921 SmallVector<SDValue,8> *MaskPtr = &LoMask;
3922 unsigned MaskIdx = 0;
3925 for (unsigned i = 0; i != 4; ++i) {
3932 SDValue Elt = PermMask.getOperand(i);
3933 if (Elt.getOpcode() == ISD::UNDEF) {
3934 Locs[i] = std::make_pair(-1, -1);
3935 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
3936 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3937 (*MaskPtr)[LoIdx] = Elt;
3940 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3941 (*MaskPtr)[HiIdx] = Elt;
3946 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3947 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3948 &LoMask[0], LoMask.size()));
3949 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3950 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3951 &HiMask[0], HiMask.size()));
3952 SmallVector<SDValue, 8> MaskOps;
3953 for (unsigned i = 0; i != 4; ++i) {
3954 if (Locs[i].first == -1) {
3955 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3957 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3958 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3961 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3962 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3963 &MaskOps[0], MaskOps.size()));
3967 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3968 SDValue V1 = Op.getOperand(0);
3969 SDValue V2 = Op.getOperand(1);
3970 SDValue PermMask = Op.getOperand(2);
3971 MVT VT = Op.getValueType();
3972 unsigned NumElems = PermMask.getNumOperands();
3973 bool isMMX = VT.getSizeInBits() == 64;
3974 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3975 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3976 bool V1IsSplat = false;
3977 bool V2IsSplat = false;
3979 if (isUndefShuffle(Op.getNode()))
3980 return DAG.getNode(ISD::UNDEF, VT);
3982 if (isZeroShuffle(Op.getNode()))
3983 return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3985 if (isIdentityMask(PermMask.getNode()))
3987 else if (isIdentityMask(PermMask.getNode(), true))
3990 // Canonicalize movddup shuffles.
3991 if (V2IsUndef && Subtarget->hasSSE2() &&
3992 VT.getSizeInBits() == 128 &&
3993 X86::isMOVDDUPMask(PermMask.getNode()))
3994 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
3996 if (isSplatMask(PermMask.getNode())) {
3997 if (isMMX || NumElems < 4) return Op;
3998 // Promote it to a v4{if}32 splat.
3999 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
4002 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4004 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4005 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
4006 if (NewOp.getNode())
4007 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
4008 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4009 // FIXME: Figure out a cleaner way to do this.
4010 // Try to make use of movq to zero out the top part.
4011 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4012 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4014 if (NewOp.getNode()) {
4015 SDValue NewV1 = NewOp.getOperand(0);
4016 SDValue NewV2 = NewOp.getOperand(1);
4017 SDValue NewMask = NewOp.getOperand(2);
4018 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4019 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4020 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
4023 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4024 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4026 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4027 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4032 // Check if this can be converted into a logical shift.
4033 bool isLeft = false;
4036 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4037 if (isShift && ShVal.hasOneUse()) {
4038 // If the shifted value has multiple uses, it may be cheaper to use
4039 // v_set0 + movlhps or movhlps, etc.
4040 MVT EVT = VT.getVectorElementType();
4041 ShAmt *= EVT.getSizeInBits();
4042 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4045 if (X86::isMOVLMask(PermMask.getNode())) {
4048 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4049 return getVZextMovL(VT, VT, V2, DAG, Subtarget);
4054 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4055 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4056 X86::isMOVHLPSMask(PermMask.getNode()) ||
4057 X86::isMOVHPMask(PermMask.getNode()) ||
4058 X86::isMOVLPMask(PermMask.getNode())))
4061 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4062 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4063 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4066 // No better options. Use a vshl / vsrl.
4067 MVT EVT = VT.getVectorElementType();
4068 ShAmt *= EVT.getSizeInBits();
4069 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4072 bool Commuted = false;
4073 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4074 // 1,1,1,1 -> v8i16 though.
4075 V1IsSplat = isSplatVector(V1.getNode());
4076 V2IsSplat = isSplatVector(V2.getNode());
4078 // Canonicalize the splat or undef, if present, to be on the RHS.
4079 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4080 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4081 std::swap(V1IsSplat, V2IsSplat);
4082 std::swap(V1IsUndef, V2IsUndef);
4086 // FIXME: Figure out a cleaner way to do this.
4087 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4088 if (V2IsUndef) return V1;
4089 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4091 // V2 is a splat, so the mask may be malformed. That is, it may point
4092 // to any V2 element. The instruction selectior won't like this. Get
4093 // a corrected mask and commute to form a proper MOVS{S|D}.
4094 SDValue NewMask = getMOVLMask(NumElems, DAG);
4095 if (NewMask.getNode() != PermMask.getNode())
4096 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4101 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4102 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4103 X86::isUNPCKLMask(PermMask.getNode()) ||
4104 X86::isUNPCKHMask(PermMask.getNode()))
4108 // Normalize mask so all entries that point to V2 points to its first
4109 // element then try to match unpck{h|l} again. If match, return a
4110 // new vector_shuffle with the corrected mask.
4111 SDValue NewMask = NormalizeMask(PermMask, DAG);
4112 if (NewMask.getNode() != PermMask.getNode()) {
4113 if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
4114 SDValue NewMask = getUnpacklMask(NumElems, DAG);
4115 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4116 } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
4117 SDValue NewMask = getUnpackhMask(NumElems, DAG);
4118 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4123 // Normalize the node to match x86 shuffle ops if needed
4124 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4125 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4128 // Commute is back and try unpck* again.
4129 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4130 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4131 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4132 X86::isUNPCKLMask(PermMask.getNode()) ||
4133 X86::isUNPCKHMask(PermMask.getNode()))
4137 // Try PSHUF* first, then SHUFP*.
4138 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4139 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4140 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4141 if (V2.getOpcode() != ISD::UNDEF)
4142 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
4143 DAG.getNode(ISD::UNDEF, VT), PermMask);
4148 if (Subtarget->hasSSE2() &&
4149 (X86::isPSHUFDMask(PermMask.getNode()) ||
4150 X86::isPSHUFHWMask(PermMask.getNode()) ||
4151 X86::isPSHUFLWMask(PermMask.getNode()))) {
4153 if (VT == MVT::v4f32) {
4155 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
4156 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
4157 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4158 } else if (V2.getOpcode() != ISD::UNDEF)
4159 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
4160 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4162 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4166 // Binary or unary shufps.
4167 if (X86::isSHUFPMask(PermMask.getNode()) ||
4168 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4172 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4173 if (VT == MVT::v8i16) {
4174 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4175 if (NewOp.getNode())
4179 // Handle all 4 wide cases with a number of shuffles except for MMX.
4180 if (NumElems == 4 && !isMMX)
4181 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4187 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4188 SelectionDAG &DAG) {
4189 MVT VT = Op.getValueType();
4190 if (VT.getSizeInBits() == 8) {
4191 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4192 Op.getOperand(0), Op.getOperand(1));
4193 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4194 DAG.getValueType(VT));
4195 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4196 } else if (VT.getSizeInBits() == 16) {
4197 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4198 Op.getOperand(0), Op.getOperand(1));
4199 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4200 DAG.getValueType(VT));
4201 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4202 } else if (VT == MVT::f32) {
4203 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4204 // the result back to FR32 register. It's only worth matching if the
4205 // result has a single use which is a store or a bitcast to i32. And in
4206 // the case of a store, it's not worth it if the index is a constant 0,
4207 // because a MOVSSmr can be used instead, which is smaller and faster.
4208 if (!Op.hasOneUse())
4210 SDNode *User = *Op.getNode()->use_begin();
4211 if ((User->getOpcode() != ISD::STORE ||
4212 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4213 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4214 (User->getOpcode() != ISD::BIT_CONVERT ||
4215 User->getValueType(0) != MVT::i32))
4217 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4218 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4220 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4227 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4228 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4231 if (Subtarget->hasSSE41()) {
4232 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4237 MVT VT = Op.getValueType();
4238 // TODO: handle v16i8.
4239 if (VT.getSizeInBits() == 16) {
4240 SDValue Vec = Op.getOperand(0);
4241 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4243 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4244 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4245 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4247 // Transform it so it match pextrw which produces a 32-bit result.
4248 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4249 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4250 Op.getOperand(0), Op.getOperand(1));
4251 SDValue Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
4252 DAG.getValueType(VT));
4253 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4254 } else if (VT.getSizeInBits() == 32) {
4255 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4258 // SHUFPS the element to the lowest double word, then movss.
4259 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4260 SmallVector<SDValue, 8> IdxVec;
4262 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4264 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4266 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4268 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4269 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4270 &IdxVec[0], IdxVec.size());
4271 SDValue Vec = Op.getOperand(0);
4272 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4273 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4274 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4275 DAG.getIntPtrConstant(0));
4276 } else if (VT.getSizeInBits() == 64) {
4277 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4278 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4279 // to match extract_elt for f64.
4280 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4284 // UNPCKHPD the element to the lowest double word, then movsd.
4285 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4286 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4287 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4288 SmallVector<SDValue, 8> IdxVec;
4289 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4291 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4292 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4293 &IdxVec[0], IdxVec.size());
4294 SDValue Vec = Op.getOperand(0);
4295 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4296 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4297 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4298 DAG.getIntPtrConstant(0));
4305 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4306 MVT VT = Op.getValueType();
4307 MVT EVT = VT.getVectorElementType();
4309 SDValue N0 = Op.getOperand(0);
4310 SDValue N1 = Op.getOperand(1);
4311 SDValue N2 = Op.getOperand(2);
4313 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4314 isa<ConstantSDNode>(N2)) {
4315 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4317 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4319 if (N1.getValueType() != MVT::i32)
4320 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4321 if (N2.getValueType() != MVT::i32)
4322 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4323 return DAG.getNode(Opc, VT, N0, N1, N2);
4324 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4325 // Bits [7:6] of the constant are the source select. This will always be
4326 // zero here. The DAG Combiner may combine an extract_elt index into these
4327 // bits. For example (insert (extract, 3), 2) could be matched by putting
4328 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4329 // Bits [5:4] of the constant are the destination select. This is the
4330 // value of the incoming immediate.
4331 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4332 // combine either bitwise AND or insert of float 0.0 to set these bits.
4333 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4334 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4340 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4341 MVT VT = Op.getValueType();
4342 MVT EVT = VT.getVectorElementType();
4344 if (Subtarget->hasSSE41())
4345 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4350 SDValue N0 = Op.getOperand(0);
4351 SDValue N1 = Op.getOperand(1);
4352 SDValue N2 = Op.getOperand(2);
4354 if (EVT.getSizeInBits() == 16) {
4355 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4356 // as its second argument.
4357 if (N1.getValueType() != MVT::i32)
4358 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4359 if (N2.getValueType() != MVT::i32)
4360 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4361 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4367 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4368 if (Op.getValueType() == MVT::v2f32)
4369 return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4370 DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4371 DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4372 Op.getOperand(0))));
4374 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4375 MVT VT = MVT::v2i32;
4376 switch (Op.getValueType().getSimpleVT()) {
4383 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4384 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4387 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4388 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4389 // one of the above mentioned nodes. It has to be wrapped because otherwise
4390 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4391 // be used to form addressing mode. These wrapped nodes will be selected
4394 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4395 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4396 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4398 CP->getAlignment());
4399 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4400 // With PIC, the address is actually $g + Offset.
4401 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4402 !Subtarget->isPICStyleRIPRel()) {
4403 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4404 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4412 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
4414 SelectionDAG &DAG) const {
4415 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4416 bool ExtraLoadRequired =
4417 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4419 // Create the TargetGlobalAddress node, folding in the constant
4420 // offset if it is legal.
4422 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4423 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4426 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4427 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4429 // With PIC, the address is actually $g + Offset.
4430 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4431 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4432 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4436 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4437 // load the value at address GV, not the value of GV itself. This means that
4438 // the GlobalAddress must be in the base or index register of the address, not
4439 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4440 // The same applies for external symbols during PIC codegen
4441 if (ExtraLoadRequired)
4442 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4443 PseudoSourceValue::getGOT(), 0);
4445 // If there was a non-zero offset that we didn't fold, create an explicit
4448 Result = DAG.getNode(ISD::ADD, getPointerTy(), Result,
4449 DAG.getConstant(Offset, getPointerTy()));
4455 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4456 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4457 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4458 return LowerGlobalAddress(GV, Offset, DAG);
4461 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4463 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4466 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4467 DAG.getNode(X86ISD::GlobalBaseReg,
4469 InFlag = Chain.getValue(1);
4471 // emit leal symbol@TLSGD(,%ebx,1), %eax
4472 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4473 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4474 GA->getValueType(0),
4476 SDValue Ops[] = { Chain, TGA, InFlag };
4477 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4478 InFlag = Result.getValue(2);
4479 Chain = Result.getValue(1);
4481 // call ___tls_get_addr. This function receives its argument in
4482 // the register EAX.
4483 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4484 InFlag = Chain.getValue(1);
4486 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4487 SDValue Ops1[] = { Chain,
4488 DAG.getTargetExternalSymbol("___tls_get_addr",
4490 DAG.getRegister(X86::EAX, PtrVT),
4491 DAG.getRegister(X86::EBX, PtrVT),
4493 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4494 InFlag = Chain.getValue(1);
4496 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4499 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4501 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4503 SDValue InFlag, Chain;
4505 // emit leaq symbol@TLSGD(%rip), %rdi
4506 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4507 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4508 GA->getValueType(0),
4510 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4511 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4512 Chain = Result.getValue(1);
4513 InFlag = Result.getValue(2);
4515 // call __tls_get_addr. This function receives its argument in
4516 // the register RDI.
4517 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4518 InFlag = Chain.getValue(1);
4520 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4521 SDValue Ops1[] = { Chain,
4522 DAG.getTargetExternalSymbol("__tls_get_addr",
4524 DAG.getRegister(X86::RDI, PtrVT),
4526 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4527 InFlag = Chain.getValue(1);
4529 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4532 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4533 // "local exec" model.
4534 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4536 // Get the Thread Pointer
4537 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4538 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4540 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4541 GA->getValueType(0),
4543 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4545 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4546 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4547 PseudoSourceValue::getGOT(), 0);
4549 // The address of the thread local variable is the add of the thread
4550 // pointer with the offset of the variable.
4551 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4555 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4556 // TODO: implement the "local dynamic" model
4557 // TODO: implement the "initial exec"model for pic executables
4558 assert(Subtarget->isTargetELF() &&
4559 "TLS not implemented for non-ELF targets");
4560 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4561 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4562 // otherwise use the "Local Exec"TLS Model
4563 if (Subtarget->is64Bit()) {
4564 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4566 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4567 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4569 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4574 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4575 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4576 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4577 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4578 // With PIC, the address is actually $g + Offset.
4579 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4580 !Subtarget->isPICStyleRIPRel()) {
4581 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4582 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4589 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4590 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4591 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4592 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4593 // With PIC, the address is actually $g + Offset.
4594 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4595 !Subtarget->isPICStyleRIPRel()) {
4596 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4597 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4604 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4605 /// take a 2 x i32 value to shift plus a shift amount.
4606 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4607 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4608 MVT VT = Op.getValueType();
4609 unsigned VTBits = VT.getSizeInBits();
4610 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4611 SDValue ShOpLo = Op.getOperand(0);
4612 SDValue ShOpHi = Op.getOperand(1);
4613 SDValue ShAmt = Op.getOperand(2);
4614 SDValue Tmp1 = isSRA ?
4615 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4616 DAG.getConstant(0, VT);
4619 if (Op.getOpcode() == ISD::SHL_PARTS) {
4620 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4621 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4623 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4624 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4627 SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4628 DAG.getConstant(VTBits, MVT::i8));
4629 SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4630 AndNode, DAG.getConstant(0, MVT::i8));
4633 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4634 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4635 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4637 if (Op.getOpcode() == ISD::SHL_PARTS) {
4638 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4639 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4641 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4642 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4645 SDValue Ops[2] = { Lo, Hi };
4646 return DAG.getMergeValues(Ops, 2);
4649 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4650 MVT SrcVT = Op.getOperand(0).getValueType();
4651 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4652 "Unknown SINT_TO_FP to lower!");
4654 // These are really Legal; caller falls through into that case.
4655 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4657 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4658 Subtarget->is64Bit())
4661 unsigned Size = SrcVT.getSizeInBits()/8;
4662 MachineFunction &MF = DAG.getMachineFunction();
4663 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4664 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4665 SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4667 PseudoSourceValue::getFixedStack(SSFI), 0);
4671 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4673 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4675 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4676 SmallVector<SDValue, 8> Ops;
4677 Ops.push_back(Chain);
4678 Ops.push_back(StackSlot);
4679 Ops.push_back(DAG.getValueType(SrcVT));
4680 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4681 Tys, &Ops[0], Ops.size());
4684 Chain = Result.getValue(1);
4685 SDValue InFlag = Result.getValue(2);
4687 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4688 // shouldn't be necessary except that RFP cannot be live across
4689 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4690 MachineFunction &MF = DAG.getMachineFunction();
4691 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4692 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4693 Tys = DAG.getVTList(MVT::Other);
4694 SmallVector<SDValue, 8> Ops;
4695 Ops.push_back(Chain);
4696 Ops.push_back(Result);
4697 Ops.push_back(StackSlot);
4698 Ops.push_back(DAG.getValueType(Op.getValueType()));
4699 Ops.push_back(InFlag);
4700 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4701 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4702 PseudoSourceValue::getFixedStack(SSFI), 0);
4708 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4709 MVT SrcVT = Op.getOperand(0).getValueType();
4710 assert(SrcVT.getSimpleVT() == MVT::i64 && "Unknown UINT_TO_FP to lower!");
4712 // We only handle SSE2 f64 target here; caller can handle the rest.
4713 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4716 // This algorithm is not obvious. Here it is in C code, more or less:
4718 double uint64_to_double( uint32_t hi, uint32_t lo )
4720 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4721 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4723 // copy ints to xmm registers
4724 __m128i xh = _mm_cvtsi32_si128( hi );
4725 __m128i xl = _mm_cvtsi32_si128( lo );
4727 // combine into low half of a single xmm register
4728 __m128i x = _mm_unpacklo_epi32( xh, xl );
4732 // merge in appropriate exponents to give the integer bits the
4734 x = _mm_unpacklo_epi32( x, exp );
4736 // subtract away the biases to deal with the IEEE-754 double precision
4738 d = _mm_sub_pd( (__m128d) x, bias );
4740 // All conversions up to here are exact. The correctly rounded result is
4741 // calculated using the
4742 // current rounding mode using the following horizontal add.
4743 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4744 _mm_store_sd( &sd, d ); //since we are returning doubles in XMM, this
4745 // store doesn't really need to be here (except maybe to zero the other
4751 // Build some magic constants.
4752 std::vector<Constant*>CV0;
4753 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4754 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4755 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4756 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4757 Constant *C0 = ConstantVector::get(CV0);
4758 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
4760 std::vector<Constant*>CV1;
4761 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4762 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4763 Constant *C1 = ConstantVector::get(CV1);
4764 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
4766 SmallVector<SDValue, 4> MaskVec;
4767 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
4768 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
4769 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
4770 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
4771 SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, &MaskVec[0],
4773 SmallVector<SDValue, 4> MaskVec2;
4774 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
4775 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
4776 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec2[0],
4779 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4780 DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4782 DAG.getIntPtrConstant(1)));
4783 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4784 DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4786 DAG.getIntPtrConstant(0)));
4787 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
4788 XR1, XR2, UnpcklMask);
4789 SDValue CLod0 = DAG.getLoad(MVT::v4i32, DAG.getEntryNode(), CPIdx0,
4790 PseudoSourceValue::getConstantPool(), 0, false, 16);
4791 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
4792 Unpck1, CLod0, UnpcklMask);
4793 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, MVT::v2f64, Unpck2);
4794 SDValue CLod1 = DAG.getLoad(MVT::v2f64, CLod0.getValue(1), CPIdx1,
4795 PseudoSourceValue::getConstantPool(), 0, false, 16);
4796 SDValue Sub = DAG.getNode(ISD::FSUB, MVT::v2f64, XR2F, CLod1);
4797 // Add the halves; easiest way is to swap them into another reg first.
4798 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2f64,
4799 Sub, Sub, ShufMask);
4800 SDValue Add = DAG.getNode(ISD::FADD, MVT::v2f64, Shuf, Sub);
4801 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f64, Add,
4802 DAG.getIntPtrConstant(0));
4805 std::pair<SDValue,SDValue> X86TargetLowering::
4806 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4807 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4808 Op.getValueType().getSimpleVT() >= MVT::i16 &&
4809 "Unknown FP_TO_SINT to lower!");
4811 // These are really Legal.
4812 if (Op.getValueType() == MVT::i32 &&
4813 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4814 return std::make_pair(SDValue(), SDValue());
4815 if (Subtarget->is64Bit() &&
4816 Op.getValueType() == MVT::i64 &&
4817 Op.getOperand(0).getValueType() != MVT::f80)
4818 return std::make_pair(SDValue(), SDValue());
4820 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4822 MachineFunction &MF = DAG.getMachineFunction();
4823 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4824 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4825 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4827 switch (Op.getValueType().getSimpleVT()) {
4828 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4829 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4830 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4831 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4834 SDValue Chain = DAG.getEntryNode();
4835 SDValue Value = Op.getOperand(0);
4836 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4837 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4838 Chain = DAG.getStore(Chain, Value, StackSlot,
4839 PseudoSourceValue::getFixedStack(SSFI), 0);
4840 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4842 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4844 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4845 Chain = Value.getValue(1);
4846 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4847 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4850 // Build the FP_TO_INT*_IN_MEM
4851 SDValue Ops[] = { Chain, Value, StackSlot };
4852 SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4854 return std::make_pair(FIST, StackSlot);
4857 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4858 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4859 SDValue FIST = Vals.first, StackSlot = Vals.second;
4860 if (FIST.getNode() == 0) return SDValue();
4863 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4866 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4867 MVT VT = Op.getValueType();
4870 EltVT = VT.getVectorElementType();
4871 std::vector<Constant*> CV;
4872 if (EltVT == MVT::f64) {
4873 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4877 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4883 Constant *C = ConstantVector::get(CV);
4884 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4885 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4886 PseudoSourceValue::getConstantPool(), 0,
4888 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4891 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4892 MVT VT = Op.getValueType();
4894 unsigned EltNum = 1;
4895 if (VT.isVector()) {
4896 EltVT = VT.getVectorElementType();
4897 EltNum = VT.getVectorNumElements();
4899 std::vector<Constant*> CV;
4900 if (EltVT == MVT::f64) {
4901 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4905 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4911 Constant *C = ConstantVector::get(CV);
4912 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4913 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4914 PseudoSourceValue::getConstantPool(), 0,
4916 if (VT.isVector()) {
4917 return DAG.getNode(ISD::BIT_CONVERT, VT,
4918 DAG.getNode(ISD::XOR, MVT::v2i64,
4919 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4920 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4922 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4926 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4927 SDValue Op0 = Op.getOperand(0);
4928 SDValue Op1 = Op.getOperand(1);
4929 MVT VT = Op.getValueType();
4930 MVT SrcVT = Op1.getValueType();
4932 // If second operand is smaller, extend it first.
4933 if (SrcVT.bitsLT(VT)) {
4934 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4937 // And if it is bigger, shrink it first.
4938 if (SrcVT.bitsGT(VT)) {
4939 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4943 // At this point the operands and the result should have the same
4944 // type, and that won't be f80 since that is not custom lowered.
4946 // First get the sign bit of second operand.
4947 std::vector<Constant*> CV;
4948 if (SrcVT == MVT::f64) {
4949 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4950 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4952 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4953 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4954 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4955 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4957 Constant *C = ConstantVector::get(CV);
4958 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4959 SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4960 PseudoSourceValue::getConstantPool(), 0,
4962 SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4964 // Shift sign bit right or left if the two operands have different types.
4965 if (SrcVT.bitsGT(VT)) {
4966 // Op0 is MVT::f32, Op1 is MVT::f64.
4967 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4968 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4969 DAG.getConstant(32, MVT::i32));
4970 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4971 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4972 DAG.getIntPtrConstant(0));
4975 // Clear first operand sign bit.
4977 if (VT == MVT::f64) {
4978 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4979 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4981 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4982 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4983 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4984 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4986 C = ConstantVector::get(CV);
4987 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4988 SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4989 PseudoSourceValue::getConstantPool(), 0,
4991 SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4993 // Or the value with the sign bit.
4994 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4997 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
4998 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5000 SDValue Op0 = Op.getOperand(0);
5001 SDValue Op1 = Op.getOperand(1);
5002 SDValue CC = Op.getOperand(2);
5003 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5006 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
5008 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
5009 return DAG.getNode(X86ISD::SETCC, MVT::i8,
5010 DAG.getConstant(X86CC, MVT::i8), Cond);
5013 assert(0 && "Illegal SetCC!");
5017 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5019 SDValue Op0 = Op.getOperand(0);
5020 SDValue Op1 = Op.getOperand(1);
5021 SDValue CC = Op.getOperand(2);
5022 MVT VT = Op.getValueType();
5023 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5024 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5028 MVT VT0 = Op0.getValueType();
5029 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5030 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5033 switch (SetCCOpcode) {
5036 case ISD::SETEQ: SSECC = 0; break;
5038 case ISD::SETGT: Swap = true; // Fallthrough
5040 case ISD::SETOLT: SSECC = 1; break;
5042 case ISD::SETGE: Swap = true; // Fallthrough
5044 case ISD::SETOLE: SSECC = 2; break;
5045 case ISD::SETUO: SSECC = 3; break;
5047 case ISD::SETNE: SSECC = 4; break;
5048 case ISD::SETULE: Swap = true;
5049 case ISD::SETUGE: SSECC = 5; break;
5050 case ISD::SETULT: Swap = true;
5051 case ISD::SETUGT: SSECC = 6; break;
5052 case ISD::SETO: SSECC = 7; break;
5055 std::swap(Op0, Op1);
5057 // In the two special cases we can't handle, emit two comparisons.
5059 if (SetCCOpcode == ISD::SETUEQ) {
5061 UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5062 EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5063 return DAG.getNode(ISD::OR, VT, UNORD, EQ);
5065 else if (SetCCOpcode == ISD::SETONE) {
5067 ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5068 NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5069 return DAG.getNode(ISD::AND, VT, ORD, NEQ);
5071 assert(0 && "Illegal FP comparison");
5073 // Handle all other FP comparisons here.
5074 return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5077 // We are handling one of the integer comparisons here. Since SSE only has
5078 // GT and EQ comparisons for integer, swapping operands and multiple
5079 // operations may be required for some comparisons.
5080 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5081 bool Swap = false, Invert = false, FlipSigns = false;
5083 switch (VT.getSimpleVT()) {
5085 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5086 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5087 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5088 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5091 switch (SetCCOpcode) {
5093 case ISD::SETNE: Invert = true;
5094 case ISD::SETEQ: Opc = EQOpc; break;
5095 case ISD::SETLT: Swap = true;
5096 case ISD::SETGT: Opc = GTOpc; break;
5097 case ISD::SETGE: Swap = true;
5098 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5099 case ISD::SETULT: Swap = true;
5100 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5101 case ISD::SETUGE: Swap = true;
5102 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5105 std::swap(Op0, Op1);
5107 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5108 // bits of the inputs before performing those operations.
5110 MVT EltVT = VT.getVectorElementType();
5111 SDValue SignBit = DAG.getConstant(EltVT.getIntegerVTSignBit(), EltVT);
5112 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5113 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
5115 Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
5116 Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
5119 SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
5121 // If the logical-not of the result is required, perform that now.
5123 MVT EltVT = VT.getVectorElementType();
5124 SDValue NegOne = DAG.getConstant(EltVT.getIntegerVTBitMask(), EltVT);
5125 std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOne);
5126 SDValue NegOneV = DAG.getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0],
5128 Result = DAG.getNode(ISD::XOR, VT, Result, NegOneV);
5133 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5134 static bool isX86LogicalCmp(unsigned Opc) {
5135 return Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI;
5138 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5139 bool addTest = true;
5140 SDValue Cond = Op.getOperand(0);
5143 if (Cond.getOpcode() == ISD::SETCC)
5144 Cond = LowerSETCC(Cond, DAG);
5146 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5147 // setting operand in place of the X86ISD::SETCC.
5148 if (Cond.getOpcode() == X86ISD::SETCC) {
5149 CC = Cond.getOperand(0);
5151 SDValue Cmp = Cond.getOperand(1);
5152 unsigned Opc = Cmp.getOpcode();
5153 MVT VT = Op.getValueType();
5155 bool IllegalFPCMov = false;
5156 if (VT.isFloatingPoint() && !VT.isVector() &&
5157 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5158 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5160 if (isX86LogicalCmp(Opc) && !IllegalFPCMov) {
5167 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5168 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5171 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5173 SmallVector<SDValue, 4> Ops;
5174 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5175 // condition is true.
5176 Ops.push_back(Op.getOperand(2));
5177 Ops.push_back(Op.getOperand(1));
5179 Ops.push_back(Cond);
5180 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
5183 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5184 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5185 // from the AND / OR.
5186 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5187 Opc = Op.getOpcode();
5188 if (Opc != ISD::OR && Opc != ISD::AND)
5190 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5191 Op.getOperand(0).hasOneUse() &&
5192 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5193 Op.getOperand(1).hasOneUse());
5196 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5197 bool addTest = true;
5198 SDValue Chain = Op.getOperand(0);
5199 SDValue Cond = Op.getOperand(1);
5200 SDValue Dest = Op.getOperand(2);
5203 if (Cond.getOpcode() == ISD::SETCC)
5204 Cond = LowerSETCC(Cond, DAG);
5205 else if (Cond.getOpcode() == ISD::SADDO || Cond.getOpcode() == ISD::UADDO)
5206 Cond = LowerXADDO(Cond, DAG);
5208 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5209 // setting operand in place of the X86ISD::SETCC.
5210 if (Cond.getOpcode() == X86ISD::SETCC) {
5211 CC = Cond.getOperand(0);
5213 SDValue Cmp = Cond.getOperand(1);
5214 unsigned Opc = Cmp.getOpcode();
5215 if (isX86LogicalCmp(Opc)) {
5219 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5223 // These can only come from an arithmetic instruction with overflow, e.g.
5225 Cond = Cond.getNode()->getOperand(1);
5232 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5233 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5234 unsigned Opc = Cmp.getOpcode();
5235 if (CondOpc == ISD::OR) {
5236 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5237 // two branches instead of an explicit OR instruction with a
5239 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5240 isX86LogicalCmp(Opc)) {
5241 CC = Cond.getOperand(0).getOperand(0);
5242 Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5243 Chain, Dest, CC, Cmp);
5244 CC = Cond.getOperand(1).getOperand(0);
5248 } else { // ISD::AND
5249 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5250 // two branches instead of an explicit AND instruction with a
5251 // separate test. However, we only do this if this block doesn't
5252 // have a fall-through edge, because this requires an explicit
5253 // jmp when the condition is false.
5254 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5255 isX86LogicalCmp(Opc) &&
5256 Op.getNode()->hasOneUse()) {
5257 X86::CondCode CCode =
5258 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5259 CCode = X86::GetOppositeBranchCondition(CCode);
5260 CC = DAG.getConstant(CCode, MVT::i8);
5261 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5262 // Look for an unconditional branch following this conditional branch.
5263 // We need this because we need to reverse the successors in order
5264 // to implement FCMP_OEQ.
5265 if (User.getOpcode() == ISD::BR) {
5266 SDValue FalseBB = User.getOperand(1);
5268 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5269 assert(NewBR == User);
5272 Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5273 Chain, Dest, CC, Cmp);
5274 X86::CondCode CCode =
5275 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5276 CCode = X86::GetOppositeBranchCondition(CCode);
5277 CC = DAG.getConstant(CCode, MVT::i8);
5287 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5288 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5290 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5291 Chain, Dest, CC, Cond);
5295 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5296 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5297 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5298 // that the guard pages used by the OS virtual memory manager are allocated in
5299 // correct sequence.
5301 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5302 SelectionDAG &DAG) {
5303 assert(Subtarget->isTargetCygMing() &&
5304 "This should be used only on Cygwin/Mingw targets");
5307 SDValue Chain = Op.getOperand(0);
5308 SDValue Size = Op.getOperand(1);
5309 // FIXME: Ensure alignment here
5313 MVT IntPtr = getPointerTy();
5314 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5316 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5318 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
5319 Flag = Chain.getValue(1);
5321 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5322 SDValue Ops[] = { Chain,
5323 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5324 DAG.getRegister(X86::EAX, IntPtr),
5325 DAG.getRegister(X86StackPtr, SPTy),
5327 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
5328 Flag = Chain.getValue(1);
5330 Chain = DAG.getCALLSEQ_END(Chain,
5331 DAG.getIntPtrConstant(0, true),
5332 DAG.getIntPtrConstant(0, true),
5335 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5337 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5338 return DAG.getMergeValues(Ops1, 2);
5342 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5344 SDValue Dst, SDValue Src,
5345 SDValue Size, unsigned Align,
5347 uint64_t DstSVOff) {
5348 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5350 // If not DWORD aligned or size is more than the threshold, call the library.
5351 // The libc version is likely to be faster for these cases. It can use the
5352 // address value and run time information about the CPU.
5353 if ((Align & 3) != 0 ||
5355 ConstantSize->getZExtValue() >
5356 getSubtarget()->getMaxInlineSizeThreshold()) {
5357 SDValue InFlag(0, 0);
5359 // Check to see if there is a specialized entry-point for memory zeroing.
5360 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5362 if (const char *bzeroEntry = V &&
5363 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5364 MVT IntPtr = getPointerTy();
5365 const Type *IntPtrTy = TD->getIntPtrType();
5366 TargetLowering::ArgListTy Args;
5367 TargetLowering::ArgListEntry Entry;
5369 Entry.Ty = IntPtrTy;
5370 Args.push_back(Entry);
5372 Args.push_back(Entry);
5373 std::pair<SDValue,SDValue> CallResult =
5374 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5375 CallingConv::C, false,
5376 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG);
5377 return CallResult.second;
5380 // Otherwise have the target-independent code call memset.
5384 uint64_t SizeVal = ConstantSize->getZExtValue();
5385 SDValue InFlag(0, 0);
5388 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5389 unsigned BytesLeft = 0;
5390 bool TwoRepStos = false;
5393 uint64_t Val = ValC->getZExtValue() & 255;
5395 // If the value is a constant, then we can potentially use larger sets.
5396 switch (Align & 3) {
5397 case 2: // WORD aligned
5400 Val = (Val << 8) | Val;
5402 case 0: // DWORD aligned
5405 Val = (Val << 8) | Val;
5406 Val = (Val << 16) | Val;
5407 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5410 Val = (Val << 32) | Val;
5413 default: // Byte aligned
5416 Count = DAG.getIntPtrConstant(SizeVal);
5420 if (AVT.bitsGT(MVT::i8)) {
5421 unsigned UBytes = AVT.getSizeInBits() / 8;
5422 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5423 BytesLeft = SizeVal % UBytes;
5426 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5428 InFlag = Chain.getValue(1);
5431 Count = DAG.getIntPtrConstant(SizeVal);
5432 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5433 InFlag = Chain.getValue(1);
5436 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5438 InFlag = Chain.getValue(1);
5439 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5441 InFlag = Chain.getValue(1);
5443 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5444 SmallVector<SDValue, 8> Ops;
5445 Ops.push_back(Chain);
5446 Ops.push_back(DAG.getValueType(AVT));
5447 Ops.push_back(InFlag);
5448 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5451 InFlag = Chain.getValue(1);
5453 MVT CVT = Count.getValueType();
5454 SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5455 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5456 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5458 InFlag = Chain.getValue(1);
5459 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5461 Ops.push_back(Chain);
5462 Ops.push_back(DAG.getValueType(MVT::i8));
5463 Ops.push_back(InFlag);
5464 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5465 } else if (BytesLeft) {
5466 // Handle the last 1 - 7 bytes.
5467 unsigned Offset = SizeVal - BytesLeft;
5468 MVT AddrVT = Dst.getValueType();
5469 MVT SizeVT = Size.getValueType();
5471 Chain = DAG.getMemset(Chain,
5472 DAG.getNode(ISD::ADD, AddrVT, Dst,
5473 DAG.getConstant(Offset, AddrVT)),
5475 DAG.getConstant(BytesLeft, SizeVT),
5476 Align, DstSV, DstSVOff + Offset);
5479 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5484 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5485 SDValue Chain, SDValue Dst, SDValue Src,
5486 SDValue Size, unsigned Align,
5488 const Value *DstSV, uint64_t DstSVOff,
5489 const Value *SrcSV, uint64_t SrcSVOff) {
5490 // This requires the copy size to be a constant, preferrably
5491 // within a subtarget-specific limit.
5492 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5495 uint64_t SizeVal = ConstantSize->getZExtValue();
5496 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5499 /// If not DWORD aligned, call the library.
5500 if ((Align & 3) != 0)
5505 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5508 unsigned UBytes = AVT.getSizeInBits() / 8;
5509 unsigned CountVal = SizeVal / UBytes;
5510 SDValue Count = DAG.getIntPtrConstant(CountVal);
5511 unsigned BytesLeft = SizeVal % UBytes;
5513 SDValue InFlag(0, 0);
5514 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5516 InFlag = Chain.getValue(1);
5517 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5519 InFlag = Chain.getValue(1);
5520 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5522 InFlag = Chain.getValue(1);
5524 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5525 SmallVector<SDValue, 8> Ops;
5526 Ops.push_back(Chain);
5527 Ops.push_back(DAG.getValueType(AVT));
5528 Ops.push_back(InFlag);
5529 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5531 SmallVector<SDValue, 4> Results;
5532 Results.push_back(RepMovs);
5534 // Handle the last 1 - 7 bytes.
5535 unsigned Offset = SizeVal - BytesLeft;
5536 MVT DstVT = Dst.getValueType();
5537 MVT SrcVT = Src.getValueType();
5538 MVT SizeVT = Size.getValueType();
5539 Results.push_back(DAG.getMemcpy(Chain,
5540 DAG.getNode(ISD::ADD, DstVT, Dst,
5541 DAG.getConstant(Offset, DstVT)),
5542 DAG.getNode(ISD::ADD, SrcVT, Src,
5543 DAG.getConstant(Offset, SrcVT)),
5544 DAG.getConstant(BytesLeft, SizeVT),
5545 Align, AlwaysInline,
5546 DstSV, DstSVOff + Offset,
5547 SrcSV, SrcSVOff + Offset));
5550 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5553 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5554 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5556 if (!Subtarget->is64Bit()) {
5557 // vastart just stores the address of the VarArgsFrameIndex slot into the
5558 // memory location argument.
5559 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5560 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5564 // gp_offset (0 - 6 * 8)
5565 // fp_offset (48 - 48 + 8 * 16)
5566 // overflow_arg_area (point to parameters coming in memory).
5568 SmallVector<SDValue, 8> MemOps;
5569 SDValue FIN = Op.getOperand(1);
5571 SDValue Store = DAG.getStore(Op.getOperand(0),
5572 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5574 MemOps.push_back(Store);
5577 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5578 Store = DAG.getStore(Op.getOperand(0),
5579 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5581 MemOps.push_back(Store);
5583 // Store ptr to overflow_arg_area
5584 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5585 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5586 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5587 MemOps.push_back(Store);
5589 // Store ptr to reg_save_area.
5590 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5591 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5592 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5593 MemOps.push_back(Store);
5594 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5597 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5598 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5599 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5600 SDValue Chain = Op.getOperand(0);
5601 SDValue SrcPtr = Op.getOperand(1);
5602 SDValue SrcSV = Op.getOperand(2);
5604 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5609 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5610 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5611 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5612 SDValue Chain = Op.getOperand(0);
5613 SDValue DstPtr = Op.getOperand(1);
5614 SDValue SrcPtr = Op.getOperand(2);
5615 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5616 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5618 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5619 DAG.getIntPtrConstant(24), 8, false,
5620 DstSV, 0, SrcSV, 0);
5624 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5625 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5627 default: return SDValue(); // Don't custom lower most intrinsics.
5628 // Comparison intrinsics.
5629 case Intrinsic::x86_sse_comieq_ss:
5630 case Intrinsic::x86_sse_comilt_ss:
5631 case Intrinsic::x86_sse_comile_ss:
5632 case Intrinsic::x86_sse_comigt_ss:
5633 case Intrinsic::x86_sse_comige_ss:
5634 case Intrinsic::x86_sse_comineq_ss:
5635 case Intrinsic::x86_sse_ucomieq_ss:
5636 case Intrinsic::x86_sse_ucomilt_ss:
5637 case Intrinsic::x86_sse_ucomile_ss:
5638 case Intrinsic::x86_sse_ucomigt_ss:
5639 case Intrinsic::x86_sse_ucomige_ss:
5640 case Intrinsic::x86_sse_ucomineq_ss:
5641 case Intrinsic::x86_sse2_comieq_sd:
5642 case Intrinsic::x86_sse2_comilt_sd:
5643 case Intrinsic::x86_sse2_comile_sd:
5644 case Intrinsic::x86_sse2_comigt_sd:
5645 case Intrinsic::x86_sse2_comige_sd:
5646 case Intrinsic::x86_sse2_comineq_sd:
5647 case Intrinsic::x86_sse2_ucomieq_sd:
5648 case Intrinsic::x86_sse2_ucomilt_sd:
5649 case Intrinsic::x86_sse2_ucomile_sd:
5650 case Intrinsic::x86_sse2_ucomigt_sd:
5651 case Intrinsic::x86_sse2_ucomige_sd:
5652 case Intrinsic::x86_sse2_ucomineq_sd: {
5654 ISD::CondCode CC = ISD::SETCC_INVALID;
5657 case Intrinsic::x86_sse_comieq_ss:
5658 case Intrinsic::x86_sse2_comieq_sd:
5662 case Intrinsic::x86_sse_comilt_ss:
5663 case Intrinsic::x86_sse2_comilt_sd:
5667 case Intrinsic::x86_sse_comile_ss:
5668 case Intrinsic::x86_sse2_comile_sd:
5672 case Intrinsic::x86_sse_comigt_ss:
5673 case Intrinsic::x86_sse2_comigt_sd:
5677 case Intrinsic::x86_sse_comige_ss:
5678 case Intrinsic::x86_sse2_comige_sd:
5682 case Intrinsic::x86_sse_comineq_ss:
5683 case Intrinsic::x86_sse2_comineq_sd:
5687 case Intrinsic::x86_sse_ucomieq_ss:
5688 case Intrinsic::x86_sse2_ucomieq_sd:
5689 Opc = X86ISD::UCOMI;
5692 case Intrinsic::x86_sse_ucomilt_ss:
5693 case Intrinsic::x86_sse2_ucomilt_sd:
5694 Opc = X86ISD::UCOMI;
5697 case Intrinsic::x86_sse_ucomile_ss:
5698 case Intrinsic::x86_sse2_ucomile_sd:
5699 Opc = X86ISD::UCOMI;
5702 case Intrinsic::x86_sse_ucomigt_ss:
5703 case Intrinsic::x86_sse2_ucomigt_sd:
5704 Opc = X86ISD::UCOMI;
5707 case Intrinsic::x86_sse_ucomige_ss:
5708 case Intrinsic::x86_sse2_ucomige_sd:
5709 Opc = X86ISD::UCOMI;
5712 case Intrinsic::x86_sse_ucomineq_ss:
5713 case Intrinsic::x86_sse2_ucomineq_sd:
5714 Opc = X86ISD::UCOMI;
5720 SDValue LHS = Op.getOperand(1);
5721 SDValue RHS = Op.getOperand(2);
5722 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5724 SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5725 SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5726 DAG.getConstant(X86CC, MVT::i8), Cond);
5727 return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
5730 // Fix vector shift instructions where the last operand is a non-immediate
5732 case Intrinsic::x86_sse2_pslli_w:
5733 case Intrinsic::x86_sse2_pslli_d:
5734 case Intrinsic::x86_sse2_pslli_q:
5735 case Intrinsic::x86_sse2_psrli_w:
5736 case Intrinsic::x86_sse2_psrli_d:
5737 case Intrinsic::x86_sse2_psrli_q:
5738 case Intrinsic::x86_sse2_psrai_w:
5739 case Intrinsic::x86_sse2_psrai_d:
5740 case Intrinsic::x86_mmx_pslli_w:
5741 case Intrinsic::x86_mmx_pslli_d:
5742 case Intrinsic::x86_mmx_pslli_q:
5743 case Intrinsic::x86_mmx_psrli_w:
5744 case Intrinsic::x86_mmx_psrli_d:
5745 case Intrinsic::x86_mmx_psrli_q:
5746 case Intrinsic::x86_mmx_psrai_w:
5747 case Intrinsic::x86_mmx_psrai_d: {
5748 SDValue ShAmt = Op.getOperand(2);
5749 if (isa<ConstantSDNode>(ShAmt))
5752 unsigned NewIntNo = 0;
5753 MVT ShAmtVT = MVT::v4i32;
5755 case Intrinsic::x86_sse2_pslli_w:
5756 NewIntNo = Intrinsic::x86_sse2_psll_w;
5758 case Intrinsic::x86_sse2_pslli_d:
5759 NewIntNo = Intrinsic::x86_sse2_psll_d;
5761 case Intrinsic::x86_sse2_pslli_q:
5762 NewIntNo = Intrinsic::x86_sse2_psll_q;
5764 case Intrinsic::x86_sse2_psrli_w:
5765 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5767 case Intrinsic::x86_sse2_psrli_d:
5768 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5770 case Intrinsic::x86_sse2_psrli_q:
5771 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5773 case Intrinsic::x86_sse2_psrai_w:
5774 NewIntNo = Intrinsic::x86_sse2_psra_w;
5776 case Intrinsic::x86_sse2_psrai_d:
5777 NewIntNo = Intrinsic::x86_sse2_psra_d;
5780 ShAmtVT = MVT::v2i32;
5782 case Intrinsic::x86_mmx_pslli_w:
5783 NewIntNo = Intrinsic::x86_mmx_psll_w;
5785 case Intrinsic::x86_mmx_pslli_d:
5786 NewIntNo = Intrinsic::x86_mmx_psll_d;
5788 case Intrinsic::x86_mmx_pslli_q:
5789 NewIntNo = Intrinsic::x86_mmx_psll_q;
5791 case Intrinsic::x86_mmx_psrli_w:
5792 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5794 case Intrinsic::x86_mmx_psrli_d:
5795 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5797 case Intrinsic::x86_mmx_psrli_q:
5798 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5800 case Intrinsic::x86_mmx_psrai_w:
5801 NewIntNo = Intrinsic::x86_mmx_psra_w;
5803 case Intrinsic::x86_mmx_psrai_d:
5804 NewIntNo = Intrinsic::x86_mmx_psra_d;
5806 default: abort(); // Can't reach here.
5811 MVT VT = Op.getValueType();
5812 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5813 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5814 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5815 DAG.getConstant(NewIntNo, MVT::i32),
5816 Op.getOperand(1), ShAmt);
5821 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5822 // Depths > 0 not supported yet!
5823 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
5826 // Just load the return address
5827 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5828 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5831 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5832 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5833 MFI->setFrameAddressIsTaken(true);
5834 MVT VT = Op.getValueType();
5835 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5836 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
5837 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), FrameReg, VT);
5839 FrameAddr = DAG.getLoad(VT, DAG.getEntryNode(), FrameAddr, NULL, 0);
5843 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
5844 SelectionDAG &DAG) {
5845 return DAG.getIntPtrConstant(2*TD->getPointerSize());
5848 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
5850 MachineFunction &MF = DAG.getMachineFunction();
5851 SDValue Chain = Op.getOperand(0);
5852 SDValue Offset = Op.getOperand(1);
5853 SDValue Handler = Op.getOperand(2);
5855 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
5857 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
5859 SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5860 DAG.getIntPtrConstant(-TD->getPointerSize()));
5861 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5862 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5863 Chain = DAG.getCopyToReg(Chain, StoreAddrReg, StoreAddr);
5864 MF.getRegInfo().addLiveOut(StoreAddrReg);
5866 return DAG.getNode(X86ISD::EH_RETURN,
5868 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
5871 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
5872 SelectionDAG &DAG) {
5873 SDValue Root = Op.getOperand(0);
5874 SDValue Trmp = Op.getOperand(1); // trampoline
5875 SDValue FPtr = Op.getOperand(2); // nested function
5876 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
5878 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5880 const X86InstrInfo *TII =
5881 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5883 if (Subtarget->is64Bit()) {
5884 SDValue OutChains[6];
5886 // Large code-model.
5888 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5889 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5891 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5892 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5894 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5896 // Load the pointer to the nested function into R11.
5897 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5898 SDValue Addr = Trmp;
5899 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5902 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5903 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5905 // Load the 'nest' parameter value into R10.
5906 // R10 is specified in X86CallingConv.td
5907 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5908 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5909 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5912 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5913 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5915 // Jump to the nested function.
5916 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5917 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5918 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5921 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5922 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5923 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5927 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5928 return DAG.getMergeValues(Ops, 2);
5930 const Function *Func =
5931 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5932 unsigned CC = Func->getCallingConv();
5937 assert(0 && "Unsupported calling convention");
5938 case CallingConv::C:
5939 case CallingConv::X86_StdCall: {
5940 // Pass 'nest' parameter in ECX.
5941 // Must be kept in sync with X86CallingConv.td
5944 // Check that ECX wasn't needed by an 'inreg' parameter.
5945 const FunctionType *FTy = Func->getFunctionType();
5946 const AttrListPtr &Attrs = Func->getAttributes();
5948 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5949 unsigned InRegCount = 0;
5952 for (FunctionType::param_iterator I = FTy->param_begin(),
5953 E = FTy->param_end(); I != E; ++I, ++Idx)
5954 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
5955 // FIXME: should only count parameters that are lowered to integers.
5956 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
5958 if (InRegCount > 2) {
5959 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5965 case CallingConv::X86_FastCall:
5966 case CallingConv::Fast:
5967 // Pass 'nest' parameter in EAX.
5968 // Must be kept in sync with X86CallingConv.td
5973 SDValue OutChains[4];
5976 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5977 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5979 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5980 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
5981 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5984 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5985 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5987 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5988 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5989 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5990 TrmpAddr, 5, false, 1);
5992 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5993 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5996 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5997 return DAG.getMergeValues(Ops, 2);
6001 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6003 The rounding mode is in bits 11:10 of FPSR, and has the following
6010 FLT_ROUNDS, on the other hand, expects the following:
6017 To perform the conversion, we do:
6018 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6021 MachineFunction &MF = DAG.getMachineFunction();
6022 const TargetMachine &TM = MF.getTarget();
6023 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6024 unsigned StackAlignment = TFI.getStackAlignment();
6025 MVT VT = Op.getValueType();
6027 // Save FP Control Word to stack slot
6028 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6029 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6031 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
6032 DAG.getEntryNode(), StackSlot);
6034 // Load FP Control Word from stack slot
6035 SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
6037 // Transform as necessary
6039 DAG.getNode(ISD::SRL, MVT::i16,
6040 DAG.getNode(ISD::AND, MVT::i16,
6041 CWD, DAG.getConstant(0x800, MVT::i16)),
6042 DAG.getConstant(11, MVT::i8));
6044 DAG.getNode(ISD::SRL, MVT::i16,
6045 DAG.getNode(ISD::AND, MVT::i16,
6046 CWD, DAG.getConstant(0x400, MVT::i16)),
6047 DAG.getConstant(9, MVT::i8));
6050 DAG.getNode(ISD::AND, MVT::i16,
6051 DAG.getNode(ISD::ADD, MVT::i16,
6052 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
6053 DAG.getConstant(1, MVT::i16)),
6054 DAG.getConstant(3, MVT::i16));
6057 return DAG.getNode((VT.getSizeInBits() < 16 ?
6058 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
6061 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6062 MVT VT = Op.getValueType();
6064 unsigned NumBits = VT.getSizeInBits();
6066 Op = Op.getOperand(0);
6067 if (VT == MVT::i8) {
6068 // Zero extend to i32 since there is not an i8 bsr.
6070 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6073 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6074 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6075 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
6077 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6078 SmallVector<SDValue, 4> Ops;
6080 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6081 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6082 Ops.push_back(Op.getValue(1));
6083 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6085 // Finally xor with NumBits-1.
6086 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6089 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6093 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6094 MVT VT = Op.getValueType();
6096 unsigned NumBits = VT.getSizeInBits();
6098 Op = Op.getOperand(0);
6099 if (VT == MVT::i8) {
6101 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6104 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6105 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6106 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
6108 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6109 SmallVector<SDValue, 4> Ops;
6111 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6112 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6113 Ops.push_back(Op.getValue(1));
6114 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6117 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6121 SDValue X86TargetLowering::LowerXADDO(SDValue Op, SelectionDAG &DAG) {
6122 // Lower the "add with overflow" instruction into a regular "add" plus a
6123 // "setcc" instruction that checks the overflow flag. The "brcond" lowering
6124 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6125 // has only one use.
6126 SDNode *N = Op.getNode();
6127 SDValue LHS = N->getOperand(0);
6128 SDValue RHS = N->getOperand(1);
6130 // Also sets EFLAGS.
6131 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6132 SDValue Sum = DAG.getNode(ISD::ADD, VTs, LHS, RHS);
6135 DAG.getNode(X86ISD::SETCC, N->getValueType(1),
6136 DAG.getConstant((Op.getOpcode() == ISD::SADDO) ?
6137 X86::COND_O : X86::COND_C,
6138 MVT::i32), SDValue(Sum.getNode(), 1));
6140 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6144 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6145 MVT T = Op.getValueType();
6148 switch(T.getSimpleVT()) {
6150 assert(false && "Invalid value type!");
6151 case MVT::i8: Reg = X86::AL; size = 1; break;
6152 case MVT::i16: Reg = X86::AX; size = 2; break;
6153 case MVT::i32: Reg = X86::EAX; size = 4; break;
6155 assert(Subtarget->is64Bit() && "Node not type legal!");
6156 Reg = X86::RAX; size = 8;
6159 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
6160 Op.getOperand(2), SDValue());
6161 SDValue Ops[] = { cpIn.getValue(0),
6164 DAG.getTargetConstant(size, MVT::i8),
6166 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6167 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
6169 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
6173 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6174 SelectionDAG &DAG) {
6175 assert(Subtarget->is64Bit() && "Result not type legalized?");
6176 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6177 SDValue TheChain = Op.getOperand(0);
6178 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
6179 SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
6180 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX, MVT::i64,
6182 SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
6183 DAG.getConstant(32, MVT::i8));
6185 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp),
6188 return DAG.getMergeValues(Ops, 2);
6191 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6192 SDNode *Node = Op.getNode();
6193 MVT T = Node->getValueType(0);
6194 SDValue negOp = DAG.getNode(ISD::SUB, T,
6195 DAG.getConstant(0, T), Node->getOperand(2));
6196 return DAG.getAtomic((Op.getOpcode()==ISD::ATOMIC_LOAD_SUB_8 ?
6197 ISD::ATOMIC_LOAD_ADD_8 :
6198 Op.getOpcode()==ISD::ATOMIC_LOAD_SUB_16 ?
6199 ISD::ATOMIC_LOAD_ADD_16 :
6200 Op.getOpcode()==ISD::ATOMIC_LOAD_SUB_32 ?
6201 ISD::ATOMIC_LOAD_ADD_32 :
6202 ISD::ATOMIC_LOAD_ADD_64),
6203 Node->getOperand(0),
6204 Node->getOperand(1), negOp,
6205 cast<AtomicSDNode>(Node)->getSrcValue(),
6206 cast<AtomicSDNode>(Node)->getAlignment());
6209 /// LowerOperation - Provide custom lowering hooks for some operations.
6211 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6212 switch (Op.getOpcode()) {
6213 default: assert(0 && "Should not custom lower this!");
6214 case ISD::ATOMIC_CMP_SWAP_8:
6215 case ISD::ATOMIC_CMP_SWAP_16:
6216 case ISD::ATOMIC_CMP_SWAP_32:
6217 case ISD::ATOMIC_CMP_SWAP_64: return LowerCMP_SWAP(Op,DAG);
6218 case ISD::ATOMIC_LOAD_SUB_8:
6219 case ISD::ATOMIC_LOAD_SUB_16:
6220 case ISD::ATOMIC_LOAD_SUB_32: return LowerLOAD_SUB(Op,DAG);
6221 case ISD::ATOMIC_LOAD_SUB_64: return LowerLOAD_SUB(Op,DAG);
6222 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6223 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6224 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6225 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6226 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6227 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6228 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6229 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6230 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6231 case ISD::SHL_PARTS:
6232 case ISD::SRA_PARTS:
6233 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6234 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6235 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6236 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6237 case ISD::FABS: return LowerFABS(Op, DAG);
6238 case ISD::FNEG: return LowerFNEG(Op, DAG);
6239 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6240 case ISD::SETCC: return LowerSETCC(Op, DAG);
6241 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6242 case ISD::SELECT: return LowerSELECT(Op, DAG);
6243 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6244 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6245 case ISD::CALL: return LowerCALL(Op, DAG);
6246 case ISD::RET: return LowerRET(Op, DAG);
6247 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6248 case ISD::VASTART: return LowerVASTART(Op, DAG);
6249 case ISD::VAARG: return LowerVAARG(Op, DAG);
6250 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6251 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6252 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6253 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6254 case ISD::FRAME_TO_ARGS_OFFSET:
6255 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6256 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6257 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6258 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6259 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6260 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6261 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6262 case ISD::SADDO: return LowerXADDO(Op, DAG);
6263 case ISD::UADDO: return LowerXADDO(Op, DAG);
6264 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6268 void X86TargetLowering::
6269 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6270 SelectionDAG &DAG, unsigned NewOp) {
6271 MVT T = Node->getValueType(0);
6272 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6274 SDValue Chain = Node->getOperand(0);
6275 SDValue In1 = Node->getOperand(1);
6276 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6277 Node->getOperand(2), DAG.getIntPtrConstant(0));
6278 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6279 Node->getOperand(2), DAG.getIntPtrConstant(1));
6280 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6281 // have a MemOperand. Pass the info through as a normal operand.
6282 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6283 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6284 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6285 SDValue Result = DAG.getNode(NewOp, Tys, Ops, 5);
6286 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6287 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2));
6288 Results.push_back(Result.getValue(2));
6291 /// ReplaceNodeResults - Replace a node with an illegal result type
6292 /// with a new node built out of custom code.
6293 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6294 SmallVectorImpl<SDValue>&Results,
6295 SelectionDAG &DAG) {
6296 switch (N->getOpcode()) {
6298 assert(false && "Do not know how to custom type legalize this operation!");
6300 case ISD::FP_TO_SINT: {
6301 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
6302 SDValue FIST = Vals.first, StackSlot = Vals.second;
6303 if (FIST.getNode() != 0) {
6304 MVT VT = N->getValueType(0);
6305 // Return a load from the stack slot.
6306 Results.push_back(DAG.getLoad(VT, FIST, StackSlot, NULL, 0));
6310 case ISD::READCYCLECOUNTER: {
6311 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6312 SDValue TheChain = N->getOperand(0);
6313 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
6314 SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
6315 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX, MVT::i32,
6317 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6318 SDValue Ops[] = { eax, edx };
6319 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2));
6320 Results.push_back(edx.getValue(1));
6323 case ISD::ATOMIC_CMP_SWAP_64: {
6324 MVT T = N->getValueType(0);
6325 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6326 SDValue cpInL, cpInH;
6327 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(2),
6328 DAG.getConstant(0, MVT::i32));
6329 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(2),
6330 DAG.getConstant(1, MVT::i32));
6331 cpInL = DAG.getCopyToReg(N->getOperand(0), X86::EAX, cpInL, SDValue());
6332 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX, cpInH,
6334 SDValue swapInL, swapInH;
6335 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(3),
6336 DAG.getConstant(0, MVT::i32));
6337 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(3),
6338 DAG.getConstant(1, MVT::i32));
6339 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX, swapInL,
6341 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX, swapInH,
6342 swapInL.getValue(1));
6343 SDValue Ops[] = { swapInH.getValue(0),
6345 swapInH.getValue(1) };
6346 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6347 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
6348 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
6349 Result.getValue(1));
6350 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
6351 cpOutL.getValue(2));
6352 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6353 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2));
6354 Results.push_back(cpOutH.getValue(1));
6357 case ISD::ATOMIC_LOAD_ADD_64:
6358 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6360 case ISD::ATOMIC_LOAD_AND_64:
6361 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6363 case ISD::ATOMIC_LOAD_NAND_64:
6364 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6366 case ISD::ATOMIC_LOAD_OR_64:
6367 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6369 case ISD::ATOMIC_LOAD_SUB_64:
6370 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6372 case ISD::ATOMIC_LOAD_XOR_64:
6373 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6375 case ISD::ATOMIC_SWAP_64:
6376 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6381 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6383 default: return NULL;
6384 case X86ISD::BSF: return "X86ISD::BSF";
6385 case X86ISD::BSR: return "X86ISD::BSR";
6386 case X86ISD::SHLD: return "X86ISD::SHLD";
6387 case X86ISD::SHRD: return "X86ISD::SHRD";
6388 case X86ISD::FAND: return "X86ISD::FAND";
6389 case X86ISD::FOR: return "X86ISD::FOR";
6390 case X86ISD::FXOR: return "X86ISD::FXOR";
6391 case X86ISD::FSRL: return "X86ISD::FSRL";
6392 case X86ISD::FILD: return "X86ISD::FILD";
6393 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6394 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6395 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6396 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6397 case X86ISD::FLD: return "X86ISD::FLD";
6398 case X86ISD::FST: return "X86ISD::FST";
6399 case X86ISD::CALL: return "X86ISD::CALL";
6400 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6401 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6402 case X86ISD::CMP: return "X86ISD::CMP";
6403 case X86ISD::COMI: return "X86ISD::COMI";
6404 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6405 case X86ISD::SETCC: return "X86ISD::SETCC";
6406 case X86ISD::CMOV: return "X86ISD::CMOV";
6407 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6408 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6409 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6410 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6411 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6412 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6413 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6414 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6415 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6416 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6417 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6418 case X86ISD::FMAX: return "X86ISD::FMAX";
6419 case X86ISD::FMIN: return "X86ISD::FMIN";
6420 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6421 case X86ISD::FRCP: return "X86ISD::FRCP";
6422 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6423 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6424 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6425 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6426 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6427 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6428 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6429 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6430 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6431 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6432 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6433 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6434 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6435 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6436 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6437 case X86ISD::VSHL: return "X86ISD::VSHL";
6438 case X86ISD::VSRL: return "X86ISD::VSRL";
6439 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6440 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6441 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6442 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6443 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6444 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6445 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6446 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6447 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6448 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6452 // isLegalAddressingMode - Return true if the addressing mode represented
6453 // by AM is legal for this target, for a load/store of the specified type.
6454 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6455 const Type *Ty) const {
6456 // X86 supports extremely general addressing modes.
6458 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6459 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6463 // We can only fold this if we don't need an extra load.
6464 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6466 // If BaseGV requires a register, we cannot also have a BaseReg.
6467 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6471 // X86-64 only supports addr of globals in small code model.
6472 if (Subtarget->is64Bit()) {
6473 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6475 // If lower 4G is not available, then we must use rip-relative addressing.
6476 if (AM.BaseOffs || AM.Scale > 1)
6487 // These scales always work.
6492 // These scales are formed with basereg+scalereg. Only accept if there is
6497 default: // Other stuff never works.
6505 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6506 if (!Ty1->isInteger() || !Ty2->isInteger())
6508 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6509 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6510 if (NumBits1 <= NumBits2)
6512 return Subtarget->is64Bit() || NumBits1 < 64;
6515 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6516 if (!VT1.isInteger() || !VT2.isInteger())
6518 unsigned NumBits1 = VT1.getSizeInBits();
6519 unsigned NumBits2 = VT2.getSizeInBits();
6520 if (NumBits1 <= NumBits2)
6522 return Subtarget->is64Bit() || NumBits1 < 64;
6525 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6526 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6527 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6528 /// are assumed to be legal.
6530 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6531 // Only do shuffles on 128-bit vector types for now.
6532 if (VT.getSizeInBits() == 64) return false;
6533 return (Mask.getNode()->getNumOperands() <= 4 ||
6534 isIdentityMask(Mask.getNode()) ||
6535 isIdentityMask(Mask.getNode(), true) ||
6536 isSplatMask(Mask.getNode()) ||
6537 isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6538 X86::isUNPCKLMask(Mask.getNode()) ||
6539 X86::isUNPCKHMask(Mask.getNode()) ||
6540 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6541 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6545 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6546 MVT EVT, SelectionDAG &DAG) const {
6547 unsigned NumElts = BVOps.size();
6548 // Only do shuffles on 128-bit vector types for now.
6549 if (EVT.getSizeInBits() * NumElts == 64) return false;
6550 if (NumElts == 2) return true;
6552 return (isMOVLMask(&BVOps[0], 4) ||
6553 isCommutedMOVL(&BVOps[0], 4, true) ||
6554 isSHUFPMask(&BVOps[0], 4) ||
6555 isCommutedSHUFP(&BVOps[0], 4));
6560 //===----------------------------------------------------------------------===//
6561 // X86 Scheduler Hooks
6562 //===----------------------------------------------------------------------===//
6564 // private utility function
6566 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6567 MachineBasicBlock *MBB,
6575 TargetRegisterClass *RC,
6577 // For the atomic bitwise operator, we generate
6580 // ld t1 = [bitinstr.addr]
6581 // op t2 = t1, [bitinstr.val]
6583 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6585 // fallthrough -->nextMBB
6586 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6587 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6588 MachineFunction::iterator MBBIter = MBB;
6591 /// First build the CFG
6592 MachineFunction *F = MBB->getParent();
6593 MachineBasicBlock *thisMBB = MBB;
6594 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6595 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6596 F->insert(MBBIter, newMBB);
6597 F->insert(MBBIter, nextMBB);
6599 // Move all successors to thisMBB to nextMBB
6600 nextMBB->transferSuccessors(thisMBB);
6602 // Update thisMBB to fall through to newMBB
6603 thisMBB->addSuccessor(newMBB);
6605 // newMBB jumps to itself and fall through to nextMBB
6606 newMBB->addSuccessor(nextMBB);
6607 newMBB->addSuccessor(newMBB);
6609 // Insert instructions into newMBB based on incoming instruction
6610 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6611 MachineOperand& destOper = bInstr->getOperand(0);
6612 MachineOperand* argOpers[6];
6613 int numArgs = bInstr->getNumOperands() - 1;
6614 for (int i=0; i < numArgs; ++i)
6615 argOpers[i] = &bInstr->getOperand(i+1);
6617 // x86 address has 4 operands: base, index, scale, and displacement
6618 int lastAddrIndx = 3; // [0,3]
6621 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6622 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
6623 for (int i=0; i <= lastAddrIndx; ++i)
6624 (*MIB).addOperand(*argOpers[i]);
6626 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6628 MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
6633 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6634 assert((argOpers[valArgIndx]->isReg() ||
6635 argOpers[valArgIndx]->isImm()) &&
6637 if (argOpers[valArgIndx]->isReg())
6638 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6640 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6642 (*MIB).addOperand(*argOpers[valArgIndx]);
6644 MIB = BuildMI(newMBB, TII->get(copyOpc), EAXreg);
6647 MIB = BuildMI(newMBB, TII->get(CXchgOpc));
6648 for (int i=0; i <= lastAddrIndx; ++i)
6649 (*MIB).addOperand(*argOpers[i]);
6651 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6652 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6654 MIB = BuildMI(newMBB, TII->get(copyOpc), destOper.getReg());
6658 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6660 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
6664 // private utility function: 64 bit atomics on 32 bit host.
6666 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
6667 MachineBasicBlock *MBB,
6673 // For the atomic bitwise operator, we generate
6674 // thisMBB (instructions are in pairs, except cmpxchg8b)
6675 // ld t1,t2 = [bitinstr.addr]
6677 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
6678 // op t5, t6 <- out1, out2, [bitinstr.val]
6679 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
6680 // mov ECX, EBX <- t5, t6
6681 // mov EAX, EDX <- t1, t2
6682 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
6683 // mov t3, t4 <- EAX, EDX
6685 // result in out1, out2
6686 // fallthrough -->nextMBB
6688 const TargetRegisterClass *RC = X86::GR32RegisterClass;
6689 const unsigned LoadOpc = X86::MOV32rm;
6690 const unsigned copyOpc = X86::MOV32rr;
6691 const unsigned NotOpc = X86::NOT32r;
6692 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6693 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6694 MachineFunction::iterator MBBIter = MBB;
6697 /// First build the CFG
6698 MachineFunction *F = MBB->getParent();
6699 MachineBasicBlock *thisMBB = MBB;
6700 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6701 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6702 F->insert(MBBIter, newMBB);
6703 F->insert(MBBIter, nextMBB);
6705 // Move all successors to thisMBB to nextMBB
6706 nextMBB->transferSuccessors(thisMBB);
6708 // Update thisMBB to fall through to newMBB
6709 thisMBB->addSuccessor(newMBB);
6711 // newMBB jumps to itself and fall through to nextMBB
6712 newMBB->addSuccessor(nextMBB);
6713 newMBB->addSuccessor(newMBB);
6715 // Insert instructions into newMBB based on incoming instruction
6716 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
6717 assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
6718 MachineOperand& dest1Oper = bInstr->getOperand(0);
6719 MachineOperand& dest2Oper = bInstr->getOperand(1);
6720 MachineOperand* argOpers[6];
6721 for (int i=0; i < 6; ++i)
6722 argOpers[i] = &bInstr->getOperand(i+2);
6724 // x86 address has 4 operands: base, index, scale, and displacement
6725 int lastAddrIndx = 3; // [0,3]
6727 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6728 MachineInstrBuilder MIB = BuildMI(thisMBB, TII->get(LoadOpc), t1);
6729 for (int i=0; i <= lastAddrIndx; ++i)
6730 (*MIB).addOperand(*argOpers[i]);
6731 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6732 MIB = BuildMI(thisMBB, TII->get(LoadOpc), t2);
6733 // add 4 to displacement.
6734 for (int i=0; i <= lastAddrIndx-1; ++i)
6735 (*MIB).addOperand(*argOpers[i]);
6736 MachineOperand newOp3 = *(argOpers[3]);
6738 newOp3.setImm(newOp3.getImm()+4);
6740 newOp3.setOffset(newOp3.getOffset()+4);
6741 (*MIB).addOperand(newOp3);
6743 // t3/4 are defined later, at the bottom of the loop
6744 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
6745 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
6746 BuildMI(newMBB, TII->get(X86::PHI), dest1Oper.getReg())
6747 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
6748 BuildMI(newMBB, TII->get(X86::PHI), dest2Oper.getReg())
6749 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
6751 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
6752 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
6754 MIB = BuildMI(newMBB, TII->get(NotOpc), tt1).addReg(t1);
6755 MIB = BuildMI(newMBB, TII->get(NotOpc), tt2).addReg(t2);
6761 assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
6763 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
6764 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
6765 if (argOpers[4]->isReg())
6766 MIB = BuildMI(newMBB, TII->get(regOpcL), t5);
6768 MIB = BuildMI(newMBB, TII->get(immOpcL), t5);
6769 if (regOpcL != X86::MOV32rr)
6771 (*MIB).addOperand(*argOpers[4]);
6772 assert(argOpers[5]->isReg() == argOpers[4]->isReg());
6773 assert(argOpers[5]->isImm() == argOpers[4]->isImm());
6774 if (argOpers[5]->isReg())
6775 MIB = BuildMI(newMBB, TII->get(regOpcH), t6);
6777 MIB = BuildMI(newMBB, TII->get(immOpcH), t6);
6778 if (regOpcH != X86::MOV32rr)
6780 (*MIB).addOperand(*argOpers[5]);
6782 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EAX);
6784 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EDX);
6787 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EBX);
6789 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::ECX);
6792 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG8B));
6793 for (int i=0; i <= lastAddrIndx; ++i)
6794 (*MIB).addOperand(*argOpers[i]);
6796 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6797 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6799 MIB = BuildMI(newMBB, TII->get(copyOpc), t3);
6800 MIB.addReg(X86::EAX);
6801 MIB = BuildMI(newMBB, TII->get(copyOpc), t4);
6802 MIB.addReg(X86::EDX);
6805 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6807 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
6811 // private utility function
6813 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
6814 MachineBasicBlock *MBB,
6816 // For the atomic min/max operator, we generate
6819 // ld t1 = [min/max.addr]
6820 // mov t2 = [min/max.val]
6822 // cmov[cond] t2 = t1
6824 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6826 // fallthrough -->nextMBB
6828 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6829 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6830 MachineFunction::iterator MBBIter = MBB;
6833 /// First build the CFG
6834 MachineFunction *F = MBB->getParent();
6835 MachineBasicBlock *thisMBB = MBB;
6836 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6837 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6838 F->insert(MBBIter, newMBB);
6839 F->insert(MBBIter, nextMBB);
6841 // Move all successors to thisMBB to nextMBB
6842 nextMBB->transferSuccessors(thisMBB);
6844 // Update thisMBB to fall through to newMBB
6845 thisMBB->addSuccessor(newMBB);
6847 // newMBB jumps to newMBB and fall through to nextMBB
6848 newMBB->addSuccessor(nextMBB);
6849 newMBB->addSuccessor(newMBB);
6851 // Insert instructions into newMBB based on incoming instruction
6852 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
6853 MachineOperand& destOper = mInstr->getOperand(0);
6854 MachineOperand* argOpers[6];
6855 int numArgs = mInstr->getNumOperands() - 1;
6856 for (int i=0; i < numArgs; ++i)
6857 argOpers[i] = &mInstr->getOperand(i+1);
6859 // x86 address has 4 operands: base, index, scale, and displacement
6860 int lastAddrIndx = 3; // [0,3]
6863 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6864 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6865 for (int i=0; i <= lastAddrIndx; ++i)
6866 (*MIB).addOperand(*argOpers[i]);
6868 // We only support register and immediate values
6869 assert((argOpers[valArgIndx]->isReg() ||
6870 argOpers[valArgIndx]->isImm()) &&
6873 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6874 if (argOpers[valArgIndx]->isReg())
6875 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6877 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6878 (*MIB).addOperand(*argOpers[valArgIndx]);
6880 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6883 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
6888 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6889 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
6893 // Cmp and exchange if none has modified the memory location
6894 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6895 for (int i=0; i <= lastAddrIndx; ++i)
6896 (*MIB).addOperand(*argOpers[i]);
6898 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6899 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
6901 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6902 MIB.addReg(X86::EAX);
6905 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6907 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
6913 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6914 MachineBasicBlock *BB) {
6915 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6916 switch (MI->getOpcode()) {
6917 default: assert(false && "Unexpected instr type to insert");
6918 case X86::CMOV_FR32:
6919 case X86::CMOV_FR64:
6920 case X86::CMOV_V4F32:
6921 case X86::CMOV_V2F64:
6922 case X86::CMOV_V2I64: {
6923 // To "insert" a SELECT_CC instruction, we actually have to insert the
6924 // diamond control-flow pattern. The incoming instruction knows the
6925 // destination vreg to set, the condition code register to branch on, the
6926 // true/false values to select between, and a branch opcode to use.
6927 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6928 MachineFunction::iterator It = BB;
6934 // cmpTY ccX, r1, r2
6936 // fallthrough --> copy0MBB
6937 MachineBasicBlock *thisMBB = BB;
6938 MachineFunction *F = BB->getParent();
6939 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6940 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6942 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6943 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6944 F->insert(It, copy0MBB);
6945 F->insert(It, sinkMBB);
6946 // Update machine-CFG edges by transferring all successors of the current
6947 // block to the new block which will contain the Phi node for the select.
6948 sinkMBB->transferSuccessors(BB);
6950 // Add the true and fallthrough blocks as its successors.
6951 BB->addSuccessor(copy0MBB);
6952 BB->addSuccessor(sinkMBB);
6955 // %FalseValue = ...
6956 // # fallthrough to sinkMBB
6959 // Update machine-CFG edges
6960 BB->addSuccessor(sinkMBB);
6963 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6966 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6967 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6968 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6970 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
6974 case X86::FP32_TO_INT16_IN_MEM:
6975 case X86::FP32_TO_INT32_IN_MEM:
6976 case X86::FP32_TO_INT64_IN_MEM:
6977 case X86::FP64_TO_INT16_IN_MEM:
6978 case X86::FP64_TO_INT32_IN_MEM:
6979 case X86::FP64_TO_INT64_IN_MEM:
6980 case X86::FP80_TO_INT16_IN_MEM:
6981 case X86::FP80_TO_INT32_IN_MEM:
6982 case X86::FP80_TO_INT64_IN_MEM: {
6983 // Change the floating point control register to use "round towards zero"
6984 // mode when truncating to an integer value.
6985 MachineFunction *F = BB->getParent();
6986 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6987 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6989 // Load the old value of the high byte of the control word...
6991 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6992 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6994 // Set the high part to be round to zero...
6995 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6998 // Reload the modified control word now...
6999 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
7001 // Restore the memory image of control word to original value
7002 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
7005 // Get the X86 opcode to use.
7007 switch (MI->getOpcode()) {
7008 default: assert(0 && "illegal opcode!");
7009 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7010 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7011 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7012 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7013 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7014 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7015 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7016 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7017 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7021 MachineOperand &Op = MI->getOperand(0);
7023 AM.BaseType = X86AddressMode::RegBase;
7024 AM.Base.Reg = Op.getReg();
7026 AM.BaseType = X86AddressMode::FrameIndexBase;
7027 AM.Base.FrameIndex = Op.getIndex();
7029 Op = MI->getOperand(1);
7031 AM.Scale = Op.getImm();
7032 Op = MI->getOperand(2);
7034 AM.IndexReg = Op.getImm();
7035 Op = MI->getOperand(3);
7036 if (Op.isGlobal()) {
7037 AM.GV = Op.getGlobal();
7039 AM.Disp = Op.getImm();
7041 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
7042 .addReg(MI->getOperand(4).getReg());
7044 // Reload the original control word now.
7045 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
7047 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7050 case X86::ATOMAND32:
7051 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7052 X86::AND32ri, X86::MOV32rm,
7053 X86::LCMPXCHG32, X86::MOV32rr,
7054 X86::NOT32r, X86::EAX,
7055 X86::GR32RegisterClass);
7057 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7058 X86::OR32ri, X86::MOV32rm,
7059 X86::LCMPXCHG32, X86::MOV32rr,
7060 X86::NOT32r, X86::EAX,
7061 X86::GR32RegisterClass);
7062 case X86::ATOMXOR32:
7063 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7064 X86::XOR32ri, X86::MOV32rm,
7065 X86::LCMPXCHG32, X86::MOV32rr,
7066 X86::NOT32r, X86::EAX,
7067 X86::GR32RegisterClass);
7068 case X86::ATOMNAND32:
7069 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7070 X86::AND32ri, X86::MOV32rm,
7071 X86::LCMPXCHG32, X86::MOV32rr,
7072 X86::NOT32r, X86::EAX,
7073 X86::GR32RegisterClass, true);
7074 case X86::ATOMMIN32:
7075 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7076 case X86::ATOMMAX32:
7077 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7078 case X86::ATOMUMIN32:
7079 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7080 case X86::ATOMUMAX32:
7081 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7083 case X86::ATOMAND16:
7084 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7085 X86::AND16ri, X86::MOV16rm,
7086 X86::LCMPXCHG16, X86::MOV16rr,
7087 X86::NOT16r, X86::AX,
7088 X86::GR16RegisterClass);
7090 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7091 X86::OR16ri, X86::MOV16rm,
7092 X86::LCMPXCHG16, X86::MOV16rr,
7093 X86::NOT16r, X86::AX,
7094 X86::GR16RegisterClass);
7095 case X86::ATOMXOR16:
7096 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7097 X86::XOR16ri, X86::MOV16rm,
7098 X86::LCMPXCHG16, X86::MOV16rr,
7099 X86::NOT16r, X86::AX,
7100 X86::GR16RegisterClass);
7101 case X86::ATOMNAND16:
7102 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7103 X86::AND16ri, X86::MOV16rm,
7104 X86::LCMPXCHG16, X86::MOV16rr,
7105 X86::NOT16r, X86::AX,
7106 X86::GR16RegisterClass, true);
7107 case X86::ATOMMIN16:
7108 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7109 case X86::ATOMMAX16:
7110 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7111 case X86::ATOMUMIN16:
7112 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7113 case X86::ATOMUMAX16:
7114 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7117 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7118 X86::AND8ri, X86::MOV8rm,
7119 X86::LCMPXCHG8, X86::MOV8rr,
7120 X86::NOT8r, X86::AL,
7121 X86::GR8RegisterClass);
7123 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7124 X86::OR8ri, X86::MOV8rm,
7125 X86::LCMPXCHG8, X86::MOV8rr,
7126 X86::NOT8r, X86::AL,
7127 X86::GR8RegisterClass);
7129 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7130 X86::XOR8ri, X86::MOV8rm,
7131 X86::LCMPXCHG8, X86::MOV8rr,
7132 X86::NOT8r, X86::AL,
7133 X86::GR8RegisterClass);
7134 case X86::ATOMNAND8:
7135 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7136 X86::AND8ri, X86::MOV8rm,
7137 X86::LCMPXCHG8, X86::MOV8rr,
7138 X86::NOT8r, X86::AL,
7139 X86::GR8RegisterClass, true);
7140 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7141 // This group is for 64-bit host.
7142 case X86::ATOMAND64:
7143 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7144 X86::AND64ri32, X86::MOV64rm,
7145 X86::LCMPXCHG64, X86::MOV64rr,
7146 X86::NOT64r, X86::RAX,
7147 X86::GR64RegisterClass);
7149 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7150 X86::OR64ri32, X86::MOV64rm,
7151 X86::LCMPXCHG64, X86::MOV64rr,
7152 X86::NOT64r, X86::RAX,
7153 X86::GR64RegisterClass);
7154 case X86::ATOMXOR64:
7155 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7156 X86::XOR64ri32, X86::MOV64rm,
7157 X86::LCMPXCHG64, X86::MOV64rr,
7158 X86::NOT64r, X86::RAX,
7159 X86::GR64RegisterClass);
7160 case X86::ATOMNAND64:
7161 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7162 X86::AND64ri32, X86::MOV64rm,
7163 X86::LCMPXCHG64, X86::MOV64rr,
7164 X86::NOT64r, X86::RAX,
7165 X86::GR64RegisterClass, true);
7166 case X86::ATOMMIN64:
7167 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7168 case X86::ATOMMAX64:
7169 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7170 case X86::ATOMUMIN64:
7171 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7172 case X86::ATOMUMAX64:
7173 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7175 // This group does 64-bit operations on a 32-bit host.
7176 case X86::ATOMAND6432:
7177 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7178 X86::AND32rr, X86::AND32rr,
7179 X86::AND32ri, X86::AND32ri,
7181 case X86::ATOMOR6432:
7182 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7183 X86::OR32rr, X86::OR32rr,
7184 X86::OR32ri, X86::OR32ri,
7186 case X86::ATOMXOR6432:
7187 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7188 X86::XOR32rr, X86::XOR32rr,
7189 X86::XOR32ri, X86::XOR32ri,
7191 case X86::ATOMNAND6432:
7192 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7193 X86::AND32rr, X86::AND32rr,
7194 X86::AND32ri, X86::AND32ri,
7196 case X86::ATOMADD6432:
7197 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7198 X86::ADD32rr, X86::ADC32rr,
7199 X86::ADD32ri, X86::ADC32ri,
7201 case X86::ATOMSUB6432:
7202 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7203 X86::SUB32rr, X86::SBB32rr,
7204 X86::SUB32ri, X86::SBB32ri,
7206 case X86::ATOMSWAP6432:
7207 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7208 X86::MOV32rr, X86::MOV32rr,
7209 X86::MOV32ri, X86::MOV32ri,
7214 //===----------------------------------------------------------------------===//
7215 // X86 Optimization Hooks
7216 //===----------------------------------------------------------------------===//
7218 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7222 const SelectionDAG &DAG,
7223 unsigned Depth) const {
7224 unsigned Opc = Op.getOpcode();
7225 assert((Opc >= ISD::BUILTIN_OP_END ||
7226 Opc == ISD::INTRINSIC_WO_CHAIN ||
7227 Opc == ISD::INTRINSIC_W_CHAIN ||
7228 Opc == ISD::INTRINSIC_VOID) &&
7229 "Should use MaskedValueIsZero if you don't know whether Op"
7230 " is a target node!");
7232 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7236 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7237 Mask.getBitWidth() - 1);
7242 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7243 /// node is a GlobalAddress + offset.
7244 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7245 GlobalValue* &GA, int64_t &Offset) const{
7246 if (N->getOpcode() == X86ISD::Wrapper) {
7247 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7248 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7249 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7253 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7256 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7257 const TargetLowering &TLI) {
7260 if (TLI.isGAPlusOffset(Base, GV, Offset))
7261 return (GV->getAlignment() >= N && (Offset % N) == 0);
7262 // DAG combine handles the stack object case.
7266 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
7267 unsigned NumElems, MVT EVT,
7269 SelectionDAG &DAG, MachineFrameInfo *MFI,
7270 const TargetLowering &TLI) {
7272 for (unsigned i = 0; i < NumElems; ++i) {
7273 SDValue Idx = PermMask.getOperand(i);
7274 if (Idx.getOpcode() == ISD::UNDEF) {
7280 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7281 if (!Elt.getNode() ||
7282 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7285 Base = Elt.getNode();
7286 if (Base->getOpcode() == ISD::UNDEF)
7290 if (Elt.getOpcode() == ISD::UNDEF)
7293 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7294 EVT.getSizeInBits()/8, i, MFI))
7300 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7301 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7302 /// if the load addresses are consecutive, non-overlapping, and in the right
7304 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7305 const TargetLowering &TLI) {
7306 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7307 MVT VT = N->getValueType(0);
7308 MVT EVT = VT.getVectorElementType();
7309 SDValue PermMask = N->getOperand(2);
7310 unsigned NumElems = PermMask.getNumOperands();
7311 SDNode *Base = NULL;
7312 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
7316 LoadSDNode *LD = cast<LoadSDNode>(Base);
7317 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7318 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7319 LD->getSrcValueOffset(), LD->isVolatile());
7320 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7321 LD->getSrcValueOffset(), LD->isVolatile(),
7322 LD->getAlignment());
7325 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7326 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7327 const X86Subtarget *Subtarget,
7328 const TargetLowering &TLI) {
7329 unsigned NumOps = N->getNumOperands();
7331 // Ignore single operand BUILD_VECTOR.
7335 MVT VT = N->getValueType(0);
7336 MVT EVT = VT.getVectorElementType();
7337 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7338 // We are looking for load i64 and zero extend. We want to transform
7339 // it before legalizer has a chance to expand it. Also look for i64
7340 // BUILD_PAIR bit casted to f64.
7342 // This must be an insertion into a zero vector.
7343 SDValue HighElt = N->getOperand(1);
7344 if (!isZeroNode(HighElt))
7347 // Value must be a load.
7348 SDNode *Base = N->getOperand(0).getNode();
7349 if (!isa<LoadSDNode>(Base)) {
7350 if (Base->getOpcode() != ISD::BIT_CONVERT)
7352 Base = Base->getOperand(0).getNode();
7353 if (!isa<LoadSDNode>(Base))
7357 // Transform it into VZEXT_LOAD addr.
7358 LoadSDNode *LD = cast<LoadSDNode>(Base);
7360 // Load must not be an extload.
7361 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7364 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7365 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7366 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, Tys, Ops, 2);
7367 DAG.ReplaceAllUsesOfValueWith(SDValue(Base, 1), ResNode.getValue(1));
7371 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7372 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7373 const X86Subtarget *Subtarget) {
7374 SDValue Cond = N->getOperand(0);
7376 // If we have SSE[12] support, try to form min/max nodes.
7377 if (Subtarget->hasSSE2() &&
7378 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
7379 if (Cond.getOpcode() == ISD::SETCC) {
7380 // Get the LHS/RHS of the select.
7381 SDValue LHS = N->getOperand(1);
7382 SDValue RHS = N->getOperand(2);
7383 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7385 unsigned Opcode = 0;
7386 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7389 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7392 if (!UnsafeFPMath) break;
7394 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7396 Opcode = X86ISD::FMIN;
7399 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7402 if (!UnsafeFPMath) break;
7404 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7406 Opcode = X86ISD::FMAX;
7409 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7412 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7415 if (!UnsafeFPMath) break;
7417 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7419 Opcode = X86ISD::FMIN;
7422 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7425 if (!UnsafeFPMath) break;
7427 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7429 Opcode = X86ISD::FMAX;
7435 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
7443 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
7444 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
7445 const X86Subtarget *Subtarget) {
7446 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
7447 // the FP state in cases where an emms may be missing.
7448 // A preferable solution to the general problem is to figure out the right
7449 // places to insert EMMS. This qualifies as a quick hack.
7450 StoreSDNode *St = cast<StoreSDNode>(N);
7451 if (St->getValue().getValueType().isVector() &&
7452 St->getValue().getValueType().getSizeInBits() == 64 &&
7453 isa<LoadSDNode>(St->getValue()) &&
7454 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
7455 St->getChain().hasOneUse() && !St->isVolatile()) {
7456 SDNode* LdVal = St->getValue().getNode();
7458 int TokenFactorIndex = -1;
7459 SmallVector<SDValue, 8> Ops;
7460 SDNode* ChainVal = St->getChain().getNode();
7461 // Must be a store of a load. We currently handle two cases: the load
7462 // is a direct child, and it's under an intervening TokenFactor. It is
7463 // possible to dig deeper under nested TokenFactors.
7464 if (ChainVal == LdVal)
7465 Ld = cast<LoadSDNode>(St->getChain());
7466 else if (St->getValue().hasOneUse() &&
7467 ChainVal->getOpcode() == ISD::TokenFactor) {
7468 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
7469 if (ChainVal->getOperand(i).getNode() == LdVal) {
7470 TokenFactorIndex = i;
7471 Ld = cast<LoadSDNode>(St->getValue());
7473 Ops.push_back(ChainVal->getOperand(i));
7477 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
7478 if (Subtarget->is64Bit()) {
7479 SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
7480 Ld->getBasePtr(), Ld->getSrcValue(),
7481 Ld->getSrcValueOffset(), Ld->isVolatile(),
7482 Ld->getAlignment());
7483 SDValue NewChain = NewLd.getValue(1);
7484 if (TokenFactorIndex != -1) {
7485 Ops.push_back(NewChain);
7486 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7489 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
7490 St->getSrcValue(), St->getSrcValueOffset(),
7491 St->isVolatile(), St->getAlignment());
7494 // Otherwise, lower to two 32-bit copies.
7495 SDValue LoAddr = Ld->getBasePtr();
7496 SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7497 DAG.getConstant(4, MVT::i32));
7499 SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
7500 Ld->getSrcValue(), Ld->getSrcValueOffset(),
7501 Ld->isVolatile(), Ld->getAlignment());
7502 SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
7503 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
7505 MinAlign(Ld->getAlignment(), 4));
7507 SDValue NewChain = LoLd.getValue(1);
7508 if (TokenFactorIndex != -1) {
7509 Ops.push_back(LoLd);
7510 Ops.push_back(HiLd);
7511 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7515 LoAddr = St->getBasePtr();
7516 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7517 DAG.getConstant(4, MVT::i32));
7519 SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
7520 St->getSrcValue(), St->getSrcValueOffset(),
7521 St->isVolatile(), St->getAlignment());
7522 SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
7524 St->getSrcValueOffset() + 4,
7526 MinAlign(St->getAlignment(), 4));
7527 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
7533 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
7534 /// X86ISD::FXOR nodes.
7535 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
7536 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
7537 // F[X]OR(0.0, x) -> x
7538 // F[X]OR(x, 0.0) -> x
7539 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7540 if (C->getValueAPF().isPosZero())
7541 return N->getOperand(1);
7542 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7543 if (C->getValueAPF().isPosZero())
7544 return N->getOperand(0);
7548 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
7549 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
7550 // FAND(0.0, x) -> 0.0
7551 // FAND(x, 0.0) -> 0.0
7552 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7553 if (C->getValueAPF().isPosZero())
7554 return N->getOperand(0);
7555 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7556 if (C->getValueAPF().isPosZero())
7557 return N->getOperand(1);
7562 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
7563 DAGCombinerInfo &DCI) const {
7564 SelectionDAG &DAG = DCI.DAG;
7565 switch (N->getOpcode()) {
7567 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
7568 case ISD::BUILD_VECTOR:
7569 return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
7570 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
7571 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
7573 case X86ISD::FOR: return PerformFORCombine(N, DAG);
7574 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
7580 //===----------------------------------------------------------------------===//
7581 // X86 Inline Assembly Support
7582 //===----------------------------------------------------------------------===//
7584 /// getConstraintType - Given a constraint letter, return the type of
7585 /// constraint it is for this target.
7586 X86TargetLowering::ConstraintType
7587 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
7588 if (Constraint.size() == 1) {
7589 switch (Constraint[0]) {
7601 return C_RegisterClass;
7606 return TargetLowering::getConstraintType(Constraint);
7609 /// LowerXConstraint - try to replace an X constraint, which matches anything,
7610 /// with another that has more specific requirements based on the type of the
7611 /// corresponding operand.
7612 const char *X86TargetLowering::
7613 LowerXConstraint(MVT ConstraintVT) const {
7614 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
7615 // 'f' like normal targets.
7616 if (ConstraintVT.isFloatingPoint()) {
7617 if (Subtarget->hasSSE2())
7619 if (Subtarget->hasSSE1())
7623 return TargetLowering::LowerXConstraint(ConstraintVT);
7626 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7627 /// vector. If it is invalid, don't add anything to Ops.
7628 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7631 std::vector<SDValue>&Ops,
7632 SelectionDAG &DAG) const {
7633 SDValue Result(0, 0);
7635 switch (Constraint) {
7638 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7639 if (C->getZExtValue() <= 31) {
7640 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7646 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7647 if (C->getZExtValue() <= 63) {
7648 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7654 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7655 if (C->getZExtValue() <= 255) {
7656 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7662 // Literal immediates are always ok.
7663 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
7664 Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
7668 // If we are in non-pic codegen mode, we allow the address of a global (with
7669 // an optional displacement) to be used with 'i'.
7670 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
7673 // Match either (GA) or (GA+C)
7675 Offset = GA->getOffset();
7676 } else if (Op.getOpcode() == ISD::ADD) {
7677 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7678 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7680 Offset = GA->getOffset()+C->getZExtValue();
7682 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7683 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7685 Offset = GA->getOffset()+C->getZExtValue();
7693 Op = LowerGlobalAddress(GA->getGlobal(), Offset, DAG);
7695 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
7701 // Otherwise, not valid for this mode.
7706 if (Result.getNode()) {
7707 Ops.push_back(Result);
7710 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
7714 std::vector<unsigned> X86TargetLowering::
7715 getRegClassForInlineAsmConstraint(const std::string &Constraint,
7717 if (Constraint.size() == 1) {
7718 // FIXME: not handling fp-stack yet!
7719 switch (Constraint[0]) { // GCC X86 Constraint Letters
7720 default: break; // Unknown constraint letter
7721 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
7724 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
7725 else if (VT == MVT::i16)
7726 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
7727 else if (VT == MVT::i8)
7728 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
7729 else if (VT == MVT::i64)
7730 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
7735 return std::vector<unsigned>();
7738 std::pair<unsigned, const TargetRegisterClass*>
7739 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7741 // First, see if this is a constraint that directly corresponds to an LLVM
7743 if (Constraint.size() == 1) {
7744 // GCC Constraint Letters
7745 switch (Constraint[0]) {
7747 case 'r': // GENERAL_REGS
7748 case 'R': // LEGACY_REGS
7749 case 'l': // INDEX_REGS
7751 return std::make_pair(0U, X86::GR8RegisterClass);
7753 return std::make_pair(0U, X86::GR16RegisterClass);
7754 if (VT == MVT::i32 || !Subtarget->is64Bit())
7755 return std::make_pair(0U, X86::GR32RegisterClass);
7756 return std::make_pair(0U, X86::GR64RegisterClass);
7757 case 'f': // FP Stack registers.
7758 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
7759 // value to the correct fpstack register class.
7760 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
7761 return std::make_pair(0U, X86::RFP32RegisterClass);
7762 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
7763 return std::make_pair(0U, X86::RFP64RegisterClass);
7764 return std::make_pair(0U, X86::RFP80RegisterClass);
7765 case 'y': // MMX_REGS if MMX allowed.
7766 if (!Subtarget->hasMMX()) break;
7767 return std::make_pair(0U, X86::VR64RegisterClass);
7768 case 'Y': // SSE_REGS if SSE2 allowed
7769 if (!Subtarget->hasSSE2()) break;
7771 case 'x': // SSE_REGS if SSE1 allowed
7772 if (!Subtarget->hasSSE1()) break;
7774 switch (VT.getSimpleVT()) {
7776 // Scalar SSE types.
7779 return std::make_pair(0U, X86::FR32RegisterClass);
7782 return std::make_pair(0U, X86::FR64RegisterClass);
7790 return std::make_pair(0U, X86::VR128RegisterClass);
7796 // Use the default implementation in TargetLowering to convert the register
7797 // constraint into a member of a register class.
7798 std::pair<unsigned, const TargetRegisterClass*> Res;
7799 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7801 // Not found as a standard register?
7802 if (Res.second == 0) {
7803 // GCC calls "st(0)" just plain "st".
7804 if (StringsEqualNoCase("{st}", Constraint)) {
7805 Res.first = X86::ST0;
7806 Res.second = X86::RFP80RegisterClass;
7808 // 'A' means EAX + EDX.
7809 if (Constraint == "A") {
7810 Res.first = X86::EAX;
7811 Res.second = X86::GRADRegisterClass;
7816 // Otherwise, check to see if this is a register class of the wrong value
7817 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
7818 // turn into {ax},{dx}.
7819 if (Res.second->hasType(VT))
7820 return Res; // Correct type already, nothing to do.
7822 // All of the single-register GCC register classes map their values onto
7823 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
7824 // really want an 8-bit or 32-bit register, map to the appropriate register
7825 // class and return the appropriate register.
7826 if (Res.second == X86::GR16RegisterClass) {
7827 if (VT == MVT::i8) {
7828 unsigned DestReg = 0;
7829 switch (Res.first) {
7831 case X86::AX: DestReg = X86::AL; break;
7832 case X86::DX: DestReg = X86::DL; break;
7833 case X86::CX: DestReg = X86::CL; break;
7834 case X86::BX: DestReg = X86::BL; break;
7837 Res.first = DestReg;
7838 Res.second = Res.second = X86::GR8RegisterClass;
7840 } else if (VT == MVT::i32) {
7841 unsigned DestReg = 0;
7842 switch (Res.first) {
7844 case X86::AX: DestReg = X86::EAX; break;
7845 case X86::DX: DestReg = X86::EDX; break;
7846 case X86::CX: DestReg = X86::ECX; break;
7847 case X86::BX: DestReg = X86::EBX; break;
7848 case X86::SI: DestReg = X86::ESI; break;
7849 case X86::DI: DestReg = X86::EDI; break;
7850 case X86::BP: DestReg = X86::EBP; break;
7851 case X86::SP: DestReg = X86::ESP; break;
7854 Res.first = DestReg;
7855 Res.second = Res.second = X86::GR32RegisterClass;
7857 } else if (VT == MVT::i64) {
7858 unsigned DestReg = 0;
7859 switch (Res.first) {
7861 case X86::AX: DestReg = X86::RAX; break;
7862 case X86::DX: DestReg = X86::RDX; break;
7863 case X86::CX: DestReg = X86::RCX; break;
7864 case X86::BX: DestReg = X86::RBX; break;
7865 case X86::SI: DestReg = X86::RSI; break;
7866 case X86::DI: DestReg = X86::RDI; break;
7867 case X86::BP: DestReg = X86::RBP; break;
7868 case X86::SP: DestReg = X86::RSP; break;
7871 Res.first = DestReg;
7872 Res.second = Res.second = X86::GR64RegisterClass;
7875 } else if (Res.second == X86::FR32RegisterClass ||
7876 Res.second == X86::FR64RegisterClass ||
7877 Res.second == X86::VR128RegisterClass) {
7878 // Handle references to XMM physical registers that got mapped into the
7879 // wrong class. This can happen with constraints like {xmm0} where the
7880 // target independent register mapper will just pick the first match it can
7881 // find, ignoring the required type.
7883 Res.second = X86::FR32RegisterClass;
7884 else if (VT == MVT::f64)
7885 Res.second = X86::FR64RegisterClass;
7886 else if (X86::VR128RegisterClass->hasType(VT))
7887 Res.second = X86::VR128RegisterClass;
7893 //===----------------------------------------------------------------------===//
7894 // X86 Widen vector type
7895 //===----------------------------------------------------------------------===//
7897 /// getWidenVectorType: given a vector type, returns the type to widen
7898 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
7899 /// If there is no vector type that we want to widen to, returns MVT::Other
7900 /// When and where to widen is target dependent based on the cost of
7901 /// scalarizing vs using the wider vector type.
7903 MVT X86TargetLowering::getWidenVectorType(MVT VT) {
7904 assert(VT.isVector());
7905 if (isTypeLegal(VT))
7908 // TODO: In computeRegisterProperty, we can compute the list of legal vector
7909 // type based on element type. This would speed up our search (though
7910 // it may not be worth it since the size of the list is relatively
7912 MVT EltVT = VT.getVectorElementType();
7913 unsigned NElts = VT.getVectorNumElements();
7915 // On X86, it make sense to widen any vector wider than 1
7919 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
7920 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
7921 MVT SVT = (MVT::SimpleValueType)nVT;
7923 if (isTypeLegal(SVT) &&
7924 SVT.getVectorElementType() == EltVT &&
7925 SVT.getVectorNumElements() > NElts)