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, DebugLoc dl);
50 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
51 : TargetLowering(TM) {
52 Subtarget = &TM.getSubtarget<X86Subtarget>();
53 X86ScalarSSEf64 = Subtarget->hasSSE2();
54 X86ScalarSSEf32 = Subtarget->hasSSE1();
55 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
59 RegInfo = TM.getRegisterInfo();
62 // Set up the TargetLowering object.
64 // X86 is weird, it always uses i8 for shift amounts and setcc results.
65 setShiftAmountType(MVT::i8);
66 setBooleanContents(ZeroOrOneBooleanContent);
67 setSchedulingPreference(SchedulingForRegPressure);
68 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
69 setStackPointerRegisterToSaveRestore(X86StackPtr);
71 if (Subtarget->isTargetDarwin()) {
72 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
73 setUseUnderscoreSetJmp(false);
74 setUseUnderscoreLongJmp(false);
75 } else if (Subtarget->isTargetMingw()) {
76 // MS runtime is weird: it exports _setjmp, but longjmp!
77 setUseUnderscoreSetJmp(true);
78 setUseUnderscoreLongJmp(false);
80 setUseUnderscoreSetJmp(true);
81 setUseUnderscoreLongJmp(true);
84 // Set up the register classes.
85 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
86 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
87 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
88 if (Subtarget->is64Bit())
89 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
91 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93 // We don't accept any truncstore of integer registers.
94 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
95 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
96 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
97 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
98 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
99 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
101 // SETOEQ and SETUNE require checking two conditions.
102 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
103 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
104 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
105 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
106 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
107 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
109 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
111 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
112 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
115 if (Subtarget->is64Bit()) {
116 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
117 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
119 if (X86ScalarSSEf64) {
120 // We have an impenetrably clever algorithm for ui64->double only.
121 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
123 // We have faster algorithm for ui32->single only.
124 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
126 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
129 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
131 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
132 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
133 // SSE has no i16 to fp conversion, only i32
134 if (X86ScalarSSEf32) {
135 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
136 // f32 and f64 cases are Legal, f80 case is not
137 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
139 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
140 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
143 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
144 // are Legal, f80 is custom lowered.
145 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
146 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
148 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
150 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
151 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
153 if (X86ScalarSSEf32) {
154 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
155 // f32 and f64 cases are Legal, f80 case is not
156 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
158 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
159 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
162 // Handle FP_TO_UINT by promoting the destination to a larger signed
164 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
165 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
166 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
168 if (Subtarget->is64Bit()) {
169 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
170 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
172 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
173 // Expand FP_TO_UINT into a select.
174 // FIXME: We would like to use a Custom expander here eventually to do
175 // the optimal thing for SSE vs. the default expansion in the legalizer.
176 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
178 // With SSE3 we can use fisttpll to convert to a signed i64.
179 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
182 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
183 if (!X86ScalarSSEf64) {
184 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
185 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
188 // Scalar integer divide and remainder are lowered to use operations that
189 // produce two results, to match the available instructions. This exposes
190 // the two-result form to trivial CSE, which is able to combine x/y and x%y
191 // into a single instruction.
193 // Scalar integer multiply-high is also lowered to use two-result
194 // operations, to match the available instructions. However, plain multiply
195 // (low) operations are left as Legal, as there are single-result
196 // instructions for this in x86. Using the two-result multiply instructions
197 // when both high and low results are needed must be arranged by dagcombine.
198 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
199 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
200 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
201 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
202 setOperationAction(ISD::SREM , MVT::i8 , Expand);
203 setOperationAction(ISD::UREM , MVT::i8 , Expand);
204 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
205 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
206 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
207 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
208 setOperationAction(ISD::SREM , MVT::i16 , Expand);
209 setOperationAction(ISD::UREM , MVT::i16 , Expand);
210 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
211 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
212 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
213 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
214 setOperationAction(ISD::SREM , MVT::i32 , Expand);
215 setOperationAction(ISD::UREM , MVT::i32 , Expand);
216 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
217 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
218 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
219 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
220 setOperationAction(ISD::SREM , MVT::i64 , Expand);
221 setOperationAction(ISD::UREM , MVT::i64 , Expand);
223 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
224 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
225 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
226 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
227 if (Subtarget->is64Bit())
228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
232 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
233 setOperationAction(ISD::FREM , MVT::f32 , Expand);
234 setOperationAction(ISD::FREM , MVT::f64 , Expand);
235 setOperationAction(ISD::FREM , MVT::f80 , Expand);
236 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
238 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
239 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
240 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
241 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
242 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
243 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
244 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
245 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
246 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
247 if (Subtarget->is64Bit()) {
248 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
249 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
250 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
253 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
254 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
256 // These should be promoted to a larger select which is supported.
257 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
258 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
259 // X86 wants to expand cmov itself.
260 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
261 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
262 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
263 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
264 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
265 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
266 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
267 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
268 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
269 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
270 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
271 if (Subtarget->is64Bit()) {
272 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
273 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
275 // X86 ret instruction may pop stack.
276 setOperationAction(ISD::RET , MVT::Other, Custom);
277 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
280 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
281 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
282 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
283 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
284 if (Subtarget->is64Bit())
285 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
286 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
287 if (Subtarget->is64Bit()) {
288 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
289 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
290 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
291 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
293 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
294 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
295 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
296 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
297 if (Subtarget->is64Bit()) {
298 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
299 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
300 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
303 if (Subtarget->hasSSE1())
304 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
306 if (!Subtarget->hasSSE2())
307 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
309 // Expand certain atomics
310 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
311 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
312 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
313 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
315 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
316 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
317 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
318 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
320 if (!Subtarget->is64Bit()) {
321 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
322 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
323 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
324 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
325 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
326 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
327 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
330 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
331 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
332 // FIXME - use subtarget debug flags
333 if (!Subtarget->isTargetDarwin() &&
334 !Subtarget->isTargetELF() &&
335 !Subtarget->isTargetCygMing()) {
336 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
337 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
340 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
341 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
342 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
343 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
344 if (Subtarget->is64Bit()) {
345 setExceptionPointerRegister(X86::RAX);
346 setExceptionSelectorRegister(X86::RDX);
348 setExceptionPointerRegister(X86::EAX);
349 setExceptionSelectorRegister(X86::EDX);
351 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
352 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
354 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
356 setOperationAction(ISD::TRAP, MVT::Other, Legal);
358 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
359 setOperationAction(ISD::VASTART , MVT::Other, Custom);
360 setOperationAction(ISD::VAEND , MVT::Other, Expand);
361 if (Subtarget->is64Bit()) {
362 setOperationAction(ISD::VAARG , MVT::Other, Custom);
363 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
365 setOperationAction(ISD::VAARG , MVT::Other, Expand);
366 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
369 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
370 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
371 if (Subtarget->is64Bit())
372 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
373 if (Subtarget->isTargetCygMing())
374 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
376 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
378 if (X86ScalarSSEf64) {
379 // f32 and f64 use SSE.
380 // Set up the FP register classes.
381 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
382 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
384 // Use ANDPD to simulate FABS.
385 setOperationAction(ISD::FABS , MVT::f64, Custom);
386 setOperationAction(ISD::FABS , MVT::f32, Custom);
388 // Use XORP to simulate FNEG.
389 setOperationAction(ISD::FNEG , MVT::f64, Custom);
390 setOperationAction(ISD::FNEG , MVT::f32, Custom);
392 // Use ANDPD and ORPD to simulate FCOPYSIGN.
393 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
394 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
396 // We don't support sin/cos/fmod
397 setOperationAction(ISD::FSIN , MVT::f64, Expand);
398 setOperationAction(ISD::FCOS , MVT::f64, Expand);
399 setOperationAction(ISD::FSIN , MVT::f32, Expand);
400 setOperationAction(ISD::FCOS , MVT::f32, Expand);
402 // Expand FP immediates into loads from the stack, except for the special
404 addLegalFPImmediate(APFloat(+0.0)); // xorpd
405 addLegalFPImmediate(APFloat(+0.0f)); // xorps
407 // Floating truncations from f80 and extensions to f80 go through memory.
408 // If optimizing, we lie about this though and handle it in
409 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
411 setConvertAction(MVT::f32, MVT::f80, Expand);
412 setConvertAction(MVT::f64, MVT::f80, Expand);
413 setConvertAction(MVT::f80, MVT::f32, Expand);
414 setConvertAction(MVT::f80, MVT::f64, Expand);
416 } else if (X86ScalarSSEf32) {
417 // Use SSE for f32, x87 for f64.
418 // Set up the FP register classes.
419 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
420 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
422 // Use ANDPS to simulate FABS.
423 setOperationAction(ISD::FABS , MVT::f32, Custom);
425 // Use XORP to simulate FNEG.
426 setOperationAction(ISD::FNEG , MVT::f32, Custom);
428 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
430 // Use ANDPS and ORPS to simulate FCOPYSIGN.
431 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
432 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
434 // We don't support sin/cos/fmod
435 setOperationAction(ISD::FSIN , MVT::f32, Expand);
436 setOperationAction(ISD::FCOS , MVT::f32, Expand);
438 // Special cases we handle for FP constants.
439 addLegalFPImmediate(APFloat(+0.0f)); // xorps
440 addLegalFPImmediate(APFloat(+0.0)); // FLD0
441 addLegalFPImmediate(APFloat(+1.0)); // FLD1
442 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
443 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
445 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
446 // this though and handle it in InstructionSelectPreprocess so that
447 // dagcombine2 can hack on these.
449 setConvertAction(MVT::f32, MVT::f64, Expand);
450 setConvertAction(MVT::f32, MVT::f80, Expand);
451 setConvertAction(MVT::f80, MVT::f32, Expand);
452 setConvertAction(MVT::f64, MVT::f32, Expand);
453 // And x87->x87 truncations also.
454 setConvertAction(MVT::f80, MVT::f64, Expand);
458 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
459 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
462 // f32 and f64 in x87.
463 // Set up the FP register classes.
464 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
465 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
467 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
468 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
469 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
470 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
472 // Floating truncations go through memory. If optimizing, we lie about
473 // this though and handle it in InstructionSelectPreprocess so that
474 // dagcombine2 can hack on these.
476 setConvertAction(MVT::f80, MVT::f32, Expand);
477 setConvertAction(MVT::f64, MVT::f32, Expand);
478 setConvertAction(MVT::f80, MVT::f64, Expand);
482 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
483 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
485 addLegalFPImmediate(APFloat(+0.0)); // FLD0
486 addLegalFPImmediate(APFloat(+1.0)); // FLD1
487 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
488 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
489 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
490 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
491 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
492 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
495 // Long double always uses X87.
496 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
497 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
498 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
501 APFloat TmpFlt(+0.0);
502 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
504 addLegalFPImmediate(TmpFlt); // FLD0
506 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
507 APFloat TmpFlt2(+1.0);
508 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
510 addLegalFPImmediate(TmpFlt2); // FLD1
511 TmpFlt2.changeSign();
512 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
516 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
517 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
520 // Always use a library call for pow.
521 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
522 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
523 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
525 setOperationAction(ISD::FLOG, MVT::f80, Expand);
526 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
527 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
528 setOperationAction(ISD::FEXP, MVT::f80, Expand);
529 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
531 // First set operation action for all vector types to either promote
532 // (for widening) or expand (for scalarization). Then we will selectively
533 // turn on ones that can be effectively codegen'd.
534 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
535 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
536 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
551 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
581 if (!DisableMMX && Subtarget->hasMMX()) {
582 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
583 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
584 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
585 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
586 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
588 // FIXME: add MMX packed arithmetics
590 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
591 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
592 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
593 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
595 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
596 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
597 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
598 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
600 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
601 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
603 setOperationAction(ISD::AND, MVT::v8i8, Promote);
604 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
605 setOperationAction(ISD::AND, MVT::v4i16, Promote);
606 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
607 setOperationAction(ISD::AND, MVT::v2i32, Promote);
608 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
609 setOperationAction(ISD::AND, MVT::v1i64, Legal);
611 setOperationAction(ISD::OR, MVT::v8i8, Promote);
612 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
613 setOperationAction(ISD::OR, MVT::v4i16, Promote);
614 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
615 setOperationAction(ISD::OR, MVT::v2i32, Promote);
616 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
617 setOperationAction(ISD::OR, MVT::v1i64, Legal);
619 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
620 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
621 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
622 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
623 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
624 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
625 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
627 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
628 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
629 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
630 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
631 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
632 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
633 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
634 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
635 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
637 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
638 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
639 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
640 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
641 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
643 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
644 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
645 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
646 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
648 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
649 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
650 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
651 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
653 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
655 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
656 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
657 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
658 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
659 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
660 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
663 if (Subtarget->hasSSE1()) {
664 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
666 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
667 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
668 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
669 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
670 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
671 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
672 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
673 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
674 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
675 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
676 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
677 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
680 if (Subtarget->hasSSE2()) {
681 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
682 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
683 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
684 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
685 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
687 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
688 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
689 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
690 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
691 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
692 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
693 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
694 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
695 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
696 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
697 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
698 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
699 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
700 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
701 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
702 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
704 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
705 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
706 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
707 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
709 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
710 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
711 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
712 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
713 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
715 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
716 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
717 MVT VT = (MVT::SimpleValueType)i;
718 // Do not attempt to custom lower non-power-of-2 vectors
719 if (!isPowerOf2_32(VT.getVectorNumElements()))
721 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
722 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
723 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
725 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
726 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
727 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
728 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
729 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
730 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
731 if (Subtarget->is64Bit()) {
732 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
733 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
736 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
737 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
738 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
739 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
740 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
741 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
742 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
743 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
744 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
745 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
746 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
747 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
750 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
752 // Custom lower v2i64 and v2f64 selects.
753 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
754 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
755 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
756 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
760 if (Subtarget->hasSSE41()) {
761 // FIXME: Do we need to handle scalar-to-vector here?
762 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
764 // i8 and i16 vectors are custom , because the source register and source
765 // source memory operand types are not the same width. f32 vectors are
766 // custom since the immediate controlling the insert encodes additional
768 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
769 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
770 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
771 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
773 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
774 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
775 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
776 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
778 if (Subtarget->is64Bit()) {
779 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
780 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
784 if (Subtarget->hasSSE42()) {
785 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
788 // We want to custom lower some of our intrinsics.
789 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
791 // Add/Sub/Mul with overflow operations are custom lowered.
792 setOperationAction(ISD::SADDO, MVT::i32, Custom);
793 setOperationAction(ISD::SADDO, MVT::i64, Custom);
794 setOperationAction(ISD::UADDO, MVT::i32, Custom);
795 setOperationAction(ISD::UADDO, MVT::i64, Custom);
796 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
797 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
798 setOperationAction(ISD::USUBO, MVT::i32, Custom);
799 setOperationAction(ISD::USUBO, MVT::i64, Custom);
800 setOperationAction(ISD::SMULO, MVT::i32, Custom);
801 setOperationAction(ISD::SMULO, MVT::i64, Custom);
802 setOperationAction(ISD::UMULO, MVT::i32, Custom);
803 setOperationAction(ISD::UMULO, MVT::i64, Custom);
805 // We have target-specific dag combine patterns for the following nodes:
806 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
807 setTargetDAGCombine(ISD::BUILD_VECTOR);
808 setTargetDAGCombine(ISD::SELECT);
809 setTargetDAGCombine(ISD::SHL);
810 setTargetDAGCombine(ISD::SRA);
811 setTargetDAGCombine(ISD::SRL);
812 setTargetDAGCombine(ISD::STORE);
814 computeRegisterProperties();
816 // FIXME: These should be based on subtarget info. Plus, the values should
817 // be smaller when we are in optimizing for size mode.
818 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
819 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
820 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
821 allowUnalignedMemoryAccesses = true; // x86 supports it!
822 setPrefLoopAlignment(16);
826 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
831 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
832 /// the desired ByVal argument alignment.
833 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
836 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
837 if (VTy->getBitWidth() == 128)
839 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
840 unsigned EltAlign = 0;
841 getMaxByValAlign(ATy->getElementType(), EltAlign);
842 if (EltAlign > MaxAlign)
844 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
845 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
846 unsigned EltAlign = 0;
847 getMaxByValAlign(STy->getElementType(i), EltAlign);
848 if (EltAlign > MaxAlign)
857 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
858 /// function arguments in the caller parameter area. For X86, aggregates
859 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
860 /// are at 4-byte boundaries.
861 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
862 if (Subtarget->is64Bit()) {
863 // Max of 8 and alignment of type.
864 unsigned TyAlign = TD->getABITypeAlignment(Ty);
871 if (Subtarget->hasSSE1())
872 getMaxByValAlign(Ty, Align);
876 /// getOptimalMemOpType - Returns the target specific optimal type for load
877 /// and store operations as a result of memset, memcpy, and memmove
878 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
881 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
882 bool isSrcConst, bool isSrcStr) const {
883 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
884 // linux. This is because the stack realignment code can't handle certain
885 // cases like PR2962. This should be removed when PR2962 is fixed.
886 if (Subtarget->getStackAlignment() >= 16) {
887 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
889 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
892 if (Subtarget->is64Bit() && Size >= 8)
898 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
900 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
901 SelectionDAG &DAG) const {
902 if (usesGlobalOffsetTable())
903 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
904 if (!Subtarget->isPICStyleRIPRel())
905 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
909 //===----------------------------------------------------------------------===//
910 // Return Value Calling Convention Implementation
911 //===----------------------------------------------------------------------===//
913 #include "X86GenCallingConv.inc"
915 /// LowerRET - Lower an ISD::RET node.
916 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
917 DebugLoc dl = Op.getNode()->getDebugLoc();
918 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
920 SmallVector<CCValAssign, 16> RVLocs;
921 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
922 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
923 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
924 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
926 // If this is the first return lowered for this function, add the regs to the
927 // liveout set for the function.
928 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
929 for (unsigned i = 0; i != RVLocs.size(); ++i)
930 if (RVLocs[i].isRegLoc())
931 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
933 SDValue Chain = Op.getOperand(0);
935 // Handle tail call return.
936 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
937 if (Chain.getOpcode() == X86ISD::TAILCALL) {
938 SDValue TailCall = Chain;
939 SDValue TargetAddress = TailCall.getOperand(1);
940 SDValue StackAdjustment = TailCall.getOperand(2);
941 assert(((TargetAddress.getOpcode() == ISD::Register &&
942 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
943 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
944 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
945 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
946 "Expecting an global address, external symbol, or register");
947 assert(StackAdjustment.getOpcode() == ISD::Constant &&
948 "Expecting a const value");
950 SmallVector<SDValue,8> Operands;
951 Operands.push_back(Chain.getOperand(0));
952 Operands.push_back(TargetAddress);
953 Operands.push_back(StackAdjustment);
954 // Copy registers used by the call. Last operand is a flag so it is not
956 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
957 Operands.push_back(Chain.getOperand(i));
959 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
966 SmallVector<SDValue, 6> RetOps;
967 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
968 // Operand #1 = Bytes To Pop
969 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
971 // Copy the result values into the output registers.
972 for (unsigned i = 0; i != RVLocs.size(); ++i) {
973 CCValAssign &VA = RVLocs[i];
974 assert(VA.isRegLoc() && "Can only return in registers!");
975 SDValue ValToCopy = Op.getOperand(i*2+1);
977 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
978 // the RET instruction and handled by the FP Stackifier.
979 if (RVLocs[i].getLocReg() == X86::ST0 ||
980 RVLocs[i].getLocReg() == X86::ST1) {
981 // If this is a copy from an xmm register to ST(0), use an FPExtend to
982 // change the value to the FP stack register class.
983 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
984 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
985 RetOps.push_back(ValToCopy);
986 // Don't emit a copytoreg.
990 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
991 Flag = Chain.getValue(1);
994 // The x86-64 ABI for returning structs by value requires that we copy
995 // the sret argument into %rax for the return. We saved the argument into
996 // a virtual register in the entry block, so now we copy the value out
998 if (Subtarget->is64Bit() &&
999 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1000 MachineFunction &MF = DAG.getMachineFunction();
1001 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1002 unsigned Reg = FuncInfo->getSRetReturnReg();
1004 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1005 FuncInfo->setSRetReturnReg(Reg);
1007 SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
1009 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
1010 Flag = Chain.getValue(1);
1013 RetOps[0] = Chain; // Update chain.
1015 // Add the flag if we have it.
1017 RetOps.push_back(Flag);
1019 return DAG.getNode(X86ISD::RET_FLAG, dl,
1020 MVT::Other, &RetOps[0], RetOps.size());
1024 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1025 /// appropriate copies out of appropriate physical registers. This assumes that
1026 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1027 /// being lowered. The returns a SDNode with the same number of values as the
1029 SDNode *X86TargetLowering::
1030 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1031 unsigned CallingConv, SelectionDAG &DAG) {
1033 DebugLoc dl = TheCall->getDebugLoc();
1034 // Assign locations to each value returned by this call.
1035 SmallVector<CCValAssign, 16> RVLocs;
1036 bool isVarArg = TheCall->isVarArg();
1037 bool Is64Bit = Subtarget->is64Bit();
1038 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1039 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1041 SmallVector<SDValue, 8> ResultVals;
1043 // Copy all of the result registers out of their specified physreg.
1044 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1045 MVT CopyVT = RVLocs[i].getValVT();
1047 // If this is x86-64, and we disabled SSE, we can't return FP values
1048 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1049 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1050 cerr << "SSE register return with SSE disabled\n";
1054 // If this is a call to a function that returns an fp value on the floating
1055 // point stack, but where we prefer to use the value in xmm registers, copy
1056 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1057 if ((RVLocs[i].getLocReg() == X86::ST0 ||
1058 RVLocs[i].getLocReg() == X86::ST1) &&
1059 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1063 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
1064 CopyVT, InFlag).getValue(1);
1065 SDValue Val = Chain.getValue(0);
1066 InFlag = Chain.getValue(2);
1068 if (CopyVT != RVLocs[i].getValVT()) {
1069 // Round the F80 the right size, which also moves to the appropriate xmm
1071 Val = DAG.getNode(ISD::FP_ROUND, dl, RVLocs[i].getValVT(), Val,
1072 // This truncation won't change the value.
1073 DAG.getIntPtrConstant(1));
1076 ResultVals.push_back(Val);
1079 // Merge everything together with a MERGE_VALUES node.
1080 ResultVals.push_back(Chain);
1081 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1082 &ResultVals[0], ResultVals.size()).getNode();
1086 //===----------------------------------------------------------------------===//
1087 // C & StdCall & Fast Calling Convention implementation
1088 //===----------------------------------------------------------------------===//
1089 // StdCall calling convention seems to be standard for many Windows' API
1090 // routines and around. It differs from C calling convention just a little:
1091 // callee should clean up the stack, not caller. Symbols should be also
1092 // decorated in some fancy way :) It doesn't support any vector arguments.
1093 // For info on fast calling convention see Fast Calling Convention (tail call)
1094 // implementation LowerX86_32FastCCCallTo.
1096 /// AddLiveIn - This helper function adds the specified physical register to the
1097 /// MachineFunction as a live in value. It also creates a corresponding virtual
1098 /// register for it.
1099 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1100 const TargetRegisterClass *RC) {
1101 assert(RC->contains(PReg) && "Not the correct regclass!");
1102 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1103 MF.getRegInfo().addLiveIn(PReg, VReg);
1107 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1109 static bool CallIsStructReturn(CallSDNode *TheCall) {
1110 unsigned NumOps = TheCall->getNumArgs();
1114 return TheCall->getArgFlags(0).isSRet();
1117 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1118 /// return semantics.
1119 static bool ArgsAreStructReturn(SDValue Op) {
1120 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1124 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1127 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1128 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1130 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1134 switch (CallingConv) {
1137 case CallingConv::X86_StdCall:
1138 return !Subtarget->is64Bit();
1139 case CallingConv::X86_FastCall:
1140 return !Subtarget->is64Bit();
1141 case CallingConv::Fast:
1142 return PerformTailCallOpt;
1146 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1147 /// given CallingConvention value.
1148 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1149 if (Subtarget->is64Bit()) {
1150 if (Subtarget->isTargetWin64())
1151 return CC_X86_Win64_C;
1152 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1153 return CC_X86_64_TailCall;
1158 if (CC == CallingConv::X86_FastCall)
1159 return CC_X86_32_FastCall;
1160 else if (CC == CallingConv::Fast)
1161 return CC_X86_32_FastCC;
1166 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1167 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1169 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1170 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1171 if (CC == CallingConv::X86_FastCall)
1173 else if (CC == CallingConv::X86_StdCall)
1179 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1180 /// in a register before calling.
1181 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1182 return !IsTailCall && !Is64Bit &&
1183 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1184 Subtarget->isPICStyleGOT();
1187 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1188 /// address to be loaded in a register.
1190 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1191 return !Is64Bit && IsTailCall &&
1192 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1193 Subtarget->isPICStyleGOT();
1196 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1197 /// by "Src" to address "Dst" with size and alignment information specified by
1198 /// the specific parameter attribute. The copy will be passed as a byval
1199 /// function parameter.
1201 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1202 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1203 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1204 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1205 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1208 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1209 const CCValAssign &VA,
1210 MachineFrameInfo *MFI,
1212 SDValue Root, unsigned i) {
1213 // Create the nodes corresponding to a load from this parameter slot.
1214 ISD::ArgFlagsTy Flags =
1215 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1216 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1217 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1219 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1220 // changed with more analysis.
1221 // In case of tail call optimization mark all arguments mutable. Since they
1222 // could be overwritten by lowering of arguments in case of a tail call.
1223 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1224 VA.getLocMemOffset(), isImmutable);
1225 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1226 if (Flags.isByVal())
1228 return DAG.getLoad(VA.getValVT(), Op.getNode()->getDebugLoc(), Root, FIN,
1229 PseudoSourceValue::getFixedStack(FI), 0);
1233 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1234 MachineFunction &MF = DAG.getMachineFunction();
1235 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1236 DebugLoc dl = Op.getNode()->getDebugLoc();
1238 const Function* Fn = MF.getFunction();
1239 if (Fn->hasExternalLinkage() &&
1240 Subtarget->isTargetCygMing() &&
1241 Fn->getName() == "main")
1242 FuncInfo->setForceFramePointer(true);
1244 // Decorate the function name.
1245 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1247 MachineFrameInfo *MFI = MF.getFrameInfo();
1248 SDValue Root = Op.getOperand(0);
1249 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1250 unsigned CC = MF.getFunction()->getCallingConv();
1251 bool Is64Bit = Subtarget->is64Bit();
1252 bool IsWin64 = Subtarget->isTargetWin64();
1254 assert(!(isVarArg && CC == CallingConv::Fast) &&
1255 "Var args not supported with calling convention fastcc");
1257 // Assign locations to all of the incoming arguments.
1258 SmallVector<CCValAssign, 16> ArgLocs;
1259 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1260 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1262 SmallVector<SDValue, 8> ArgValues;
1263 unsigned LastVal = ~0U;
1264 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1265 CCValAssign &VA = ArgLocs[i];
1266 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1268 assert(VA.getValNo() != LastVal &&
1269 "Don't support value assigned to multiple locs yet");
1270 LastVal = VA.getValNo();
1272 if (VA.isRegLoc()) {
1273 MVT RegVT = VA.getLocVT();
1274 TargetRegisterClass *RC = NULL;
1275 if (RegVT == MVT::i32)
1276 RC = X86::GR32RegisterClass;
1277 else if (Is64Bit && RegVT == MVT::i64)
1278 RC = X86::GR64RegisterClass;
1279 else if (RegVT == MVT::f32)
1280 RC = X86::FR32RegisterClass;
1281 else if (RegVT == MVT::f64)
1282 RC = X86::FR64RegisterClass;
1283 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1284 RC = X86::VR128RegisterClass;
1285 else if (RegVT.isVector()) {
1286 assert(RegVT.getSizeInBits() == 64);
1288 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1290 // Darwin calling convention passes MMX values in either GPRs or
1291 // XMMs in x86-64. Other targets pass them in memory.
1292 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1293 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1296 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1301 assert(0 && "Unknown argument type!");
1304 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1305 SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1307 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1308 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1310 if (VA.getLocInfo() == CCValAssign::SExt)
1311 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1312 DAG.getValueType(VA.getValVT()));
1313 else if (VA.getLocInfo() == CCValAssign::ZExt)
1314 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1315 DAG.getValueType(VA.getValVT()));
1317 if (VA.getLocInfo() != CCValAssign::Full)
1318 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1320 // Handle MMX values passed in GPRs.
1321 if (Is64Bit && RegVT != VA.getLocVT()) {
1322 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1323 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1324 else if (RC == X86::VR128RegisterClass) {
1325 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1326 ArgValue, DAG.getConstant(0, MVT::i64));
1327 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1331 ArgValues.push_back(ArgValue);
1333 assert(VA.isMemLoc());
1334 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1338 // The x86-64 ABI for returning structs by value requires that we copy
1339 // the sret argument into %rax for the return. Save the argument into
1340 // a virtual register so that we can access it from the return points.
1341 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1342 MachineFunction &MF = DAG.getMachineFunction();
1343 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1344 unsigned Reg = FuncInfo->getSRetReturnReg();
1346 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1347 FuncInfo->setSRetReturnReg(Reg);
1349 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1350 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1353 unsigned StackSize = CCInfo.getNextStackOffset();
1354 // align stack specially for tail calls
1355 if (PerformTailCallOpt && CC == CallingConv::Fast)
1356 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1358 // If the function takes variable number of arguments, make a frame index for
1359 // the start of the first vararg value... for expansion of llvm.va_start.
1361 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1362 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1365 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1367 // FIXME: We should really autogenerate these arrays
1368 static const unsigned GPR64ArgRegsWin64[] = {
1369 X86::RCX, X86::RDX, X86::R8, X86::R9
1371 static const unsigned XMMArgRegsWin64[] = {
1372 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1374 static const unsigned GPR64ArgRegs64Bit[] = {
1375 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1377 static const unsigned XMMArgRegs64Bit[] = {
1378 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1379 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1381 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1384 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1385 GPR64ArgRegs = GPR64ArgRegsWin64;
1386 XMMArgRegs = XMMArgRegsWin64;
1388 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1389 GPR64ArgRegs = GPR64ArgRegs64Bit;
1390 XMMArgRegs = XMMArgRegs64Bit;
1392 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1394 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1397 assert((Subtarget->hasSSE1() || !NumXMMRegs) &&
1398 "SSE register cannot be used when SSE is disabled!");
1399 if (!Subtarget->hasSSE1()) {
1400 // Kernel mode asks for SSE to be disabled, so don't push them
1402 TotalNumXMMRegs = 0;
1404 // For X86-64, if there are vararg parameters that are passed via
1405 // registers, then we must store them to their spots on the stack so they
1406 // may be loaded by deferencing the result of va_next.
1407 VarArgsGPOffset = NumIntRegs * 8;
1408 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1409 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1410 TotalNumXMMRegs * 16, 16);
1412 // Store the integer parameter registers.
1413 SmallVector<SDValue, 8> MemOps;
1414 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1415 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1416 DAG.getIntPtrConstant(VarArgsGPOffset));
1417 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1418 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1419 X86::GR64RegisterClass);
1420 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1422 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1423 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1424 MemOps.push_back(Store);
1425 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1426 DAG.getIntPtrConstant(8));
1429 // Now store the XMM (fp + vector) parameter registers.
1430 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1431 DAG.getIntPtrConstant(VarArgsFPOffset));
1432 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1433 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1434 X86::VR128RegisterClass);
1435 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1437 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1438 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1439 MemOps.push_back(Store);
1440 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1441 DAG.getIntPtrConstant(16));
1443 if (!MemOps.empty())
1444 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1445 &MemOps[0], MemOps.size());
1449 ArgValues.push_back(Root);
1451 // Some CCs need callee pop.
1452 if (IsCalleePop(isVarArg, CC)) {
1453 BytesToPopOnReturn = StackSize; // Callee pops everything.
1454 BytesCallerReserves = 0;
1456 BytesToPopOnReturn = 0; // Callee pops nothing.
1457 // If this is an sret function, the return should pop the hidden pointer.
1458 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1459 BytesToPopOnReturn = 4;
1460 BytesCallerReserves = StackSize;
1464 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1465 if (CC == CallingConv::X86_FastCall)
1466 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1469 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1471 // Return the new list of results.
1472 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1473 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1477 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1478 const SDValue &StackPtr,
1479 const CCValAssign &VA,
1481 SDValue Arg, ISD::ArgFlagsTy Flags) {
1482 DebugLoc dl = TheCall->getDebugLoc();
1483 unsigned LocMemOffset = VA.getLocMemOffset();
1484 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1485 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1486 if (Flags.isByVal()) {
1487 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1489 return DAG.getStore(Chain, dl, Arg, PtrOff,
1490 PseudoSourceValue::getStack(), LocMemOffset);
1493 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1494 /// optimization is performed and it is required.
1496 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1497 SDValue &OutRetAddr,
1503 if (!IsTailCall || FPDiff==0) return Chain;
1505 // Adjust the Return address stack slot.
1506 MVT VT = getPointerTy();
1507 OutRetAddr = getReturnAddressFrameIndex(DAG);
1509 // Load the "old" Return address.
1510 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1511 return SDValue(OutRetAddr.getNode(), 1);
1514 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1515 /// optimization is performed and it is required (FPDiff!=0).
1517 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1518 SDValue Chain, SDValue RetAddrFrIdx,
1519 bool Is64Bit, int FPDiff, DebugLoc dl) {
1520 // Store the return address to the appropriate stack slot.
1521 if (!FPDiff) return Chain;
1522 // Calculate the new stack slot for the return address.
1523 int SlotSize = Is64Bit ? 8 : 4;
1524 int NewReturnAddrFI =
1525 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1526 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1527 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1528 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1529 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1533 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1534 MachineFunction &MF = DAG.getMachineFunction();
1535 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1536 SDValue Chain = TheCall->getChain();
1537 unsigned CC = TheCall->getCallingConv();
1538 bool isVarArg = TheCall->isVarArg();
1539 bool IsTailCall = TheCall->isTailCall() &&
1540 CC == CallingConv::Fast && PerformTailCallOpt;
1541 SDValue Callee = TheCall->getCallee();
1542 bool Is64Bit = Subtarget->is64Bit();
1543 bool IsStructRet = CallIsStructReturn(TheCall);
1544 DebugLoc dl = TheCall->getDebugLoc();
1546 assert(!(isVarArg && CC == CallingConv::Fast) &&
1547 "Var args not supported with calling convention fastcc");
1549 // Analyze operands of the call, assigning locations to each operand.
1550 SmallVector<CCValAssign, 16> ArgLocs;
1551 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1552 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1554 // Get a count of how many bytes are to be pushed on the stack.
1555 unsigned NumBytes = CCInfo.getNextStackOffset();
1556 if (PerformTailCallOpt && CC == CallingConv::Fast)
1557 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1561 // Lower arguments at fp - stackoffset + fpdiff.
1562 unsigned NumBytesCallerPushed =
1563 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1564 FPDiff = NumBytesCallerPushed - NumBytes;
1566 // Set the delta of movement of the returnaddr stackslot.
1567 // But only set if delta is greater than previous delta.
1568 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1569 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1572 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1574 SDValue RetAddrFrIdx;
1575 // Load return adress for tail calls.
1576 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1579 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1580 SmallVector<SDValue, 8> MemOpChains;
1583 // Walk the register/memloc assignments, inserting copies/loads. In the case
1584 // of tail call optimization arguments are handle later.
1585 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1586 CCValAssign &VA = ArgLocs[i];
1587 SDValue Arg = TheCall->getArg(i);
1588 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1589 bool isByVal = Flags.isByVal();
1591 // Promote the value if needed.
1592 switch (VA.getLocInfo()) {
1593 default: assert(0 && "Unknown loc info!");
1594 case CCValAssign::Full: break;
1595 case CCValAssign::SExt:
1596 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1598 case CCValAssign::ZExt:
1599 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1601 case CCValAssign::AExt:
1602 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1606 if (VA.isRegLoc()) {
1608 MVT RegVT = VA.getLocVT();
1609 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1610 switch (VA.getLocReg()) {
1613 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1615 // Special case: passing MMX values in GPR registers.
1616 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1619 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1620 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1621 // Special case: passing MMX values in XMM registers.
1622 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1623 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1624 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
1625 DAG.getNode(ISD::UNDEF, dl, MVT::v2i64), Arg,
1626 getMOVLMask(2, DAG, dl));
1631 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1633 if (!IsTailCall || (IsTailCall && isByVal)) {
1634 assert(VA.isMemLoc());
1635 if (StackPtr.getNode() == 0)
1636 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1638 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1639 Chain, Arg, Flags));
1644 if (!MemOpChains.empty())
1645 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1646 &MemOpChains[0], MemOpChains.size());
1648 // Build a sequence of copy-to-reg nodes chained together with token chain
1649 // and flag operands which copy the outgoing args into registers.
1651 // Tail call byval lowering might overwrite argument registers so in case of
1652 // tail call optimization the copies to registers are lowered later.
1654 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1655 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1657 InFlag = Chain.getValue(1);
1660 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1662 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1663 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1664 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1666 InFlag = Chain.getValue(1);
1668 // If we are tail calling and generating PIC/GOT style code load the address
1669 // of the callee into ecx. The value in ecx is used as target of the tail
1670 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1671 // calls on PIC/GOT architectures. Normally we would just put the address of
1672 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1673 // restored (since ebx is callee saved) before jumping to the target@PLT.
1674 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1675 // Note: The actual moving to ecx is done further down.
1676 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1677 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1678 !G->getGlobal()->hasProtectedVisibility())
1679 Callee = LowerGlobalAddress(Callee, DAG);
1680 else if (isa<ExternalSymbolSDNode>(Callee))
1681 Callee = LowerExternalSymbol(Callee,DAG);
1684 if (Is64Bit && isVarArg) {
1685 // From AMD64 ABI document:
1686 // For calls that may call functions that use varargs or stdargs
1687 // (prototype-less calls or calls to functions containing ellipsis (...) in
1688 // the declaration) %al is used as hidden argument to specify the number
1689 // of SSE registers used. The contents of %al do not need to match exactly
1690 // the number of registers, but must be an ubound on the number of SSE
1691 // registers used and is in the range 0 - 8 inclusive.
1693 // FIXME: Verify this on Win64
1694 // Count the number of XMM registers allocated.
1695 static const unsigned XMMArgRegs[] = {
1696 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1697 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1699 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1700 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1701 && "SSE registers cannot be used when SSE is disabled");
1703 Chain = DAG.getCopyToReg(Chain, X86::AL,
1704 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1705 InFlag = Chain.getValue(1);
1709 // For tail calls lower the arguments to the 'real' stack slot.
1711 SmallVector<SDValue, 8> MemOpChains2;
1714 // Do not flag preceeding copytoreg stuff together with the following stuff.
1716 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1717 CCValAssign &VA = ArgLocs[i];
1718 if (!VA.isRegLoc()) {
1719 assert(VA.isMemLoc());
1720 SDValue Arg = TheCall->getArg(i);
1721 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1722 // Create frame index.
1723 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1724 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1725 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1726 FIN = DAG.getFrameIndex(FI, getPointerTy());
1728 if (Flags.isByVal()) {
1729 // Copy relative to framepointer.
1730 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1731 if (StackPtr.getNode() == 0)
1732 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1733 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1735 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1738 // Store relative to framepointer.
1739 MemOpChains2.push_back(
1740 DAG.getStore(Chain, dl, Arg, FIN,
1741 PseudoSourceValue::getFixedStack(FI), 0));
1746 if (!MemOpChains2.empty())
1747 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1748 &MemOpChains2[0], MemOpChains2.size());
1750 // Copy arguments to their registers.
1751 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1752 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1754 InFlag = Chain.getValue(1);
1758 // Store the return address to the appropriate stack slot.
1759 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1763 // If the callee is a GlobalAddress node (quite common, every direct call is)
1764 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1765 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1766 // We should use extra load for direct calls to dllimported functions in
1768 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1769 getTargetMachine(), true))
1770 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1772 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1773 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1774 } else if (IsTailCall) {
1775 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1777 Chain = DAG.getCopyToReg(Chain,
1778 DAG.getRegister(Opc, getPointerTy()),
1780 Callee = DAG.getRegister(Opc, getPointerTy());
1781 // Add register as live out.
1782 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1785 // Returns a chain & a flag for retval copy to use.
1786 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1787 SmallVector<SDValue, 8> Ops;
1790 Ops.push_back(Chain);
1791 Ops.push_back(DAG.getIntPtrConstant(NumBytes, true));
1792 Ops.push_back(DAG.getIntPtrConstant(0, true));
1793 if (InFlag.getNode())
1794 Ops.push_back(InFlag);
1795 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1796 InFlag = Chain.getValue(1);
1798 // Returns a chain & a flag for retval copy to use.
1799 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1803 Ops.push_back(Chain);
1804 Ops.push_back(Callee);
1807 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1809 // Add argument registers to the end of the list so that they are known live
1811 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1812 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1813 RegsToPass[i].second.getValueType()));
1815 // Add an implicit use GOT pointer in EBX.
1816 if (!IsTailCall && !Is64Bit &&
1817 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1818 Subtarget->isPICStyleGOT())
1819 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1821 // Add an implicit use of AL for x86 vararg functions.
1822 if (Is64Bit && isVarArg)
1823 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1825 if (InFlag.getNode())
1826 Ops.push_back(InFlag);
1829 assert(InFlag.getNode() &&
1830 "Flag must be set. Depend on flag being set in LowerRET");
1831 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1832 TheCall->getVTList(), &Ops[0], Ops.size());
1834 return SDValue(Chain.getNode(), Op.getResNo());
1837 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1838 InFlag = Chain.getValue(1);
1840 // Create the CALLSEQ_END node.
1841 unsigned NumBytesForCalleeToPush;
1842 if (IsCalleePop(isVarArg, CC))
1843 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1844 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1845 // If this is is a call to a struct-return function, the callee
1846 // pops the hidden struct pointer, so we have to push it back.
1847 // This is common for Darwin/X86, Linux & Mingw32 targets.
1848 NumBytesForCalleeToPush = 4;
1850 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1852 // Returns a flag for retval copy to use.
1853 Chain = DAG.getCALLSEQ_END(Chain,
1854 DAG.getIntPtrConstant(NumBytes, true),
1855 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1858 InFlag = Chain.getValue(1);
1860 // Handle result values, copying them out of physregs into vregs that we
1862 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1867 //===----------------------------------------------------------------------===//
1868 // Fast Calling Convention (tail call) implementation
1869 //===----------------------------------------------------------------------===//
1871 // Like std call, callee cleans arguments, convention except that ECX is
1872 // reserved for storing the tail called function address. Only 2 registers are
1873 // free for argument passing (inreg). Tail call optimization is performed
1875 // * tailcallopt is enabled
1876 // * caller/callee are fastcc
1877 // On X86_64 architecture with GOT-style position independent code only local
1878 // (within module) calls are supported at the moment.
1879 // To keep the stack aligned according to platform abi the function
1880 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1881 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1882 // If a tail called function callee has more arguments than the caller the
1883 // caller needs to make sure that there is room to move the RETADDR to. This is
1884 // achieved by reserving an area the size of the argument delta right after the
1885 // original REtADDR, but before the saved framepointer or the spilled registers
1886 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1898 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1899 /// for a 16 byte align requirement.
1900 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1901 SelectionDAG& DAG) {
1902 MachineFunction &MF = DAG.getMachineFunction();
1903 const TargetMachine &TM = MF.getTarget();
1904 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1905 unsigned StackAlignment = TFI.getStackAlignment();
1906 uint64_t AlignMask = StackAlignment - 1;
1907 int64_t Offset = StackSize;
1908 uint64_t SlotSize = TD->getPointerSize();
1909 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1910 // Number smaller than 12 so just add the difference.
1911 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1913 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1914 Offset = ((~AlignMask) & Offset) + StackAlignment +
1915 (StackAlignment-SlotSize);
1920 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1921 /// following the call is a return. A function is eligible if caller/callee
1922 /// calling conventions match, currently only fastcc supports tail calls, and
1923 /// the function CALL is immediatly followed by a RET.
1924 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1926 SelectionDAG& DAG) const {
1927 if (!PerformTailCallOpt)
1930 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1931 MachineFunction &MF = DAG.getMachineFunction();
1932 unsigned CallerCC = MF.getFunction()->getCallingConv();
1933 unsigned CalleeCC= TheCall->getCallingConv();
1934 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1935 SDValue Callee = TheCall->getCallee();
1936 // On x86/32Bit PIC/GOT tail calls are supported.
1937 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1938 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1941 // Can only do local tail calls (in same module, hidden or protected) on
1942 // x86_64 PIC/GOT at the moment.
1943 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1944 return G->getGlobal()->hasHiddenVisibility()
1945 || G->getGlobal()->hasProtectedVisibility();
1953 X86TargetLowering::createFastISel(MachineFunction &mf,
1954 MachineModuleInfo *mmo,
1956 DenseMap<const Value *, unsigned> &vm,
1957 DenseMap<const BasicBlock *,
1958 MachineBasicBlock *> &bm,
1959 DenseMap<const AllocaInst *, int> &am
1961 , SmallSet<Instruction*, 8> &cil
1964 return X86::createFastISel(mf, mmo, dw, vm, bm, am
1972 //===----------------------------------------------------------------------===//
1973 // Other Lowering Hooks
1974 //===----------------------------------------------------------------------===//
1977 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1978 MachineFunction &MF = DAG.getMachineFunction();
1979 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1980 int ReturnAddrIndex = FuncInfo->getRAIndex();
1982 if (ReturnAddrIndex == 0) {
1983 // Set up a frame object for the return address.
1984 uint64_t SlotSize = TD->getPointerSize();
1985 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1986 FuncInfo->setRAIndex(ReturnAddrIndex);
1989 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1993 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
1994 /// specific condition code, returning the condition code and the LHS/RHS of the
1995 /// comparison to make.
1996 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1997 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
1999 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2000 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2001 // X > -1 -> X == 0, jump !sign.
2002 RHS = DAG.getConstant(0, RHS.getValueType());
2003 return X86::COND_NS;
2004 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2005 // X < 0 -> X == 0, jump on sign.
2007 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2009 RHS = DAG.getConstant(0, RHS.getValueType());
2010 return X86::COND_LE;
2014 switch (SetCCOpcode) {
2015 default: assert(0 && "Invalid integer condition!");
2016 case ISD::SETEQ: return X86::COND_E;
2017 case ISD::SETGT: return X86::COND_G;
2018 case ISD::SETGE: return X86::COND_GE;
2019 case ISD::SETLT: return X86::COND_L;
2020 case ISD::SETLE: return X86::COND_LE;
2021 case ISD::SETNE: return X86::COND_NE;
2022 case ISD::SETULT: return X86::COND_B;
2023 case ISD::SETUGT: return X86::COND_A;
2024 case ISD::SETULE: return X86::COND_BE;
2025 case ISD::SETUGE: return X86::COND_AE;
2029 // First determine if it is required or is profitable to flip the operands.
2031 // If LHS is a foldable load, but RHS is not, flip the condition.
2032 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2033 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2034 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2035 std::swap(LHS, RHS);
2038 switch (SetCCOpcode) {
2044 std::swap(LHS, RHS);
2048 // On a floating point condition, the flags are set as follows:
2050 // 0 | 0 | 0 | X > Y
2051 // 0 | 0 | 1 | X < Y
2052 // 1 | 0 | 0 | X == Y
2053 // 1 | 1 | 1 | unordered
2054 switch (SetCCOpcode) {
2055 default: assert(0 && "Condcode should be pre-legalized away");
2057 case ISD::SETEQ: return X86::COND_E;
2058 case ISD::SETOLT: // flipped
2060 case ISD::SETGT: return X86::COND_A;
2061 case ISD::SETOLE: // flipped
2063 case ISD::SETGE: return X86::COND_AE;
2064 case ISD::SETUGT: // flipped
2066 case ISD::SETLT: return X86::COND_B;
2067 case ISD::SETUGE: // flipped
2069 case ISD::SETLE: return X86::COND_BE;
2071 case ISD::SETNE: return X86::COND_NE;
2072 case ISD::SETUO: return X86::COND_P;
2073 case ISD::SETO: return X86::COND_NP;
2077 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2078 /// code. Current x86 isa includes the following FP cmov instructions:
2079 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2080 static bool hasFPCMov(unsigned X86CC) {
2096 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2097 /// true if Op is undef or if its value falls within the specified range (L, H].
2098 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2099 if (Op.getOpcode() == ISD::UNDEF)
2102 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2103 return (Val >= Low && Val < Hi);
2106 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2107 /// true if Op is undef or if its value equal to the specified value.
2108 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2109 if (Op.getOpcode() == ISD::UNDEF)
2111 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2114 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2115 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2116 bool X86::isPSHUFDMask(SDNode *N) {
2117 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2119 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2122 // Check if the value doesn't reference the second vector.
2123 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2124 SDValue Arg = N->getOperand(i);
2125 if (Arg.getOpcode() == ISD::UNDEF) continue;
2126 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2127 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2134 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2135 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2136 bool X86::isPSHUFHWMask(SDNode *N) {
2137 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2139 if (N->getNumOperands() != 8)
2142 // Lower quadword copied in order.
2143 for (unsigned i = 0; i != 4; ++i) {
2144 SDValue Arg = N->getOperand(i);
2145 if (Arg.getOpcode() == ISD::UNDEF) continue;
2146 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2147 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2151 // Upper quadword shuffled.
2152 for (unsigned i = 4; i != 8; ++i) {
2153 SDValue Arg = N->getOperand(i);
2154 if (Arg.getOpcode() == ISD::UNDEF) continue;
2155 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2156 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2157 if (Val < 4 || Val > 7)
2164 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2165 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2166 bool X86::isPSHUFLWMask(SDNode *N) {
2167 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2169 if (N->getNumOperands() != 8)
2172 // Upper quadword copied in order.
2173 for (unsigned i = 4; i != 8; ++i)
2174 if (!isUndefOrEqual(N->getOperand(i), i))
2177 // Lower quadword shuffled.
2178 for (unsigned i = 0; i != 4; ++i)
2179 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2185 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2186 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2187 template<class SDOperand>
2188 static bool isSHUFPMask(SDOperand *Elems, unsigned NumElems) {
2189 if (NumElems != 2 && NumElems != 4) return false;
2191 unsigned Half = NumElems / 2;
2192 for (unsigned i = 0; i < Half; ++i)
2193 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2195 for (unsigned i = Half; i < NumElems; ++i)
2196 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2202 bool X86::isSHUFPMask(SDNode *N) {
2203 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2204 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2207 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2208 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2209 /// half elements to come from vector 1 (which would equal the dest.) and
2210 /// the upper half to come from vector 2.
2211 template<class SDOperand>
2212 static bool isCommutedSHUFP(SDOperand *Ops, unsigned NumOps) {
2213 if (NumOps != 2 && NumOps != 4) return false;
2215 unsigned Half = NumOps / 2;
2216 for (unsigned i = 0; i < Half; ++i)
2217 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2219 for (unsigned i = Half; i < NumOps; ++i)
2220 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2225 static bool isCommutedSHUFP(SDNode *N) {
2226 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2227 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2230 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2231 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2232 bool X86::isMOVHLPSMask(SDNode *N) {
2233 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2235 if (N->getNumOperands() != 4)
2238 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2239 return isUndefOrEqual(N->getOperand(0), 6) &&
2240 isUndefOrEqual(N->getOperand(1), 7) &&
2241 isUndefOrEqual(N->getOperand(2), 2) &&
2242 isUndefOrEqual(N->getOperand(3), 3);
2245 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2246 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2248 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2249 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2251 if (N->getNumOperands() != 4)
2254 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2255 return isUndefOrEqual(N->getOperand(0), 2) &&
2256 isUndefOrEqual(N->getOperand(1), 3) &&
2257 isUndefOrEqual(N->getOperand(2), 2) &&
2258 isUndefOrEqual(N->getOperand(3), 3);
2261 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2262 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2263 bool X86::isMOVLPMask(SDNode *N) {
2264 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2266 unsigned NumElems = N->getNumOperands();
2267 if (NumElems != 2 && NumElems != 4)
2270 for (unsigned i = 0; i < NumElems/2; ++i)
2271 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2274 for (unsigned i = NumElems/2; i < NumElems; ++i)
2275 if (!isUndefOrEqual(N->getOperand(i), i))
2281 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2282 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2284 bool X86::isMOVHPMask(SDNode *N) {
2285 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2287 unsigned NumElems = N->getNumOperands();
2288 if (NumElems != 2 && NumElems != 4)
2291 for (unsigned i = 0; i < NumElems/2; ++i)
2292 if (!isUndefOrEqual(N->getOperand(i), i))
2295 for (unsigned i = 0; i < NumElems/2; ++i) {
2296 SDValue Arg = N->getOperand(i + NumElems/2);
2297 if (!isUndefOrEqual(Arg, i + NumElems))
2304 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2305 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2306 template<class SDOperand>
2307 bool static isUNPCKLMask(SDOperand *Elts, unsigned NumElts,
2308 bool V2IsSplat = false) {
2309 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2312 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2313 SDValue BitI = Elts[i];
2314 SDValue BitI1 = Elts[i+1];
2315 if (!isUndefOrEqual(BitI, j))
2318 if (isUndefOrEqual(BitI1, NumElts))
2321 if (!isUndefOrEqual(BitI1, j + NumElts))
2329 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2330 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2331 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2334 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2335 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2336 template<class SDOperand>
2337 bool static isUNPCKHMask(SDOperand *Elts, unsigned NumElts,
2338 bool V2IsSplat = false) {
2339 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2342 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2343 SDValue BitI = Elts[i];
2344 SDValue BitI1 = Elts[i+1];
2345 if (!isUndefOrEqual(BitI, j + NumElts/2))
2348 if (isUndefOrEqual(BitI1, NumElts))
2351 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2359 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2360 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2361 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2364 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2365 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2367 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2368 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2370 unsigned NumElems = N->getNumOperands();
2371 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2374 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2375 SDValue BitI = N->getOperand(i);
2376 SDValue BitI1 = N->getOperand(i+1);
2378 if (!isUndefOrEqual(BitI, j))
2380 if (!isUndefOrEqual(BitI1, j))
2387 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2388 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2390 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2391 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2393 unsigned NumElems = N->getNumOperands();
2394 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2397 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2398 SDValue BitI = N->getOperand(i);
2399 SDValue BitI1 = N->getOperand(i + 1);
2401 if (!isUndefOrEqual(BitI, j))
2403 if (!isUndefOrEqual(BitI1, j))
2410 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2411 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2412 /// MOVSD, and MOVD, i.e. setting the lowest element.
2413 template<class SDOperand>
2414 static bool isMOVLMask(SDOperand *Elts, unsigned NumElts) {
2415 if (NumElts != 2 && NumElts != 4)
2418 if (!isUndefOrEqual(Elts[0], NumElts))
2421 for (unsigned i = 1; i < NumElts; ++i) {
2422 if (!isUndefOrEqual(Elts[i], i))
2429 bool X86::isMOVLMask(SDNode *N) {
2430 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2431 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2434 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2435 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2436 /// element of vector 2 and the other elements to come from vector 1 in order.
2437 template<class SDOperand>
2438 static bool isCommutedMOVL(SDOperand *Ops, unsigned NumOps,
2439 bool V2IsSplat = false,
2440 bool V2IsUndef = false) {
2441 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2444 if (!isUndefOrEqual(Ops[0], 0))
2447 for (unsigned i = 1; i < NumOps; ++i) {
2448 SDValue Arg = Ops[i];
2449 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2450 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2451 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2458 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2459 bool V2IsUndef = false) {
2460 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2461 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2462 V2IsSplat, V2IsUndef);
2465 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2466 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2467 bool X86::isMOVSHDUPMask(SDNode *N) {
2468 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2470 if (N->getNumOperands() != 4)
2473 // Expect 1, 1, 3, 3
2474 for (unsigned i = 0; i < 2; ++i) {
2475 SDValue Arg = N->getOperand(i);
2476 if (Arg.getOpcode() == ISD::UNDEF) continue;
2477 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2478 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2479 if (Val != 1) return false;
2483 for (unsigned i = 2; i < 4; ++i) {
2484 SDValue Arg = N->getOperand(i);
2485 if (Arg.getOpcode() == ISD::UNDEF) continue;
2486 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2487 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2488 if (Val != 3) return false;
2492 // Don't use movshdup if it can be done with a shufps.
2496 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2497 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2498 bool X86::isMOVSLDUPMask(SDNode *N) {
2499 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2501 if (N->getNumOperands() != 4)
2504 // Expect 0, 0, 2, 2
2505 for (unsigned i = 0; i < 2; ++i) {
2506 SDValue Arg = N->getOperand(i);
2507 if (Arg.getOpcode() == ISD::UNDEF) continue;
2508 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2509 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2510 if (Val != 0) return false;
2514 for (unsigned i = 2; i < 4; ++i) {
2515 SDValue Arg = N->getOperand(i);
2516 if (Arg.getOpcode() == ISD::UNDEF) continue;
2517 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2518 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2519 if (Val != 2) return false;
2523 // Don't use movshdup if it can be done with a shufps.
2527 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2528 /// specifies a identity operation on the LHS or RHS.
2529 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2530 unsigned NumElems = N->getNumOperands();
2531 for (unsigned i = 0; i < NumElems; ++i)
2532 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2537 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2538 /// a splat of a single element.
2539 static bool isSplatMask(SDNode *N) {
2540 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2542 // This is a splat operation if each element of the permute is the same, and
2543 // if the value doesn't reference the second vector.
2544 unsigned NumElems = N->getNumOperands();
2545 SDValue ElementBase;
2547 for (; i != NumElems; ++i) {
2548 SDValue Elt = N->getOperand(i);
2549 if (isa<ConstantSDNode>(Elt)) {
2555 if (!ElementBase.getNode())
2558 for (; i != NumElems; ++i) {
2559 SDValue Arg = N->getOperand(i);
2560 if (Arg.getOpcode() == ISD::UNDEF) continue;
2561 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2562 if (Arg != ElementBase) return false;
2565 // Make sure it is a splat of the first vector operand.
2566 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2569 /// getSplatMaskEltNo - Given a splat mask, return the index to the element
2570 /// we want to splat.
2571 static SDValue getSplatMaskEltNo(SDNode *N) {
2572 assert(isSplatMask(N) && "Not a splat mask");
2573 unsigned NumElems = N->getNumOperands();
2574 SDValue ElementBase;
2576 for (; i != NumElems; ++i) {
2577 SDValue Elt = N->getOperand(i);
2578 if (isa<ConstantSDNode>(Elt))
2581 assert(0 && " No splat value found!");
2586 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2587 /// a splat of a single element and it's a 2 or 4 element mask.
2588 bool X86::isSplatMask(SDNode *N) {
2589 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2591 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2592 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2594 return ::isSplatMask(N);
2597 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2598 /// specifies a splat of zero element.
2599 bool X86::isSplatLoMask(SDNode *N) {
2600 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2602 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2603 if (!isUndefOrEqual(N->getOperand(i), 0))
2608 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2609 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2610 bool X86::isMOVDDUPMask(SDNode *N) {
2611 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2613 unsigned e = N->getNumOperands() / 2;
2614 for (unsigned i = 0; i < e; ++i)
2615 if (!isUndefOrEqual(N->getOperand(i), i))
2617 for (unsigned i = 0; i < e; ++i)
2618 if (!isUndefOrEqual(N->getOperand(e+i), i))
2623 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2624 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2626 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2627 unsigned NumOperands = N->getNumOperands();
2628 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2630 for (unsigned i = 0; i < NumOperands; ++i) {
2632 SDValue Arg = N->getOperand(NumOperands-i-1);
2633 if (Arg.getOpcode() != ISD::UNDEF)
2634 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2635 if (Val >= NumOperands) Val -= NumOperands;
2637 if (i != NumOperands - 1)
2644 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2645 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2647 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2649 // 8 nodes, but we only care about the last 4.
2650 for (unsigned i = 7; i >= 4; --i) {
2652 SDValue Arg = N->getOperand(i);
2653 if (Arg.getOpcode() != ISD::UNDEF)
2654 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2663 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2664 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2666 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2668 // 8 nodes, but we only care about the first 4.
2669 for (int i = 3; i >= 0; --i) {
2671 SDValue Arg = N->getOperand(i);
2672 if (Arg.getOpcode() != ISD::UNDEF)
2673 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2682 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2683 /// specifies a 8 element shuffle that can be broken into a pair of
2684 /// PSHUFHW and PSHUFLW.
2685 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2686 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2688 if (N->getNumOperands() != 8)
2691 // Lower quadword shuffled.
2692 for (unsigned i = 0; i != 4; ++i) {
2693 SDValue Arg = N->getOperand(i);
2694 if (Arg.getOpcode() == ISD::UNDEF) continue;
2695 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2696 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2701 // Upper quadword shuffled.
2702 for (unsigned i = 4; i != 8; ++i) {
2703 SDValue Arg = N->getOperand(i);
2704 if (Arg.getOpcode() == ISD::UNDEF) continue;
2705 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2706 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2707 if (Val < 4 || Val > 7)
2714 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2715 /// values in ther permute mask.
2716 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2717 SDValue &V2, SDValue &Mask,
2718 SelectionDAG &DAG) {
2719 MVT VT = Op.getValueType();
2720 MVT MaskVT = Mask.getValueType();
2721 MVT EltVT = MaskVT.getVectorElementType();
2722 unsigned NumElems = Mask.getNumOperands();
2723 SmallVector<SDValue, 8> MaskVec;
2724 DebugLoc dl = Op.getNode()->getDebugLoc();
2726 for (unsigned i = 0; i != NumElems; ++i) {
2727 SDValue Arg = Mask.getOperand(i);
2728 if (Arg.getOpcode() == ISD::UNDEF) {
2729 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, EltVT));
2732 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2733 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2735 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2737 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2741 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2742 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
2745 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2746 /// the two vector operands have swapped position.
2748 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG, DebugLoc dl) {
2749 MVT MaskVT = Mask.getValueType();
2750 MVT EltVT = MaskVT.getVectorElementType();
2751 unsigned NumElems = Mask.getNumOperands();
2752 SmallVector<SDValue, 8> MaskVec;
2753 for (unsigned i = 0; i != NumElems; ++i) {
2754 SDValue Arg = Mask.getOperand(i);
2755 if (Arg.getOpcode() == ISD::UNDEF) {
2756 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, EltVT));
2759 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2760 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2762 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2764 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2766 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2770 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2771 /// match movhlps. The lower half elements should come from upper half of
2772 /// V1 (and in order), and the upper half elements should come from the upper
2773 /// half of V2 (and in order).
2774 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2775 unsigned NumElems = Mask->getNumOperands();
2778 for (unsigned i = 0, e = 2; i != e; ++i)
2779 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2781 for (unsigned i = 2; i != 4; ++i)
2782 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2787 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2788 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2790 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2791 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2793 N = N->getOperand(0).getNode();
2794 if (!ISD::isNON_EXTLoad(N))
2797 *LD = cast<LoadSDNode>(N);
2801 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2802 /// match movlp{s|d}. The lower half elements should come from lower half of
2803 /// V1 (and in order), and the upper half elements should come from the upper
2804 /// half of V2 (and in order). And since V1 will become the source of the
2805 /// MOVLP, it must be either a vector load or a scalar load to vector.
2806 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2807 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2809 // Is V2 is a vector load, don't do this transformation. We will try to use
2810 // load folding shufps op.
2811 if (ISD::isNON_EXTLoad(V2))
2814 unsigned NumElems = Mask->getNumOperands();
2815 if (NumElems != 2 && NumElems != 4)
2817 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2818 if (!isUndefOrEqual(Mask->getOperand(i), i))
2820 for (unsigned i = NumElems/2; i != NumElems; ++i)
2821 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2826 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2828 static bool isSplatVector(SDNode *N) {
2829 if (N->getOpcode() != ISD::BUILD_VECTOR)
2832 SDValue SplatValue = N->getOperand(0);
2833 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2834 if (N->getOperand(i) != SplatValue)
2839 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2841 static bool isUndefShuffle(SDNode *N) {
2842 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2845 SDValue V1 = N->getOperand(0);
2846 SDValue V2 = N->getOperand(1);
2847 SDValue Mask = N->getOperand(2);
2848 unsigned NumElems = Mask.getNumOperands();
2849 for (unsigned i = 0; i != NumElems; ++i) {
2850 SDValue Arg = Mask.getOperand(i);
2851 if (Arg.getOpcode() != ISD::UNDEF) {
2852 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2853 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2855 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2862 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2864 static inline bool isZeroNode(SDValue Elt) {
2865 return ((isa<ConstantSDNode>(Elt) &&
2866 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2867 (isa<ConstantFPSDNode>(Elt) &&
2868 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2871 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2872 /// to an zero vector.
2873 static bool isZeroShuffle(SDNode *N) {
2874 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2877 SDValue V1 = N->getOperand(0);
2878 SDValue V2 = N->getOperand(1);
2879 SDValue Mask = N->getOperand(2);
2880 unsigned NumElems = Mask.getNumOperands();
2881 for (unsigned i = 0; i != NumElems; ++i) {
2882 SDValue Arg = Mask.getOperand(i);
2883 if (Arg.getOpcode() == ISD::UNDEF)
2886 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2887 if (Idx < NumElems) {
2888 unsigned Opc = V1.getNode()->getOpcode();
2889 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2891 if (Opc != ISD::BUILD_VECTOR ||
2892 !isZeroNode(V1.getNode()->getOperand(Idx)))
2894 } else if (Idx >= NumElems) {
2895 unsigned Opc = V2.getNode()->getOpcode();
2896 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2898 if (Opc != ISD::BUILD_VECTOR ||
2899 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2906 /// getZeroVector - Returns a vector of specified type with all zero elements.
2908 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2910 assert(VT.isVector() && "Expected a vector type");
2912 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2913 // type. This ensures they get CSE'd.
2915 if (VT.getSizeInBits() == 64) { // MMX
2916 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2917 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2918 } else if (HasSSE2) { // SSE2
2919 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2920 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2922 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2923 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2925 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2928 /// getOnesVector - Returns a vector of specified type with all bits set.
2930 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2931 assert(VT.isVector() && "Expected a vector type");
2933 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2934 // type. This ensures they get CSE'd.
2935 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2937 if (VT.getSizeInBits() == 64) // MMX
2938 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2940 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2941 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2945 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2946 /// that point to V2 points to its first element.
2947 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2948 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2950 bool Changed = false;
2951 SmallVector<SDValue, 8> MaskVec;
2952 unsigned NumElems = Mask.getNumOperands();
2953 for (unsigned i = 0; i != NumElems; ++i) {
2954 SDValue Arg = Mask.getOperand(i);
2955 if (Arg.getOpcode() != ISD::UNDEF) {
2956 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2957 if (Val > NumElems) {
2958 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2962 MaskVec.push_back(Arg);
2966 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getNode()->getDebugLoc(),
2967 Mask.getValueType(),
2968 &MaskVec[0], MaskVec.size());
2972 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2973 /// operation of specified width.
2974 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG, DebugLoc dl) {
2975 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2976 MVT BaseVT = MaskVT.getVectorElementType();
2978 SmallVector<SDValue, 8> MaskVec;
2979 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2980 for (unsigned i = 1; i != NumElems; ++i)
2981 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2982 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
2983 &MaskVec[0], MaskVec.size());
2986 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2987 /// of specified width.
2988 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG,
2990 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2991 MVT BaseVT = MaskVT.getVectorElementType();
2992 SmallVector<SDValue, 8> MaskVec;
2993 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2994 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2995 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2997 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
2998 &MaskVec[0], MaskVec.size());
3001 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3002 /// of specified width.
3003 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG,
3005 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3006 MVT BaseVT = MaskVT.getVectorElementType();
3007 unsigned Half = NumElems/2;
3008 SmallVector<SDValue, 8> MaskVec;
3009 for (unsigned i = 0; i != Half; ++i) {
3010 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3011 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3013 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3014 &MaskVec[0], MaskVec.size());
3017 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
3018 /// element #0 of a vector with the specified index, leaving the rest of the
3019 /// elements in place.
3020 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
3021 SelectionDAG &DAG, DebugLoc dl) {
3022 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3023 MVT BaseVT = MaskVT.getVectorElementType();
3024 SmallVector<SDValue, 8> MaskVec;
3025 // Element #0 of the result gets the elt we are replacing.
3026 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
3027 for (unsigned i = 1; i != NumElems; ++i)
3028 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
3029 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3030 &MaskVec[0], MaskVec.size());
3033 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3034 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
3035 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
3036 MVT VT = Op.getValueType();
3039 SDValue V1 = Op.getOperand(0);
3040 SDValue Mask = Op.getOperand(2);
3041 unsigned MaskNumElems = Mask.getNumOperands();
3042 unsigned NumElems = MaskNumElems;
3043 DebugLoc dl = Op.getNode()->getDebugLoc();
3044 // Special handling of v4f32 -> v4i32.
3045 if (VT != MVT::v4f32) {
3046 // Find which element we want to splat.
3047 SDNode* EltNoNode = getSplatMaskEltNo(Mask.getNode()).getNode();
3048 unsigned EltNo = cast<ConstantSDNode>(EltNoNode)->getZExtValue();
3049 // unpack elements to the correct location
3050 while (NumElems > 4) {
3051 if (EltNo < NumElems/2) {
3052 Mask = getUnpacklMask(MaskNumElems, DAG, dl);
3054 Mask = getUnpackhMask(MaskNumElems, DAG, dl);
3055 EltNo -= NumElems/2;
3057 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1, Mask);
3060 SDValue Cst = DAG.getConstant(EltNo, MVT::i32);
3061 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3064 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3065 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3066 DAG.getNode(ISD::UNDEF, PVT), Mask);
3067 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3070 /// isVectorLoad - Returns true if the node is a vector load, a scalar
3071 /// load that's promoted to vector, or a load bitcasted.
3072 static bool isVectorLoad(SDValue Op) {
3073 assert(Op.getValueType().isVector() && "Expected a vector type");
3074 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
3075 Op.getOpcode() == ISD::BIT_CONVERT) {
3076 return isa<LoadSDNode>(Op.getOperand(0));
3078 return isa<LoadSDNode>(Op);
3082 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3084 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3085 SelectionDAG &DAG, bool HasSSE3) {
3086 // If we have sse3 and shuffle has more than one use or input is a load, then
3087 // use movddup. Otherwise, use movlhps.
3088 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3089 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3090 MVT VT = Op.getValueType();
3093 DebugLoc dl = Op.getNode()->getDebugLoc();
3094 unsigned NumElems = PVT.getVectorNumElements();
3095 if (NumElems == 2) {
3096 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3097 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3099 assert(NumElems == 4);
3100 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3101 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3102 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
3103 Cst0, Cst1, Cst0, Cst1);
3106 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3107 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3108 DAG.getNode(ISD::UNDEF, dl, PVT), Mask);
3109 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3112 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3113 /// vector of zero or undef vector. This produces a shuffle where the low
3114 /// element of V2 is swizzled into the zero/undef vector, landing at element
3115 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3116 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3117 bool isZero, bool HasSSE2,
3118 SelectionDAG &DAG) {
3119 DebugLoc dl = V2.getNode()->getDebugLoc();
3120 MVT VT = V2.getValueType();
3122 ? getZeroVector(VT, HasSSE2, DAG, dl) : DAG.getNode(ISD::UNDEF, dl, VT);
3123 unsigned NumElems = V2.getValueType().getVectorNumElements();
3124 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3125 MVT EVT = MaskVT.getVectorElementType();
3126 SmallVector<SDValue, 16> MaskVec;
3127 for (unsigned i = 0; i != NumElems; ++i)
3128 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3129 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3131 MaskVec.push_back(DAG.getConstant(i, EVT));
3132 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3133 &MaskVec[0], MaskVec.size());
3134 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
3137 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3138 /// a shuffle that is zero.
3140 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3141 unsigned NumElems, bool Low,
3142 SelectionDAG &DAG) {
3143 unsigned NumZeros = 0;
3144 for (unsigned i = 0; i < NumElems; ++i) {
3145 unsigned Index = Low ? i : NumElems-i-1;
3146 SDValue Idx = Mask.getOperand(Index);
3147 if (Idx.getOpcode() == ISD::UNDEF) {
3151 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3152 if (Elt.getNode() && isZeroNode(Elt))
3160 /// isVectorShift - Returns true if the shuffle can be implemented as a
3161 /// logical left or right shift of a vector.
3162 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3163 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3164 unsigned NumElems = Mask.getNumOperands();
3167 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3170 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3175 bool SeenV1 = false;
3176 bool SeenV2 = false;
3177 for (unsigned i = NumZeros; i < NumElems; ++i) {
3178 unsigned Val = isLeft ? (i - NumZeros) : i;
3179 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3180 if (Idx.getOpcode() == ISD::UNDEF)
3182 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3183 if (Index < NumElems)
3192 if (SeenV1 && SeenV2)
3195 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3201 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3203 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3204 unsigned NumNonZero, unsigned NumZero,
3205 SelectionDAG &DAG, TargetLowering &TLI) {
3209 DebugLoc dl = Op.getNode()->getDebugLoc();
3212 for (unsigned i = 0; i < 16; ++i) {
3213 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3214 if (ThisIsNonZero && First) {
3216 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3218 V = DAG.getNode(ISD::UNDEF, dl, MVT::v8i16);
3223 SDValue ThisElt(0, 0), LastElt(0, 0);
3224 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3225 if (LastIsNonZero) {
3226 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3227 MVT::i16, Op.getOperand(i-1));
3229 if (ThisIsNonZero) {
3230 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3231 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3232 ThisElt, DAG.getConstant(8, MVT::i8));
3234 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3238 if (ThisElt.getNode())
3239 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3240 DAG.getIntPtrConstant(i/2));
3244 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3247 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3249 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3250 unsigned NumNonZero, unsigned NumZero,
3251 SelectionDAG &DAG, TargetLowering &TLI) {
3255 DebugLoc dl = Op.getNode()->getDebugLoc();
3258 for (unsigned i = 0; i < 8; ++i) {
3259 bool isNonZero = (NonZeros & (1 << i)) != 0;
3263 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3265 V = DAG.getNode(ISD::UNDEF, dl, MVT::v8i16);
3268 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3269 MVT::v8i16, V, Op.getOperand(i),
3270 DAG.getIntPtrConstant(i));
3277 /// getVShift - Return a vector logical shift node.
3279 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3280 unsigned NumBits, SelectionDAG &DAG,
3281 const TargetLowering &TLI, DebugLoc dl) {
3282 bool isMMX = VT.getSizeInBits() == 64;
3283 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3284 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3285 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3286 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3287 DAG.getNode(Opc, dl, ShVT, SrcOp,
3288 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3292 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3293 DebugLoc dl = Op.getNode()->getDebugLoc();
3294 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3295 if (ISD::isBuildVectorAllZeros(Op.getNode())
3296 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3297 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3298 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3299 // eliminated on x86-32 hosts.
3300 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3303 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3304 return getOnesVector(Op.getValueType(), DAG, dl);
3305 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3308 MVT VT = Op.getValueType();
3309 MVT EVT = VT.getVectorElementType();
3310 unsigned EVTBits = EVT.getSizeInBits();
3312 unsigned NumElems = Op.getNumOperands();
3313 unsigned NumZero = 0;
3314 unsigned NumNonZero = 0;
3315 unsigned NonZeros = 0;
3316 bool IsAllConstants = true;
3317 SmallSet<SDValue, 8> Values;
3318 for (unsigned i = 0; i < NumElems; ++i) {
3319 SDValue Elt = Op.getOperand(i);
3320 if (Elt.getOpcode() == ISD::UNDEF)
3323 if (Elt.getOpcode() != ISD::Constant &&
3324 Elt.getOpcode() != ISD::ConstantFP)
3325 IsAllConstants = false;
3326 if (isZeroNode(Elt))
3329 NonZeros |= (1 << i);
3334 if (NumNonZero == 0) {
3335 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3336 return DAG.getNode(ISD::UNDEF, dl, VT);
3339 // Special case for single non-zero, non-undef, element.
3340 if (NumNonZero == 1 && NumElems <= 4) {
3341 unsigned Idx = CountTrailingZeros_32(NonZeros);
3342 SDValue Item = Op.getOperand(Idx);
3344 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3345 // the value are obviously zero, truncate the value to i32 and do the
3346 // insertion that way. Only do this if the value is non-constant or if the
3347 // value is a constant being inserted into element 0. It is cheaper to do
3348 // a constant pool load than it is to do a movd + shuffle.
3349 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3350 (!IsAllConstants || Idx == 0)) {
3351 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3352 // Handle MMX and SSE both.
3353 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3354 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3356 // Truncate the value (which may itself be a constant) to i32, and
3357 // convert it to a vector with movd (S2V+shuffle to zero extend).
3358 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3359 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3360 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3361 Subtarget->hasSSE2(), DAG);
3363 // Now we have our 32-bit value zero extended in the low element of
3364 // a vector. If Idx != 0, swizzle it into place.
3367 Item, DAG.getNode(ISD::UNDEF, dl, Item.getValueType()),
3368 getSwapEltZeroMask(VecElts, Idx, DAG, dl)
3370 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VecVT, Ops, 3);
3372 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3376 // If we have a constant or non-constant insertion into the low element of
3377 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3378 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3379 // depending on what the source datatype is. Because we can only get here
3380 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3382 // Don't do this for i64 values on x86-32.
3383 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3384 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3385 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3386 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3387 Subtarget->hasSSE2(), DAG);
3390 // Is it a vector logical left shift?
3391 if (NumElems == 2 && Idx == 1 &&
3392 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3393 unsigned NumBits = VT.getSizeInBits();
3394 return getVShift(true, VT,
3395 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3396 NumBits/2, DAG, *this, dl);
3399 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3402 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3403 // is a non-constant being inserted into an element other than the low one,
3404 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3405 // movd/movss) to move this into the low element, then shuffle it into
3407 if (EVTBits == 32) {
3408 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3410 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3411 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3412 Subtarget->hasSSE2(), DAG);
3413 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3414 MVT MaskEVT = MaskVT.getVectorElementType();
3415 SmallVector<SDValue, 8> MaskVec;
3416 for (unsigned i = 0; i < NumElems; i++)
3417 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3418 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3419 &MaskVec[0], MaskVec.size());
3420 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, Item,
3421 DAG.getNode(ISD::UNDEF, VT), Mask);
3425 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3426 if (Values.size() == 1)
3429 // A vector full of immediates; various special cases are already
3430 // handled, so this is best done with a single constant-pool load.
3434 // Let legalizer expand 2-wide build_vectors.
3435 if (EVTBits == 64) {
3436 if (NumNonZero == 1) {
3437 // One half is zero or undef.
3438 unsigned Idx = CountTrailingZeros_32(NonZeros);
3439 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3440 Op.getOperand(Idx));
3441 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3442 Subtarget->hasSSE2(), DAG);
3447 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3448 if (EVTBits == 8 && NumElems == 16) {
3449 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3451 if (V.getNode()) return V;
3454 if (EVTBits == 16 && NumElems == 8) {
3455 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3457 if (V.getNode()) return V;
3460 // If element VT is == 32 bits, turn it into a number of shuffles.
3461 SmallVector<SDValue, 8> V;
3463 if (NumElems == 4 && NumZero > 0) {
3464 for (unsigned i = 0; i < 4; ++i) {
3465 bool isZero = !(NonZeros & (1 << i));
3467 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3469 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3472 for (unsigned i = 0; i < 2; ++i) {
3473 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3476 V[i] = V[i*2]; // Must be a zero vector.
3479 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2+1], V[i*2],
3480 getMOVLMask(NumElems, DAG, dl));
3483 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3484 getMOVLMask(NumElems, DAG, dl));
3487 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3488 getUnpacklMask(NumElems, DAG, dl));
3493 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3494 MVT EVT = MaskVT.getVectorElementType();
3495 SmallVector<SDValue, 8> MaskVec;
3496 bool Reverse = (NonZeros & 0x3) == 2;
3497 for (unsigned i = 0; i < 2; ++i)
3499 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3501 MaskVec.push_back(DAG.getConstant(i, EVT));
3502 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3503 for (unsigned i = 0; i < 2; ++i)
3505 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3507 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3508 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3509 &MaskVec[0], MaskVec.size());
3510 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[0], V[1], ShufMask);
3513 if (Values.size() > 2) {
3514 // Expand into a number of unpckl*.
3516 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3517 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3518 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3519 SDValue UnpckMask = getUnpacklMask(NumElems, DAG, dl);
3520 for (unsigned i = 0; i < NumElems; ++i)
3521 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3523 while (NumElems != 0) {
3524 for (unsigned i = 0; i < NumElems; ++i)
3525 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i], V[i + NumElems],
3536 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3537 SDValue PermMask, SelectionDAG &DAG,
3538 TargetLowering &TLI, DebugLoc dl) {
3540 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3541 MVT MaskEVT = MaskVT.getVectorElementType();
3542 MVT PtrVT = TLI.getPointerTy();
3543 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3544 PermMask.getNode()->op_end());
3546 // First record which half of which vector the low elements come from.
3547 SmallVector<unsigned, 4> LowQuad(4);
3548 for (unsigned i = 0; i < 4; ++i) {
3549 SDValue Elt = MaskElts[i];
3550 if (Elt.getOpcode() == ISD::UNDEF)
3552 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3553 int QuadIdx = EltIdx / 4;
3557 int BestLowQuad = -1;
3558 unsigned MaxQuad = 1;
3559 for (unsigned i = 0; i < 4; ++i) {
3560 if (LowQuad[i] > MaxQuad) {
3562 MaxQuad = LowQuad[i];
3566 // Record which half of which vector the high elements come from.
3567 SmallVector<unsigned, 4> HighQuad(4);
3568 for (unsigned i = 4; i < 8; ++i) {
3569 SDValue Elt = MaskElts[i];
3570 if (Elt.getOpcode() == ISD::UNDEF)
3572 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3573 int QuadIdx = EltIdx / 4;
3574 ++HighQuad[QuadIdx];
3577 int BestHighQuad = -1;
3579 for (unsigned i = 0; i < 4; ++i) {
3580 if (HighQuad[i] > MaxQuad) {
3582 MaxQuad = HighQuad[i];
3586 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3587 if (BestLowQuad != -1 || BestHighQuad != -1) {
3588 // First sort the 4 chunks in order using shufpd.
3589 SmallVector<SDValue, 8> MaskVec;
3591 if (BestLowQuad != -1)
3592 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3594 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3596 if (BestHighQuad != -1)
3597 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3599 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3601 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, &MaskVec[0],2);
3602 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
3603 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3604 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), Mask);
3605 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3607 // Now sort high and low parts separately.
3608 BitVector InOrder(8);
3609 if (BestLowQuad != -1) {
3610 // Sort lower half in order using PSHUFLW.
3612 bool AnyOutOrder = false;
3614 for (unsigned i = 0; i != 4; ++i) {
3615 SDValue Elt = MaskElts[i];
3616 if (Elt.getOpcode() == ISD::UNDEF) {
3617 MaskVec.push_back(Elt);
3620 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3624 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3626 // If this element is in the right place after this shuffle, then
3628 if ((int)(EltIdx / 4) == BestLowQuad)
3633 for (unsigned i = 4; i != 8; ++i)
3634 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3635 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3637 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16,
3642 if (BestHighQuad != -1) {
3643 // Sort high half in order using PSHUFHW if possible.
3646 for (unsigned i = 0; i != 4; ++i)
3647 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3649 bool AnyOutOrder = false;
3650 for (unsigned i = 4; i != 8; ++i) {
3651 SDValue Elt = MaskElts[i];
3652 if (Elt.getOpcode() == ISD::UNDEF) {
3653 MaskVec.push_back(Elt);
3656 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3660 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3662 // If this element is in the right place after this shuffle, then
3664 if ((int)(EltIdx / 4) == BestHighQuad)
3670 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl,
3671 MaskVT, &MaskVec[0], 8);
3672 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16,
3677 // The other elements are put in the right place using pextrw and pinsrw.
3678 for (unsigned i = 0; i != 8; ++i) {
3681 SDValue Elt = MaskElts[i];
3682 if (Elt.getOpcode() == ISD::UNDEF)
3684 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3685 SDValue ExtOp = (EltIdx < 8)
3686 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3687 DAG.getConstant(EltIdx, PtrVT))
3688 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3689 DAG.getConstant(EltIdx - 8, PtrVT));
3690 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3691 DAG.getConstant(i, PtrVT));
3697 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3698 // few as possible. First, let's find out how many elements are already in the
3700 unsigned V1InOrder = 0;
3701 unsigned V1FromV1 = 0;
3702 unsigned V2InOrder = 0;
3703 unsigned V2FromV2 = 0;
3704 SmallVector<SDValue, 8> V1Elts;
3705 SmallVector<SDValue, 8> V2Elts;
3706 for (unsigned i = 0; i < 8; ++i) {
3707 SDValue Elt = MaskElts[i];
3708 if (Elt.getOpcode() == ISD::UNDEF) {
3709 V1Elts.push_back(Elt);
3710 V2Elts.push_back(Elt);
3715 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3717 V1Elts.push_back(Elt);
3718 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3720 } else if (EltIdx == i+8) {
3721 V1Elts.push_back(Elt);
3722 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3724 } else if (EltIdx < 8) {
3725 V1Elts.push_back(Elt);
3726 V2Elts.push_back(DAG.getConstant(EltIdx+8, MaskEVT));
3729 V1Elts.push_back(Elt);
3730 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3735 if (V2InOrder > V1InOrder) {
3736 PermMask = CommuteVectorShuffleMask(PermMask, DAG, dl);
3738 std::swap(V1Elts, V2Elts);
3739 std::swap(V1FromV1, V2FromV2);
3742 if ((V1FromV1 + V1InOrder) != 8) {
3743 // Some elements are from V2.
3745 // If there are elements that are from V1 but out of place,
3746 // then first sort them in place
3747 SmallVector<SDValue, 8> MaskVec;
3748 for (unsigned i = 0; i < 8; ++i) {
3749 SDValue Elt = V1Elts[i];
3750 if (Elt.getOpcode() == ISD::UNDEF) {
3751 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3754 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3756 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3758 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3760 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], 8);
3761 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, V1, V1, Mask);
3765 for (unsigned i = 0; i < 8; ++i) {
3766 SDValue Elt = V1Elts[i];
3767 if (Elt.getOpcode() == ISD::UNDEF)
3769 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3772 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3773 DAG.getConstant(EltIdx - 8, PtrVT));
3774 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3775 DAG.getConstant(i, PtrVT));
3779 // All elements are from V1.
3781 for (unsigned i = 0; i < 8; ++i) {
3782 SDValue Elt = V1Elts[i];
3783 if (Elt.getOpcode() == ISD::UNDEF)
3785 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3786 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3787 DAG.getConstant(EltIdx, PtrVT));
3788 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3789 DAG.getConstant(i, PtrVT));
3795 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3796 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3797 /// done when every pair / quad of shuffle mask elements point to elements in
3798 /// the right sequence. e.g.
3799 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3801 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3803 SDValue PermMask, SelectionDAG &DAG,
3804 TargetLowering &TLI, DebugLoc dl) {
3805 unsigned NumElems = PermMask.getNumOperands();
3806 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3807 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3808 MVT MaskEltVT = MaskVT.getVectorElementType();
3810 switch (VT.getSimpleVT()) {
3811 default: assert(false && "Unexpected!");
3812 case MVT::v4f32: NewVT = MVT::v2f64; break;
3813 case MVT::v4i32: NewVT = MVT::v2i64; break;
3814 case MVT::v8i16: NewVT = MVT::v4i32; break;
3815 case MVT::v16i8: NewVT = MVT::v4i32; break;
3818 if (NewWidth == 2) {
3824 unsigned Scale = NumElems / NewWidth;
3825 SmallVector<SDValue, 8> MaskVec;
3826 for (unsigned i = 0; i < NumElems; i += Scale) {
3827 unsigned StartIdx = ~0U;
3828 for (unsigned j = 0; j < Scale; ++j) {
3829 SDValue Elt = PermMask.getOperand(i+j);
3830 if (Elt.getOpcode() == ISD::UNDEF)
3832 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3833 if (StartIdx == ~0U)
3834 StartIdx = EltIdx - (EltIdx % Scale);
3835 if (EltIdx != StartIdx + j)
3838 if (StartIdx == ~0U)
3839 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEltVT));
3841 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3844 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3845 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3846 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, NewVT, V1, V2,
3847 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3848 &MaskVec[0], MaskVec.size()));
3851 /// getVZextMovL - Return a zero-extending vector move low node.
3853 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3854 SDValue SrcOp, SelectionDAG &DAG,
3855 const X86Subtarget *Subtarget, DebugLoc dl) {
3856 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3857 LoadSDNode *LD = NULL;
3858 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3859 LD = dyn_cast<LoadSDNode>(SrcOp);
3861 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3863 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3864 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3865 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3866 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3867 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3869 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3870 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3871 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3872 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3880 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3881 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3882 DAG.getNode(ISD::BIT_CONVERT, dl,
3886 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3889 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3890 SDValue PermMask, MVT VT, SelectionDAG &DAG,
3892 MVT MaskVT = PermMask.getValueType();
3893 MVT MaskEVT = MaskVT.getVectorElementType();
3894 SmallVector<std::pair<int, int>, 8> Locs;
3896 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3899 for (unsigned i = 0; i != 4; ++i) {
3900 SDValue Elt = PermMask.getOperand(i);
3901 if (Elt.getOpcode() == ISD::UNDEF) {
3902 Locs[i] = std::make_pair(-1, -1);
3904 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3905 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3907 Locs[i] = std::make_pair(0, NumLo);
3911 Locs[i] = std::make_pair(1, NumHi);
3913 Mask1[2+NumHi] = Elt;
3919 if (NumLo <= 2 && NumHi <= 2) {
3920 // If no more than two elements come from either vector. This can be
3921 // implemented with two shuffles. First shuffle gather the elements.
3922 // The second shuffle, which takes the first shuffle as both of its
3923 // vector operands, put the elements into the right order.
3924 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3925 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3926 &Mask1[0], Mask1.size()));
3928 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3929 for (unsigned i = 0; i != 4; ++i) {
3930 if (Locs[i].first == -1)
3933 unsigned Idx = (i < 2) ? 0 : 4;
3934 Idx += Locs[i].first * 2 + Locs[i].second;
3935 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3939 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1,
3940 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3941 &Mask2[0], Mask2.size()));
3942 } else if (NumLo == 3 || NumHi == 3) {
3943 // Otherwise, we must have three elements from one vector, call it X, and
3944 // one element from the other, call it Y. First, use a shufps to build an
3945 // intermediate vector with the one element from Y and the element from X
3946 // that will be in the same half in the final destination (the indexes don't
3947 // matter). Then, use a shufps to build the final vector, taking the half
3948 // containing the element from Y from the intermediate, and the other half
3951 // Normalize it so the 3 elements come from V1.
3952 PermMask = CommuteVectorShuffleMask(PermMask, DAG, dl);
3956 // Find the element from V2.
3958 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3959 SDValue Elt = PermMask.getOperand(HiIndex);
3960 if (Elt.getOpcode() == ISD::UNDEF)
3962 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3967 Mask1[0] = PermMask.getOperand(HiIndex);
3968 Mask1[1] = DAG.getNode(ISD::UNDEF, dl, MaskEVT);
3969 Mask1[2] = PermMask.getOperand(HiIndex^1);
3970 Mask1[3] = DAG.getNode(ISD::UNDEF, dl, MaskEVT);
3971 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3972 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3975 Mask1[0] = PermMask.getOperand(0);
3976 Mask1[1] = PermMask.getOperand(1);
3977 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3978 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3979 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3980 DAG.getNode(ISD::BUILD_VECTOR, dl,
3981 MaskVT, &Mask1[0], 4));
3983 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3984 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3985 Mask1[2] = PermMask.getOperand(2);
3986 Mask1[3] = PermMask.getOperand(3);
3987 if (Mask1[2].getOpcode() != ISD::UNDEF)
3989 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3991 if (Mask1[3].getOpcode() != ISD::UNDEF)
3993 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3995 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V2, V1,
3996 DAG.getNode(ISD::BUILD_VECTOR, dl,
3997 MaskVT, &Mask1[0], 4));
4001 // Break it into (shuffle shuffle_hi, shuffle_lo).
4003 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
4004 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
4005 SmallVector<SDValue,8> *MaskPtr = &LoMask;
4006 unsigned MaskIdx = 0;
4009 for (unsigned i = 0; i != 4; ++i) {
4016 SDValue Elt = PermMask.getOperand(i);
4017 if (Elt.getOpcode() == ISD::UNDEF) {
4018 Locs[i] = std::make_pair(-1, -1);
4019 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
4020 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4021 (*MaskPtr)[LoIdx] = Elt;
4024 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4025 (*MaskPtr)[HiIdx] = Elt;
4030 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4031 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4032 &LoMask[0], LoMask.size()));
4033 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4034 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4035 &HiMask[0], HiMask.size()));
4036 SmallVector<SDValue, 8> MaskOps;
4037 for (unsigned i = 0; i != 4; ++i) {
4038 if (Locs[i].first == -1) {
4039 MaskOps.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
4041 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4042 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
4045 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, LoShuffle, HiShuffle,
4046 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4047 &MaskOps[0], MaskOps.size()));
4051 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4052 SDValue V1 = Op.getOperand(0);
4053 SDValue V2 = Op.getOperand(1);
4054 SDValue PermMask = Op.getOperand(2);
4055 MVT VT = Op.getValueType();
4056 DebugLoc dl = Op.getNode()->getDebugLoc();
4057 unsigned NumElems = PermMask.getNumOperands();
4058 bool isMMX = VT.getSizeInBits() == 64;
4059 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4060 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4061 bool V1IsSplat = false;
4062 bool V2IsSplat = false;
4064 if (isUndefShuffle(Op.getNode()))
4065 return DAG.getNode(ISD::UNDEF, dl, VT);
4067 if (isZeroShuffle(Op.getNode()))
4068 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4070 if (isIdentityMask(PermMask.getNode()))
4072 else if (isIdentityMask(PermMask.getNode(), true))
4075 // Canonicalize movddup shuffles.
4076 if (V2IsUndef && Subtarget->hasSSE2() &&
4077 VT.getSizeInBits() == 128 &&
4078 X86::isMOVDDUPMask(PermMask.getNode()))
4079 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
4081 if (isSplatMask(PermMask.getNode())) {
4082 if (isMMX || NumElems < 4) return Op;
4083 // Promote it to a v4{if}32 splat.
4084 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
4087 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4089 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4090 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG,
4092 if (NewOp.getNode())
4093 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4094 LowerVECTOR_SHUFFLE(NewOp, DAG));
4095 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4096 // FIXME: Figure out a cleaner way to do this.
4097 // Try to make use of movq to zero out the top part.
4098 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4099 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4101 if (NewOp.getNode()) {
4102 SDValue NewV1 = NewOp.getOperand(0);
4103 SDValue NewV2 = NewOp.getOperand(1);
4104 SDValue NewMask = NewOp.getOperand(2);
4105 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4106 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4107 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget,
4111 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4112 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4114 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4115 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4116 DAG, Subtarget, dl);
4120 // Check if this can be converted into a logical shift.
4121 bool isLeft = false;
4124 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4125 if (isShift && ShVal.hasOneUse()) {
4126 // If the shifted value has multiple uses, it may be cheaper to use
4127 // v_set0 + movlhps or movhlps, etc.
4128 MVT EVT = VT.getVectorElementType();
4129 ShAmt *= EVT.getSizeInBits();
4130 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4133 if (X86::isMOVLMask(PermMask.getNode())) {
4136 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4137 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4142 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4143 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4144 X86::isMOVHLPSMask(PermMask.getNode()) ||
4145 X86::isMOVHPMask(PermMask.getNode()) ||
4146 X86::isMOVLPMask(PermMask.getNode())))
4149 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4150 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4151 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4154 // No better options. Use a vshl / vsrl.
4155 MVT EVT = VT.getVectorElementType();
4156 ShAmt *= EVT.getSizeInBits();
4157 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4160 bool Commuted = false;
4161 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4162 // 1,1,1,1 -> v8i16 though.
4163 V1IsSplat = isSplatVector(V1.getNode());
4164 V2IsSplat = isSplatVector(V2.getNode());
4166 // Canonicalize the splat or undef, if present, to be on the RHS.
4167 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4168 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4169 std::swap(V1IsSplat, V2IsSplat);
4170 std::swap(V1IsUndef, V2IsUndef);
4174 // FIXME: Figure out a cleaner way to do this.
4175 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4176 if (V2IsUndef) return V1;
4177 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4179 // V2 is a splat, so the mask may be malformed. That is, it may point
4180 // to any V2 element. The instruction selectior won't like this. Get
4181 // a corrected mask and commute to form a proper MOVS{S|D}.
4182 SDValue NewMask = getMOVLMask(NumElems, DAG, dl);
4183 if (NewMask.getNode() != PermMask.getNode())
4184 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4189 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4190 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4191 X86::isUNPCKLMask(PermMask.getNode()) ||
4192 X86::isUNPCKHMask(PermMask.getNode()))
4196 // Normalize mask so all entries that point to V2 points to its first
4197 // element then try to match unpck{h|l} again. If match, return a
4198 // new vector_shuffle with the corrected mask.
4199 SDValue NewMask = NormalizeMask(PermMask, DAG);
4200 if (NewMask.getNode() != PermMask.getNode()) {
4201 if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
4202 SDValue NewMask = getUnpacklMask(NumElems, DAG, dl);
4203 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4204 } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
4205 SDValue NewMask = getUnpackhMask(NumElems, DAG, dl);
4206 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4211 // Normalize the node to match x86 shuffle ops if needed
4212 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4213 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4216 // Commute is back and try unpck* again.
4217 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4218 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4219 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4220 X86::isUNPCKLMask(PermMask.getNode()) ||
4221 X86::isUNPCKHMask(PermMask.getNode()))
4225 // Try PSHUF* first, then SHUFP*.
4226 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4227 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4228 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4229 if (V2.getOpcode() != ISD::UNDEF)
4230 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1,
4231 DAG.getNode(ISD::UNDEF, VT), PermMask);
4236 if (Subtarget->hasSSE2() &&
4237 (X86::isPSHUFDMask(PermMask.getNode()) ||
4238 X86::isPSHUFHWMask(PermMask.getNode()) ||
4239 X86::isPSHUFLWMask(PermMask.getNode()))) {
4241 if (VT == MVT::v4f32) {
4243 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT,
4244 DAG.getNode(ISD::BIT_CONVERT, dl, RVT, V1),
4245 DAG.getNode(ISD::UNDEF, dl, RVT), PermMask);
4246 } else if (V2.getOpcode() != ISD::UNDEF)
4247 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT, V1,
4248 DAG.getNode(ISD::UNDEF, dl, RVT), PermMask);
4250 Op = DAG.getNode(ISD::BIT_CONVERT, dl, VT, Op);
4254 // Binary or unary shufps.
4255 if (X86::isSHUFPMask(PermMask.getNode()) ||
4256 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4260 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4261 if (VT == MVT::v8i16) {
4262 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this, dl);
4263 if (NewOp.getNode())
4267 // Handle all 4 wide cases with a number of shuffles except for MMX.
4268 if (NumElems == 4 && !isMMX)
4269 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG, dl);
4275 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4276 SelectionDAG &DAG) {
4277 MVT VT = Op.getValueType();
4278 DebugLoc dl = Op.getNode()->getDebugLoc();
4279 if (VT.getSizeInBits() == 8) {
4280 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4281 Op.getOperand(0), Op.getOperand(1));
4282 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4283 DAG.getValueType(VT));
4284 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4285 } else if (VT.getSizeInBits() == 16) {
4286 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4287 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4289 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4290 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4291 DAG.getNode(ISD::BIT_CONVERT, dl,
4295 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4296 Op.getOperand(0), Op.getOperand(1));
4297 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4298 DAG.getValueType(VT));
4299 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4300 } else if (VT == MVT::f32) {
4301 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4302 // the result back to FR32 register. It's only worth matching if the
4303 // result has a single use which is a store or a bitcast to i32. And in
4304 // the case of a store, it's not worth it if the index is a constant 0,
4305 // because a MOVSSmr can be used instead, which is smaller and faster.
4306 if (!Op.hasOneUse())
4308 SDNode *User = *Op.getNode()->use_begin();
4309 if ((User->getOpcode() != ISD::STORE ||
4310 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4311 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4312 (User->getOpcode() != ISD::BIT_CONVERT ||
4313 User->getValueType(0) != MVT::i32))
4315 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4316 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4319 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4320 } else if (VT == MVT::i32) {
4321 // ExtractPS works with constant index.
4322 if (isa<ConstantSDNode>(Op.getOperand(1)))
4330 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4331 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4334 if (Subtarget->hasSSE41()) {
4335 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4340 MVT VT = Op.getValueType();
4341 DebugLoc dl = Op.getNode()->getDebugLoc();
4342 // TODO: handle v16i8.
4343 if (VT.getSizeInBits() == 16) {
4344 SDValue Vec = Op.getOperand(0);
4345 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4347 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4348 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4349 DAG.getNode(ISD::BIT_CONVERT, dl,
4352 // Transform it so it match pextrw which produces a 32-bit result.
4353 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4354 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4355 Op.getOperand(0), Op.getOperand(1));
4356 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4357 DAG.getValueType(VT));
4358 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4359 } else if (VT.getSizeInBits() == 32) {
4360 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4363 // SHUFPS the element to the lowest double word, then movss.
4364 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4365 SmallVector<SDValue, 8> IdxVec;
4367 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4369 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4371 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4373 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4374 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4375 &IdxVec[0], IdxVec.size());
4376 SDValue Vec = Op.getOperand(0);
4377 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4378 Vec, DAG.getNode(ISD::UNDEF, dl, Vec.getValueType()),
4380 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4381 DAG.getIntPtrConstant(0));
4382 } else if (VT.getSizeInBits() == 64) {
4383 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4384 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4385 // to match extract_elt for f64.
4386 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4390 // UNPCKHPD the element to the lowest double word, then movsd.
4391 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4392 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4393 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4394 SmallVector<SDValue, 8> IdxVec;
4395 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4397 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4398 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4399 &IdxVec[0], IdxVec.size());
4400 SDValue Vec = Op.getOperand(0);
4401 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4402 Vec, DAG.getNode(ISD::UNDEF, dl, Vec.getValueType()),
4404 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4405 DAG.getIntPtrConstant(0));
4412 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4413 MVT VT = Op.getValueType();
4414 MVT EVT = VT.getVectorElementType();
4415 DebugLoc dl = Op.getNode()->getDebugLoc();
4417 SDValue N0 = Op.getOperand(0);
4418 SDValue N1 = Op.getOperand(1);
4419 SDValue N2 = Op.getOperand(2);
4421 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4422 isa<ConstantSDNode>(N2)) {
4423 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4425 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4427 if (N1.getValueType() != MVT::i32)
4428 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4429 if (N2.getValueType() != MVT::i32)
4430 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4431 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4432 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4433 // Bits [7:6] of the constant are the source select. This will always be
4434 // zero here. The DAG Combiner may combine an extract_elt index into these
4435 // bits. For example (insert (extract, 3), 2) could be matched by putting
4436 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4437 // Bits [5:4] of the constant are the destination select. This is the
4438 // value of the incoming immediate.
4439 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4440 // combine either bitwise AND or insert of float 0.0 to set these bits.
4441 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4442 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4443 } else if (EVT == MVT::i32) {
4444 // InsertPS works with constant index.
4445 if (isa<ConstantSDNode>(N2))
4452 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4453 MVT VT = Op.getValueType();
4454 MVT EVT = VT.getVectorElementType();
4456 if (Subtarget->hasSSE41())
4457 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4462 DebugLoc dl = Op.getNode()->getDebugLoc();
4463 SDValue N0 = Op.getOperand(0);
4464 SDValue N1 = Op.getOperand(1);
4465 SDValue N2 = Op.getOperand(2);
4467 if (EVT.getSizeInBits() == 16) {
4468 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4469 // as its second argument.
4470 if (N1.getValueType() != MVT::i32)
4471 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4472 if (N2.getValueType() != MVT::i32)
4473 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4474 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4480 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4481 DebugLoc dl = Op.getNode()->getDebugLoc();
4482 if (Op.getValueType() == MVT::v2f32)
4483 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4484 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4485 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4486 Op.getOperand(0))));
4488 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4489 MVT VT = MVT::v2i32;
4490 switch (Op.getValueType().getSimpleVT()) {
4497 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4498 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4501 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4502 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4503 // one of the above mentioned nodes. It has to be wrapped because otherwise
4504 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4505 // be used to form addressing mode. These wrapped nodes will be selected
4508 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4509 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4510 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4512 CP->getAlignment());
4513 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4514 // With PIC, the address is actually $g + Offset.
4515 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4516 !Subtarget->isPICStyleRIPRel()) {
4517 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4518 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4526 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
4528 SelectionDAG &DAG) const {
4529 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4530 bool ExtraLoadRequired =
4531 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4533 // Create the TargetGlobalAddress node, folding in the constant
4534 // offset if it is legal.
4536 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4537 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4540 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4541 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4543 // With PIC, the address is actually $g + Offset.
4544 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4545 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4546 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4550 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4551 // load the value at address GV, not the value of GV itself. This means that
4552 // the GlobalAddress must be in the base or index register of the address, not
4553 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4554 // The same applies for external symbols during PIC codegen
4555 if (ExtraLoadRequired)
4556 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4557 PseudoSourceValue::getGOT(), 0);
4559 // If there was a non-zero offset that we didn't fold, create an explicit
4562 Result = DAG.getNode(ISD::ADD, getPointerTy(), Result,
4563 DAG.getConstant(Offset, getPointerTy()));
4569 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4570 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4571 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4572 return LowerGlobalAddress(GV, Offset, DAG);
4575 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4577 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4580 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4581 DAG.getNode(X86ISD::GlobalBaseReg,
4583 InFlag = Chain.getValue(1);
4585 // emit leal symbol@TLSGD(,%ebx,1), %eax
4586 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4587 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4588 GA->getValueType(0),
4590 SDValue Ops[] = { Chain, TGA, InFlag };
4591 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4592 InFlag = Result.getValue(2);
4593 Chain = Result.getValue(1);
4595 // call ___tls_get_addr. This function receives its argument in
4596 // the register EAX.
4597 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4598 InFlag = Chain.getValue(1);
4600 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4601 SDValue Ops1[] = { Chain,
4602 DAG.getTargetExternalSymbol("___tls_get_addr",
4604 DAG.getRegister(X86::EAX, PtrVT),
4605 DAG.getRegister(X86::EBX, PtrVT),
4607 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4608 InFlag = Chain.getValue(1);
4610 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4613 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4615 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4617 SDValue InFlag, Chain;
4619 // emit leaq symbol@TLSGD(%rip), %rdi
4620 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4621 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4622 GA->getValueType(0),
4624 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4625 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4626 Chain = Result.getValue(1);
4627 InFlag = Result.getValue(2);
4629 // call __tls_get_addr. This function receives its argument in
4630 // the register RDI.
4631 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4632 InFlag = Chain.getValue(1);
4634 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4635 SDValue Ops1[] = { Chain,
4636 DAG.getTargetExternalSymbol("__tls_get_addr",
4638 DAG.getRegister(X86::RDI, PtrVT),
4640 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4641 InFlag = Chain.getValue(1);
4643 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4646 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4647 // "local exec" model.
4648 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4650 // Get the Thread Pointer
4651 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4652 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4654 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4655 GA->getValueType(0),
4657 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4659 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4660 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4661 PseudoSourceValue::getGOT(), 0);
4663 // The address of the thread local variable is the add of the thread
4664 // pointer with the offset of the variable.
4665 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4669 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4670 // TODO: implement the "local dynamic" model
4671 // TODO: implement the "initial exec"model for pic executables
4672 assert(Subtarget->isTargetELF() &&
4673 "TLS not implemented for non-ELF targets");
4674 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4675 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4676 // otherwise use the "Local Exec"TLS Model
4677 if (Subtarget->is64Bit()) {
4678 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4680 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4681 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4683 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4688 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4689 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4690 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4691 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4692 // With PIC, the address is actually $g + Offset.
4693 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4694 !Subtarget->isPICStyleRIPRel()) {
4695 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4696 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4703 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4704 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4705 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4706 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4707 // With PIC, the address is actually $g + Offset.
4708 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4709 !Subtarget->isPICStyleRIPRel()) {
4710 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4711 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4718 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4719 /// take a 2 x i32 value to shift plus a shift amount.
4720 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4721 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4722 MVT VT = Op.getValueType();
4723 unsigned VTBits = VT.getSizeInBits();
4724 DebugLoc dl = Op.getNode()->getDebugLoc();
4725 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4726 SDValue ShOpLo = Op.getOperand(0);
4727 SDValue ShOpHi = Op.getOperand(1);
4728 SDValue ShAmt = Op.getOperand(2);
4729 SDValue Tmp1 = isSRA ?
4730 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4731 DAG.getConstant(VTBits - 1, MVT::i8)) :
4732 DAG.getConstant(0, VT);
4735 if (Op.getOpcode() == ISD::SHL_PARTS) {
4736 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4737 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4739 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4740 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4743 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4744 DAG.getConstant(VTBits, MVT::i8));
4745 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4746 AndNode, DAG.getConstant(0, MVT::i8));
4749 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4750 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4751 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4753 if (Op.getOpcode() == ISD::SHL_PARTS) {
4754 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4755 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4757 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4758 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4761 SDValue Ops[2] = { Lo, Hi };
4762 return DAG.getMergeValues(Ops, 2, dl);
4765 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4766 MVT SrcVT = Op.getOperand(0).getValueType();
4767 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4768 "Unknown SINT_TO_FP to lower!");
4770 // These are really Legal; caller falls through into that case.
4771 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4773 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4774 Subtarget->is64Bit())
4777 DebugLoc dl = Op.getNode()->getDebugLoc();
4778 unsigned Size = SrcVT.getSizeInBits()/8;
4779 MachineFunction &MF = DAG.getMachineFunction();
4780 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4781 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4782 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4784 PseudoSourceValue::getFixedStack(SSFI), 0);
4788 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4790 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4792 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4793 SmallVector<SDValue, 8> Ops;
4794 Ops.push_back(Chain);
4795 Ops.push_back(StackSlot);
4796 Ops.push_back(DAG.getValueType(SrcVT));
4797 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4798 Tys, &Ops[0], Ops.size());
4801 Chain = Result.getValue(1);
4802 SDValue InFlag = Result.getValue(2);
4804 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4805 // shouldn't be necessary except that RFP cannot be live across
4806 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4807 MachineFunction &MF = DAG.getMachineFunction();
4808 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4809 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4810 Tys = DAG.getVTList(MVT::Other);
4811 SmallVector<SDValue, 8> Ops;
4812 Ops.push_back(Chain);
4813 Ops.push_back(Result);
4814 Ops.push_back(StackSlot);
4815 Ops.push_back(DAG.getValueType(Op.getValueType()));
4816 Ops.push_back(InFlag);
4817 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4818 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4819 PseudoSourceValue::getFixedStack(SSFI), 0);
4825 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4826 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4827 // This algorithm is not obvious. Here it is in C code, more or less:
4829 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4830 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4831 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4833 // Copy ints to xmm registers.
4834 __m128i xh = _mm_cvtsi32_si128( hi );
4835 __m128i xl = _mm_cvtsi32_si128( lo );
4837 // Combine into low half of a single xmm register.
4838 __m128i x = _mm_unpacklo_epi32( xh, xl );
4842 // Merge in appropriate exponents to give the integer bits the right
4844 x = _mm_unpacklo_epi32( x, exp );
4846 // Subtract away the biases to deal with the IEEE-754 double precision
4848 d = _mm_sub_pd( (__m128d) x, bias );
4850 // All conversions up to here are exact. The correctly rounded result is
4851 // calculated using the current rounding mode using the following
4853 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4854 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4855 // store doesn't really need to be here (except
4856 // maybe to zero the other double)
4861 DebugLoc dl = Op.getNode()->getDebugLoc();
4863 // Build some magic constants.
4864 std::vector<Constant*> CV0;
4865 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4866 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4867 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4868 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4869 Constant *C0 = ConstantVector::get(CV0);
4870 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
4872 std::vector<Constant*> CV1;
4873 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4874 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4875 Constant *C1 = ConstantVector::get(CV1);
4876 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
4878 SmallVector<SDValue, 4> MaskVec;
4879 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
4880 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
4881 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
4882 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
4883 SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4884 &MaskVec[0], MaskVec.size());
4885 SmallVector<SDValue, 4> MaskVec2;
4886 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
4887 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
4888 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32,
4889 &MaskVec2[0], MaskVec2.size());
4891 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4892 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4894 DAG.getIntPtrConstant(1)));
4895 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4896 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4898 DAG.getIntPtrConstant(0)));
4899 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
4900 XR1, XR2, UnpcklMask);
4901 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4902 PseudoSourceValue::getConstantPool(), 0,
4904 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
4905 Unpck1, CLod0, UnpcklMask);
4906 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4907 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4908 PseudoSourceValue::getConstantPool(), 0,
4910 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4912 // Add the halves; easiest way is to swap them into another reg first.
4913 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2f64,
4914 Sub, Sub, ShufMask);
4915 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4916 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4917 DAG.getIntPtrConstant(0));
4920 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4921 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4922 DebugLoc dl = Op.getNode()->getDebugLoc();
4923 // FP constant to bias correct the final result.
4924 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4927 // Load the 32-bit value into an XMM register.
4928 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4929 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4931 DAG.getIntPtrConstant(0)));
4933 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4934 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4935 DAG.getIntPtrConstant(0));
4937 // Or the load with the bias.
4938 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4939 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4940 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4942 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4943 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4944 MVT::v2f64, Bias)));
4945 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4946 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4947 DAG.getIntPtrConstant(0));
4949 // Subtract the bias.
4950 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4952 // Handle final rounding.
4953 MVT DestVT = Op.getValueType();
4955 if (DestVT.bitsLT(MVT::f64)) {
4956 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4957 DAG.getIntPtrConstant(0));
4958 } else if (DestVT.bitsGT(MVT::f64)) {
4959 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4962 // Handle final rounding.
4966 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4967 SDValue N0 = Op.getOperand(0);
4968 DebugLoc dl = Op.getNode()->getDebugLoc();
4970 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4971 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4972 // the optimization here.
4973 if (DAG.SignBitIsZero(N0))
4974 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4976 MVT SrcVT = N0.getValueType();
4977 if (SrcVT == MVT::i64) {
4978 // We only handle SSE2 f64 target here; caller can handle the rest.
4979 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4982 return LowerUINT_TO_FP_i64(Op, DAG);
4983 } else if (SrcVT == MVT::i32) {
4984 return LowerUINT_TO_FP_i32(Op, DAG);
4987 assert(0 && "Unknown UINT_TO_FP to lower!");
4991 std::pair<SDValue,SDValue> X86TargetLowering::
4992 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4993 DebugLoc dl = Op.getNode()->getDebugLoc();
4994 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4995 Op.getValueType().getSimpleVT() >= MVT::i16 &&
4996 "Unknown FP_TO_SINT to lower!");
4998 // These are really Legal.
4999 if (Op.getValueType() == MVT::i32 &&
5000 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5001 return std::make_pair(SDValue(), SDValue());
5002 if (Subtarget->is64Bit() &&
5003 Op.getValueType() == MVT::i64 &&
5004 Op.getOperand(0).getValueType() != MVT::f80)
5005 return std::make_pair(SDValue(), SDValue());
5007 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5009 MachineFunction &MF = DAG.getMachineFunction();
5010 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
5011 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5012 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5014 switch (Op.getValueType().getSimpleVT()) {
5015 default: assert(0 && "Invalid FP_TO_SINT to lower!");
5016 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5017 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5018 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5021 SDValue Chain = DAG.getEntryNode();
5022 SDValue Value = Op.getOperand(0);
5023 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5024 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5025 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5026 PseudoSourceValue::getFixedStack(SSFI), 0);
5027 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5029 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5031 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5032 Chain = Value.getValue(1);
5033 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5034 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5037 // Build the FP_TO_INT*_IN_MEM
5038 SDValue Ops[] = { Chain, Value, StackSlot };
5039 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5041 return std::make_pair(FIST, StackSlot);
5044 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5045 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
5046 SDValue FIST = Vals.first, StackSlot = Vals.second;
5047 if (FIST.getNode() == 0) return SDValue();
5050 return DAG.getLoad(Op.getValueType(), Op.getNode()->getDebugLoc(),
5051 FIST, StackSlot, NULL, 0);
5054 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5055 DebugLoc dl = Op.getNode()->getDebugLoc();
5056 MVT VT = Op.getValueType();
5059 EltVT = VT.getVectorElementType();
5060 std::vector<Constant*> CV;
5061 if (EltVT == MVT::f64) {
5062 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
5066 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
5072 Constant *C = ConstantVector::get(CV);
5073 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5074 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5075 PseudoSourceValue::getConstantPool(), 0,
5077 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5080 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5081 DebugLoc dl = Op.getNode()->getDebugLoc();
5082 MVT VT = Op.getValueType();
5084 unsigned EltNum = 1;
5085 if (VT.isVector()) {
5086 EltVT = VT.getVectorElementType();
5087 EltNum = VT.getVectorNumElements();
5089 std::vector<Constant*> CV;
5090 if (EltVT == MVT::f64) {
5091 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
5095 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
5101 Constant *C = ConstantVector::get(CV);
5102 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5103 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5104 PseudoSourceValue::getConstantPool(), 0,
5106 if (VT.isVector()) {
5107 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5108 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5109 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5111 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5113 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5117 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5118 SDValue Op0 = Op.getOperand(0);
5119 SDValue Op1 = Op.getOperand(1);
5120 DebugLoc dl = Op.getNode()->getDebugLoc();
5121 MVT VT = Op.getValueType();
5122 MVT SrcVT = Op1.getValueType();
5124 // If second operand is smaller, extend it first.
5125 if (SrcVT.bitsLT(VT)) {
5126 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5129 // And if it is bigger, shrink it first.
5130 if (SrcVT.bitsGT(VT)) {
5131 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5135 // At this point the operands and the result should have the same
5136 // type, and that won't be f80 since that is not custom lowered.
5138 // First get the sign bit of second operand.
5139 std::vector<Constant*> CV;
5140 if (SrcVT == MVT::f64) {
5141 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5142 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5144 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5145 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5146 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5147 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5149 Constant *C = ConstantVector::get(CV);
5150 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5151 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5152 PseudoSourceValue::getConstantPool(), 0,
5154 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5156 // Shift sign bit right or left if the two operands have different types.
5157 if (SrcVT.bitsGT(VT)) {
5158 // Op0 is MVT::f32, Op1 is MVT::f64.
5159 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5160 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5161 DAG.getConstant(32, MVT::i32));
5162 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5163 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5164 DAG.getIntPtrConstant(0));
5167 // Clear first operand sign bit.
5169 if (VT == MVT::f64) {
5170 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5171 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5173 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5174 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5175 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5176 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5178 C = ConstantVector::get(CV);
5179 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5180 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5181 PseudoSourceValue::getConstantPool(), 0,
5183 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5185 // Or the value with the sign bit.
5186 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5189 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5190 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5191 SDValue Op0 = Op.getOperand(0);
5192 SDValue Op1 = Op.getOperand(1);
5193 DebugLoc dl = Op.getNode()->getDebugLoc();
5194 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5196 // Lower (X & (1 << N)) == 0 to BT(X, N).
5197 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5198 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5199 if (Op0.getOpcode() == ISD::AND &&
5201 Op1.getOpcode() == ISD::Constant &&
5202 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5203 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5205 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5206 if (ConstantSDNode *Op010C =
5207 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5208 if (Op010C->getZExtValue() == 1) {
5209 LHS = Op0.getOperand(0);
5210 RHS = Op0.getOperand(1).getOperand(1);
5212 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5213 if (ConstantSDNode *Op000C =
5214 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5215 if (Op000C->getZExtValue() == 1) {
5216 LHS = Op0.getOperand(1);
5217 RHS = Op0.getOperand(0).getOperand(1);
5219 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5220 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5221 SDValue AndLHS = Op0.getOperand(0);
5222 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5223 LHS = AndLHS.getOperand(0);
5224 RHS = AndLHS.getOperand(1);
5228 if (LHS.getNode()) {
5229 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5230 // instruction. Since the shift amount is in-range-or-undefined, we know
5231 // that doing a bittest on the i16 value is ok. We extend to i32 because
5232 // the encoding for the i16 version is larger than the i32 version.
5233 if (LHS.getValueType() == MVT::i8)
5234 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5236 // If the operand types disagree, extend the shift amount to match. Since
5237 // BT ignores high bits (like shifts) we can use anyextend.
5238 if (LHS.getValueType() != RHS.getValueType())
5239 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5241 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5242 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5243 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5244 DAG.getConstant(Cond, MVT::i8), BT);
5248 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5249 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5251 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5252 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5253 DAG.getConstant(X86CC, MVT::i8), Cond);
5256 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5258 SDValue Op0 = Op.getOperand(0);
5259 SDValue Op1 = Op.getOperand(1);
5260 SDValue CC = Op.getOperand(2);
5261 MVT VT = Op.getValueType();
5262 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5263 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5264 DebugLoc dl = Op.getNode()->getDebugLoc();
5268 MVT VT0 = Op0.getValueType();
5269 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5270 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5273 switch (SetCCOpcode) {
5276 case ISD::SETEQ: SSECC = 0; break;
5278 case ISD::SETGT: Swap = true; // Fallthrough
5280 case ISD::SETOLT: SSECC = 1; break;
5282 case ISD::SETGE: Swap = true; // Fallthrough
5284 case ISD::SETOLE: SSECC = 2; break;
5285 case ISD::SETUO: SSECC = 3; break;
5287 case ISD::SETNE: SSECC = 4; break;
5288 case ISD::SETULE: Swap = true;
5289 case ISD::SETUGE: SSECC = 5; break;
5290 case ISD::SETULT: Swap = true;
5291 case ISD::SETUGT: SSECC = 6; break;
5292 case ISD::SETO: SSECC = 7; break;
5295 std::swap(Op0, Op1);
5297 // In the two special cases we can't handle, emit two comparisons.
5299 if (SetCCOpcode == ISD::SETUEQ) {
5301 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5302 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5303 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5305 else if (SetCCOpcode == ISD::SETONE) {
5307 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5308 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5309 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5311 assert(0 && "Illegal FP comparison");
5313 // Handle all other FP comparisons here.
5314 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5317 // We are handling one of the integer comparisons here. Since SSE only has
5318 // GT and EQ comparisons for integer, swapping operands and multiple
5319 // operations may be required for some comparisons.
5320 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5321 bool Swap = false, Invert = false, FlipSigns = false;
5323 switch (VT.getSimpleVT()) {
5325 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5326 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5327 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5328 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5331 switch (SetCCOpcode) {
5333 case ISD::SETNE: Invert = true;
5334 case ISD::SETEQ: Opc = EQOpc; break;
5335 case ISD::SETLT: Swap = true;
5336 case ISD::SETGT: Opc = GTOpc; break;
5337 case ISD::SETGE: Swap = true;
5338 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5339 case ISD::SETULT: Swap = true;
5340 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5341 case ISD::SETUGE: Swap = true;
5342 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5345 std::swap(Op0, Op1);
5347 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5348 // bits of the inputs before performing those operations.
5350 MVT EltVT = VT.getVectorElementType();
5351 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5353 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5354 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5356 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5357 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5360 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5362 // If the logical-not of the result is required, perform that now.
5364 Result = DAG.getNOT(dl, Result, VT);
5369 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5370 static bool isX86LogicalCmp(unsigned Opc) {
5371 return Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI;
5374 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5375 bool addTest = true;
5376 SDValue Cond = Op.getOperand(0);
5379 if (Cond.getOpcode() == ISD::SETCC)
5380 Cond = LowerSETCC(Cond, DAG);
5382 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5383 // setting operand in place of the X86ISD::SETCC.
5384 if (Cond.getOpcode() == X86ISD::SETCC) {
5385 CC = Cond.getOperand(0);
5387 SDValue Cmp = Cond.getOperand(1);
5388 unsigned Opc = Cmp.getOpcode();
5389 MVT VT = Op.getValueType();
5391 bool IllegalFPCMov = false;
5392 if (VT.isFloatingPoint() && !VT.isVector() &&
5393 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5394 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5396 if ((isX86LogicalCmp(Opc) && !IllegalFPCMov) || Opc == X86ISD::BT) { // FIXME
5403 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5404 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5407 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5409 SmallVector<SDValue, 4> Ops;
5410 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5411 // condition is true.
5412 Ops.push_back(Op.getOperand(2));
5413 Ops.push_back(Op.getOperand(1));
5415 Ops.push_back(Cond);
5416 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
5419 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5420 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5421 // from the AND / OR.
5422 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5423 Opc = Op.getOpcode();
5424 if (Opc != ISD::OR && Opc != ISD::AND)
5426 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5427 Op.getOperand(0).hasOneUse() &&
5428 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5429 Op.getOperand(1).hasOneUse());
5432 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5433 // 1 and that the SETCC node has a single use.
5434 static bool isXor1OfSetCC(SDValue Op) {
5435 if (Op.getOpcode() != ISD::XOR)
5437 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5438 if (N1C && N1C->getAPIntValue() == 1) {
5439 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5440 Op.getOperand(0).hasOneUse();
5445 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5446 bool addTest = true;
5447 SDValue Chain = Op.getOperand(0);
5448 SDValue Cond = Op.getOperand(1);
5449 SDValue Dest = Op.getOperand(2);
5452 if (Cond.getOpcode() == ISD::SETCC)
5453 Cond = LowerSETCC(Cond, DAG);
5455 // FIXME: LowerXALUO doesn't handle these!!
5456 else if (Cond.getOpcode() == X86ISD::ADD ||
5457 Cond.getOpcode() == X86ISD::SUB ||
5458 Cond.getOpcode() == X86ISD::SMUL ||
5459 Cond.getOpcode() == X86ISD::UMUL)
5460 Cond = LowerXALUO(Cond, DAG);
5463 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5464 // setting operand in place of the X86ISD::SETCC.
5465 if (Cond.getOpcode() == X86ISD::SETCC) {
5466 CC = Cond.getOperand(0);
5468 SDValue Cmp = Cond.getOperand(1);
5469 unsigned Opc = Cmp.getOpcode();
5470 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5471 if (isX86LogicalCmp(Opc) || Opc == X86ISD::BT) {
5475 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5479 // These can only come from an arithmetic instruction with overflow,
5480 // e.g. SADDO, UADDO.
5481 Cond = Cond.getNode()->getOperand(1);
5488 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5489 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5490 unsigned Opc = Cmp.getOpcode();
5491 if (CondOpc == ISD::OR) {
5492 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5493 // two branches instead of an explicit OR instruction with a
5495 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5496 isX86LogicalCmp(Opc)) {
5497 CC = Cond.getOperand(0).getOperand(0);
5498 Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5499 Chain, Dest, CC, Cmp);
5500 CC = Cond.getOperand(1).getOperand(0);
5504 } else { // ISD::AND
5505 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5506 // two branches instead of an explicit AND instruction with a
5507 // separate test. However, we only do this if this block doesn't
5508 // have a fall-through edge, because this requires an explicit
5509 // jmp when the condition is false.
5510 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5511 isX86LogicalCmp(Opc) &&
5512 Op.getNode()->hasOneUse()) {
5513 X86::CondCode CCode =
5514 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5515 CCode = X86::GetOppositeBranchCondition(CCode);
5516 CC = DAG.getConstant(CCode, MVT::i8);
5517 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5518 // Look for an unconditional branch following this conditional branch.
5519 // We need this because we need to reverse the successors in order
5520 // to implement FCMP_OEQ.
5521 if (User.getOpcode() == ISD::BR) {
5522 SDValue FalseBB = User.getOperand(1);
5524 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5525 assert(NewBR == User);
5528 Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5529 Chain, Dest, CC, Cmp);
5530 X86::CondCode CCode =
5531 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5532 CCode = X86::GetOppositeBranchCondition(CCode);
5533 CC = DAG.getConstant(CCode, MVT::i8);
5539 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5540 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5541 // It should be transformed during dag combiner except when the condition
5542 // is set by a arithmetics with overflow node.
5543 X86::CondCode CCode =
5544 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5545 CCode = X86::GetOppositeBranchCondition(CCode);
5546 CC = DAG.getConstant(CCode, MVT::i8);
5547 Cond = Cond.getOperand(0).getOperand(1);
5553 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5554 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5556 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5557 Chain, Dest, CC, Cond);
5561 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5562 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5563 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5564 // that the guard pages used by the OS virtual memory manager are allocated in
5565 // correct sequence.
5567 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5568 SelectionDAG &DAG) {
5569 assert(Subtarget->isTargetCygMing() &&
5570 "This should be used only on Cygwin/Mingw targets");
5573 SDValue Chain = Op.getOperand(0);
5574 SDValue Size = Op.getOperand(1);
5575 // FIXME: Ensure alignment here
5579 MVT IntPtr = getPointerTy();
5580 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5582 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5584 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
5585 Flag = Chain.getValue(1);
5587 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5588 SDValue Ops[] = { Chain,
5589 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5590 DAG.getRegister(X86::EAX, IntPtr),
5591 DAG.getRegister(X86StackPtr, SPTy),
5593 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
5594 Flag = Chain.getValue(1);
5596 Chain = DAG.getCALLSEQ_END(Chain,
5597 DAG.getIntPtrConstant(0, true),
5598 DAG.getIntPtrConstant(0, true),
5601 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5603 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5604 return DAG.getMergeValues(Ops1, 2);
5608 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5610 SDValue Dst, SDValue Src,
5611 SDValue Size, unsigned Align,
5613 uint64_t DstSVOff) {
5614 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5616 // If not DWORD aligned or size is more than the threshold, call the library.
5617 // The libc version is likely to be faster for these cases. It can use the
5618 // address value and run time information about the CPU.
5619 if ((Align & 3) != 0 ||
5621 ConstantSize->getZExtValue() >
5622 getSubtarget()->getMaxInlineSizeThreshold()) {
5623 SDValue InFlag(0, 0);
5625 // Check to see if there is a specialized entry-point for memory zeroing.
5626 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5628 if (const char *bzeroEntry = V &&
5629 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5630 MVT IntPtr = getPointerTy();
5631 const Type *IntPtrTy = TD->getIntPtrType();
5632 TargetLowering::ArgListTy Args;
5633 TargetLowering::ArgListEntry Entry;
5635 Entry.Ty = IntPtrTy;
5636 Args.push_back(Entry);
5638 Args.push_back(Entry);
5639 // FIXME provide DebugLoc info
5640 std::pair<SDValue,SDValue> CallResult =
5641 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5642 CallingConv::C, false,
5643 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG,
5644 DebugLoc::getUnknownLoc());
5645 return CallResult.second;
5648 // Otherwise have the target-independent code call memset.
5652 uint64_t SizeVal = ConstantSize->getZExtValue();
5653 SDValue InFlag(0, 0);
5656 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5657 unsigned BytesLeft = 0;
5658 bool TwoRepStos = false;
5661 uint64_t Val = ValC->getZExtValue() & 255;
5663 // If the value is a constant, then we can potentially use larger sets.
5664 switch (Align & 3) {
5665 case 2: // WORD aligned
5668 Val = (Val << 8) | Val;
5670 case 0: // DWORD aligned
5673 Val = (Val << 8) | Val;
5674 Val = (Val << 16) | Val;
5675 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5678 Val = (Val << 32) | Val;
5681 default: // Byte aligned
5684 Count = DAG.getIntPtrConstant(SizeVal);
5688 if (AVT.bitsGT(MVT::i8)) {
5689 unsigned UBytes = AVT.getSizeInBits() / 8;
5690 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5691 BytesLeft = SizeVal % UBytes;
5694 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5696 InFlag = Chain.getValue(1);
5699 Count = DAG.getIntPtrConstant(SizeVal);
5700 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5701 InFlag = Chain.getValue(1);
5704 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5706 InFlag = Chain.getValue(1);
5707 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5709 InFlag = Chain.getValue(1);
5711 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5712 SmallVector<SDValue, 8> Ops;
5713 Ops.push_back(Chain);
5714 Ops.push_back(DAG.getValueType(AVT));
5715 Ops.push_back(InFlag);
5716 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5719 InFlag = Chain.getValue(1);
5721 MVT CVT = Count.getValueType();
5722 SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5723 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5724 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5726 InFlag = Chain.getValue(1);
5727 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5729 Ops.push_back(Chain);
5730 Ops.push_back(DAG.getValueType(MVT::i8));
5731 Ops.push_back(InFlag);
5732 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5733 } else if (BytesLeft) {
5734 // Handle the last 1 - 7 bytes.
5735 unsigned Offset = SizeVal - BytesLeft;
5736 MVT AddrVT = Dst.getValueType();
5737 MVT SizeVT = Size.getValueType();
5739 Chain = DAG.getMemset(Chain,
5740 DAG.getNode(ISD::ADD, AddrVT, Dst,
5741 DAG.getConstant(Offset, AddrVT)),
5743 DAG.getConstant(BytesLeft, SizeVT),
5744 Align, DstSV, DstSVOff + Offset);
5747 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5752 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5753 SDValue Chain, SDValue Dst, SDValue Src,
5754 SDValue Size, unsigned Align,
5756 const Value *DstSV, uint64_t DstSVOff,
5757 const Value *SrcSV, uint64_t SrcSVOff) {
5758 // This requires the copy size to be a constant, preferrably
5759 // within a subtarget-specific limit.
5760 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5763 uint64_t SizeVal = ConstantSize->getZExtValue();
5764 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5767 /// If not DWORD aligned, call the library.
5768 if ((Align & 3) != 0)
5773 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5776 unsigned UBytes = AVT.getSizeInBits() / 8;
5777 unsigned CountVal = SizeVal / UBytes;
5778 SDValue Count = DAG.getIntPtrConstant(CountVal);
5779 unsigned BytesLeft = SizeVal % UBytes;
5781 SDValue InFlag(0, 0);
5782 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5784 InFlag = Chain.getValue(1);
5785 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5787 InFlag = Chain.getValue(1);
5788 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5790 InFlag = Chain.getValue(1);
5792 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5793 SmallVector<SDValue, 8> Ops;
5794 Ops.push_back(Chain);
5795 Ops.push_back(DAG.getValueType(AVT));
5796 Ops.push_back(InFlag);
5797 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5799 SmallVector<SDValue, 4> Results;
5800 Results.push_back(RepMovs);
5802 // Handle the last 1 - 7 bytes.
5803 unsigned Offset = SizeVal - BytesLeft;
5804 MVT DstVT = Dst.getValueType();
5805 MVT SrcVT = Src.getValueType();
5806 MVT SizeVT = Size.getValueType();
5807 Results.push_back(DAG.getMemcpy(Chain,
5808 DAG.getNode(ISD::ADD, DstVT, Dst,
5809 DAG.getConstant(Offset, DstVT)),
5810 DAG.getNode(ISD::ADD, SrcVT, Src,
5811 DAG.getConstant(Offset, SrcVT)),
5812 DAG.getConstant(BytesLeft, SizeVT),
5813 Align, AlwaysInline,
5814 DstSV, DstSVOff + Offset,
5815 SrcSV, SrcSVOff + Offset));
5818 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5821 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5822 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5824 if (!Subtarget->is64Bit()) {
5825 // vastart just stores the address of the VarArgsFrameIndex slot into the
5826 // memory location argument.
5827 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5828 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5832 // gp_offset (0 - 6 * 8)
5833 // fp_offset (48 - 48 + 8 * 16)
5834 // overflow_arg_area (point to parameters coming in memory).
5836 SmallVector<SDValue, 8> MemOps;
5837 SDValue FIN = Op.getOperand(1);
5839 SDValue Store = DAG.getStore(Op.getOperand(0),
5840 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5842 MemOps.push_back(Store);
5845 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5846 Store = DAG.getStore(Op.getOperand(0),
5847 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5849 MemOps.push_back(Store);
5851 // Store ptr to overflow_arg_area
5852 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5853 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5854 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5855 MemOps.push_back(Store);
5857 // Store ptr to reg_save_area.
5858 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5859 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5860 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5861 MemOps.push_back(Store);
5862 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5865 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5866 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5867 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5868 SDValue Chain = Op.getOperand(0);
5869 SDValue SrcPtr = Op.getOperand(1);
5870 SDValue SrcSV = Op.getOperand(2);
5872 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5877 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5878 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5879 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5880 SDValue Chain = Op.getOperand(0);
5881 SDValue DstPtr = Op.getOperand(1);
5882 SDValue SrcPtr = Op.getOperand(2);
5883 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5884 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5886 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5887 DAG.getIntPtrConstant(24), 8, false,
5888 DstSV, 0, SrcSV, 0);
5892 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5893 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5895 default: return SDValue(); // Don't custom lower most intrinsics.
5896 // Comparison intrinsics.
5897 case Intrinsic::x86_sse_comieq_ss:
5898 case Intrinsic::x86_sse_comilt_ss:
5899 case Intrinsic::x86_sse_comile_ss:
5900 case Intrinsic::x86_sse_comigt_ss:
5901 case Intrinsic::x86_sse_comige_ss:
5902 case Intrinsic::x86_sse_comineq_ss:
5903 case Intrinsic::x86_sse_ucomieq_ss:
5904 case Intrinsic::x86_sse_ucomilt_ss:
5905 case Intrinsic::x86_sse_ucomile_ss:
5906 case Intrinsic::x86_sse_ucomigt_ss:
5907 case Intrinsic::x86_sse_ucomige_ss:
5908 case Intrinsic::x86_sse_ucomineq_ss:
5909 case Intrinsic::x86_sse2_comieq_sd:
5910 case Intrinsic::x86_sse2_comilt_sd:
5911 case Intrinsic::x86_sse2_comile_sd:
5912 case Intrinsic::x86_sse2_comigt_sd:
5913 case Intrinsic::x86_sse2_comige_sd:
5914 case Intrinsic::x86_sse2_comineq_sd:
5915 case Intrinsic::x86_sse2_ucomieq_sd:
5916 case Intrinsic::x86_sse2_ucomilt_sd:
5917 case Intrinsic::x86_sse2_ucomile_sd:
5918 case Intrinsic::x86_sse2_ucomigt_sd:
5919 case Intrinsic::x86_sse2_ucomige_sd:
5920 case Intrinsic::x86_sse2_ucomineq_sd: {
5922 ISD::CondCode CC = ISD::SETCC_INVALID;
5925 case Intrinsic::x86_sse_comieq_ss:
5926 case Intrinsic::x86_sse2_comieq_sd:
5930 case Intrinsic::x86_sse_comilt_ss:
5931 case Intrinsic::x86_sse2_comilt_sd:
5935 case Intrinsic::x86_sse_comile_ss:
5936 case Intrinsic::x86_sse2_comile_sd:
5940 case Intrinsic::x86_sse_comigt_ss:
5941 case Intrinsic::x86_sse2_comigt_sd:
5945 case Intrinsic::x86_sse_comige_ss:
5946 case Intrinsic::x86_sse2_comige_sd:
5950 case Intrinsic::x86_sse_comineq_ss:
5951 case Intrinsic::x86_sse2_comineq_sd:
5955 case Intrinsic::x86_sse_ucomieq_ss:
5956 case Intrinsic::x86_sse2_ucomieq_sd:
5957 Opc = X86ISD::UCOMI;
5960 case Intrinsic::x86_sse_ucomilt_ss:
5961 case Intrinsic::x86_sse2_ucomilt_sd:
5962 Opc = X86ISD::UCOMI;
5965 case Intrinsic::x86_sse_ucomile_ss:
5966 case Intrinsic::x86_sse2_ucomile_sd:
5967 Opc = X86ISD::UCOMI;
5970 case Intrinsic::x86_sse_ucomigt_ss:
5971 case Intrinsic::x86_sse2_ucomigt_sd:
5972 Opc = X86ISD::UCOMI;
5975 case Intrinsic::x86_sse_ucomige_ss:
5976 case Intrinsic::x86_sse2_ucomige_sd:
5977 Opc = X86ISD::UCOMI;
5980 case Intrinsic::x86_sse_ucomineq_ss:
5981 case Intrinsic::x86_sse2_ucomineq_sd:
5982 Opc = X86ISD::UCOMI;
5987 SDValue LHS = Op.getOperand(1);
5988 SDValue RHS = Op.getOperand(2);
5989 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
5990 SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5991 SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5992 DAG.getConstant(X86CC, MVT::i8), Cond);
5993 return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
5996 // Fix vector shift instructions where the last operand is a non-immediate
5998 case Intrinsic::x86_sse2_pslli_w:
5999 case Intrinsic::x86_sse2_pslli_d:
6000 case Intrinsic::x86_sse2_pslli_q:
6001 case Intrinsic::x86_sse2_psrli_w:
6002 case Intrinsic::x86_sse2_psrli_d:
6003 case Intrinsic::x86_sse2_psrli_q:
6004 case Intrinsic::x86_sse2_psrai_w:
6005 case Intrinsic::x86_sse2_psrai_d:
6006 case Intrinsic::x86_mmx_pslli_w:
6007 case Intrinsic::x86_mmx_pslli_d:
6008 case Intrinsic::x86_mmx_pslli_q:
6009 case Intrinsic::x86_mmx_psrli_w:
6010 case Intrinsic::x86_mmx_psrli_d:
6011 case Intrinsic::x86_mmx_psrli_q:
6012 case Intrinsic::x86_mmx_psrai_w:
6013 case Intrinsic::x86_mmx_psrai_d: {
6014 SDValue ShAmt = Op.getOperand(2);
6015 if (isa<ConstantSDNode>(ShAmt))
6018 unsigned NewIntNo = 0;
6019 MVT ShAmtVT = MVT::v4i32;
6021 case Intrinsic::x86_sse2_pslli_w:
6022 NewIntNo = Intrinsic::x86_sse2_psll_w;
6024 case Intrinsic::x86_sse2_pslli_d:
6025 NewIntNo = Intrinsic::x86_sse2_psll_d;
6027 case Intrinsic::x86_sse2_pslli_q:
6028 NewIntNo = Intrinsic::x86_sse2_psll_q;
6030 case Intrinsic::x86_sse2_psrli_w:
6031 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6033 case Intrinsic::x86_sse2_psrli_d:
6034 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6036 case Intrinsic::x86_sse2_psrli_q:
6037 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6039 case Intrinsic::x86_sse2_psrai_w:
6040 NewIntNo = Intrinsic::x86_sse2_psra_w;
6042 case Intrinsic::x86_sse2_psrai_d:
6043 NewIntNo = Intrinsic::x86_sse2_psra_d;
6046 ShAmtVT = MVT::v2i32;
6048 case Intrinsic::x86_mmx_pslli_w:
6049 NewIntNo = Intrinsic::x86_mmx_psll_w;
6051 case Intrinsic::x86_mmx_pslli_d:
6052 NewIntNo = Intrinsic::x86_mmx_psll_d;
6054 case Intrinsic::x86_mmx_pslli_q:
6055 NewIntNo = Intrinsic::x86_mmx_psll_q;
6057 case Intrinsic::x86_mmx_psrli_w:
6058 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6060 case Intrinsic::x86_mmx_psrli_d:
6061 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6063 case Intrinsic::x86_mmx_psrli_q:
6064 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6066 case Intrinsic::x86_mmx_psrai_w:
6067 NewIntNo = Intrinsic::x86_mmx_psra_w;
6069 case Intrinsic::x86_mmx_psrai_d:
6070 NewIntNo = Intrinsic::x86_mmx_psra_d;
6072 default: abort(); // Can't reach here.
6077 MVT VT = Op.getValueType();
6078 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
6079 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
6080 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6081 DAG.getConstant(NewIntNo, MVT::i32),
6082 Op.getOperand(1), ShAmt);
6087 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6088 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6091 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6093 DAG.getConstant(TD->getPointerSize(),
6094 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6095 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(),
6096 DAG.getNode(ISD::ADD, getPointerTy(), FrameAddr, Offset),
6100 // Just load the return address.
6101 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6102 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
6105 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6106 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6107 MFI->setFrameAddressIsTaken(true);
6108 MVT VT = Op.getValueType();
6109 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6110 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6111 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), FrameReg, VT);
6113 FrameAddr = DAG.getLoad(VT, DAG.getEntryNode(), FrameAddr, NULL, 0);
6117 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6118 SelectionDAG &DAG) {
6119 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6122 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6124 MachineFunction &MF = DAG.getMachineFunction();
6125 SDValue Chain = Op.getOperand(0);
6126 SDValue Offset = Op.getOperand(1);
6127 SDValue Handler = Op.getOperand(2);
6129 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6131 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6133 SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
6134 DAG.getIntPtrConstant(-TD->getPointerSize()));
6135 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
6136 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
6137 Chain = DAG.getCopyToReg(Chain, StoreAddrReg, StoreAddr);
6138 MF.getRegInfo().addLiveOut(StoreAddrReg);
6140 return DAG.getNode(X86ISD::EH_RETURN,
6142 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6145 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6146 SelectionDAG &DAG) {
6147 SDValue Root = Op.getOperand(0);
6148 SDValue Trmp = Op.getOperand(1); // trampoline
6149 SDValue FPtr = Op.getOperand(2); // nested function
6150 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6152 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6154 const X86InstrInfo *TII =
6155 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6157 if (Subtarget->is64Bit()) {
6158 SDValue OutChains[6];
6160 // Large code-model.
6162 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6163 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6165 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6166 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6168 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6170 // Load the pointer to the nested function into R11.
6171 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6172 SDValue Addr = Trmp;
6173 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
6176 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
6177 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
6179 // Load the 'nest' parameter value into R10.
6180 // R10 is specified in X86CallingConv.td
6181 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6182 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
6183 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
6186 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
6187 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
6189 // Jump to the nested function.
6190 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6191 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
6192 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
6195 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6196 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
6197 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
6201 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
6202 return DAG.getMergeValues(Ops, 2);
6204 const Function *Func =
6205 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6206 unsigned CC = Func->getCallingConv();
6211 assert(0 && "Unsupported calling convention");
6212 case CallingConv::C:
6213 case CallingConv::X86_StdCall: {
6214 // Pass 'nest' parameter in ECX.
6215 // Must be kept in sync with X86CallingConv.td
6218 // Check that ECX wasn't needed by an 'inreg' parameter.
6219 const FunctionType *FTy = Func->getFunctionType();
6220 const AttrListPtr &Attrs = Func->getAttributes();
6222 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6223 unsigned InRegCount = 0;
6226 for (FunctionType::param_iterator I = FTy->param_begin(),
6227 E = FTy->param_end(); I != E; ++I, ++Idx)
6228 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6229 // FIXME: should only count parameters that are lowered to integers.
6230 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6232 if (InRegCount > 2) {
6233 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6239 case CallingConv::X86_FastCall:
6240 case CallingConv::Fast:
6241 // Pass 'nest' parameter in EAX.
6242 // Must be kept in sync with X86CallingConv.td
6247 SDValue OutChains[4];
6250 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
6251 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
6253 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6254 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6255 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6258 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
6259 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
6261 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6262 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
6263 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
6264 TrmpAddr, 5, false, 1);
6266 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
6267 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
6270 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
6271 return DAG.getMergeValues(Ops, 2);
6275 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6277 The rounding mode is in bits 11:10 of FPSR, and has the following
6284 FLT_ROUNDS, on the other hand, expects the following:
6291 To perform the conversion, we do:
6292 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6295 MachineFunction &MF = DAG.getMachineFunction();
6296 const TargetMachine &TM = MF.getTarget();
6297 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6298 unsigned StackAlignment = TFI.getStackAlignment();
6299 MVT VT = Op.getValueType();
6301 // Save FP Control Word to stack slot
6302 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6303 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6305 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
6306 DAG.getEntryNode(), StackSlot);
6308 // Load FP Control Word from stack slot
6309 SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
6311 // Transform as necessary
6313 DAG.getNode(ISD::SRL, MVT::i16,
6314 DAG.getNode(ISD::AND, MVT::i16,
6315 CWD, DAG.getConstant(0x800, MVT::i16)),
6316 DAG.getConstant(11, MVT::i8));
6318 DAG.getNode(ISD::SRL, MVT::i16,
6319 DAG.getNode(ISD::AND, MVT::i16,
6320 CWD, DAG.getConstant(0x400, MVT::i16)),
6321 DAG.getConstant(9, MVT::i8));
6324 DAG.getNode(ISD::AND, MVT::i16,
6325 DAG.getNode(ISD::ADD, MVT::i16,
6326 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
6327 DAG.getConstant(1, MVT::i16)),
6328 DAG.getConstant(3, MVT::i16));
6331 return DAG.getNode((VT.getSizeInBits() < 16 ?
6332 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
6335 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6336 MVT VT = Op.getValueType();
6338 unsigned NumBits = VT.getSizeInBits();
6340 Op = Op.getOperand(0);
6341 if (VT == MVT::i8) {
6342 // Zero extend to i32 since there is not an i8 bsr.
6344 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6347 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6348 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6349 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
6351 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6352 SmallVector<SDValue, 4> Ops;
6354 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6355 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6356 Ops.push_back(Op.getValue(1));
6357 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6359 // Finally xor with NumBits-1.
6360 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6363 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6367 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6368 MVT VT = Op.getValueType();
6370 unsigned NumBits = VT.getSizeInBits();
6372 Op = Op.getOperand(0);
6373 if (VT == MVT::i8) {
6375 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6378 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6379 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6380 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
6382 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6383 SmallVector<SDValue, 4> Ops;
6385 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6386 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6387 Ops.push_back(Op.getValue(1));
6388 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6391 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6395 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6396 MVT VT = Op.getValueType();
6397 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6399 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6400 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6401 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6402 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6403 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6405 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6406 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6407 // return AloBlo + AloBhi + AhiBlo;
6409 SDValue A = Op.getOperand(0);
6410 SDValue B = Op.getOperand(1);
6412 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6413 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6414 A, DAG.getConstant(32, MVT::i32));
6415 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6416 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6417 B, DAG.getConstant(32, MVT::i32));
6418 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6419 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6421 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6422 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6424 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6425 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6427 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6428 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6429 AloBhi, DAG.getConstant(32, MVT::i32));
6430 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6431 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6432 AhiBlo, DAG.getConstant(32, MVT::i32));
6433 SDValue Res = DAG.getNode(ISD::ADD, VT, AloBlo, AloBhi);
6434 Res = DAG.getNode(ISD::ADD, VT, Res, AhiBlo);
6439 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6440 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6441 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6442 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6443 // has only one use.
6444 SDNode *N = Op.getNode();
6445 SDValue LHS = N->getOperand(0);
6446 SDValue RHS = N->getOperand(1);
6447 unsigned BaseOp = 0;
6450 switch (Op.getOpcode()) {
6451 default: assert(0 && "Unknown ovf instruction!");
6453 BaseOp = X86ISD::ADD;
6457 BaseOp = X86ISD::ADD;
6461 BaseOp = X86ISD::SUB;
6465 BaseOp = X86ISD::SUB;
6469 BaseOp = X86ISD::SMUL;
6473 BaseOp = X86ISD::UMUL;
6478 // Also sets EFLAGS.
6479 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6480 SDValue Sum = DAG.getNode(BaseOp, VTs, LHS, RHS);
6483 DAG.getNode(X86ISD::SETCC, N->getValueType(1),
6484 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6486 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6490 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6491 MVT T = Op.getValueType();
6494 switch(T.getSimpleVT()) {
6496 assert(false && "Invalid value type!");
6497 case MVT::i8: Reg = X86::AL; size = 1; break;
6498 case MVT::i16: Reg = X86::AX; size = 2; break;
6499 case MVT::i32: Reg = X86::EAX; size = 4; break;
6501 assert(Subtarget->is64Bit() && "Node not type legal!");
6502 Reg = X86::RAX; size = 8;
6505 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
6506 Op.getOperand(2), SDValue());
6507 SDValue Ops[] = { cpIn.getValue(0),
6510 DAG.getTargetConstant(size, MVT::i8),
6512 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6513 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
6515 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
6519 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6520 SelectionDAG &DAG) {
6521 assert(Subtarget->is64Bit() && "Result not type legalized?");
6522 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6523 SDValue TheChain = Op.getOperand(0);
6524 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
6525 SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
6526 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX, MVT::i64,
6528 SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
6529 DAG.getConstant(32, MVT::i8));
6531 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp),
6534 return DAG.getMergeValues(Ops, 2);
6537 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6538 SDNode *Node = Op.getNode();
6539 MVT T = Node->getValueType(0);
6540 SDValue negOp = DAG.getNode(ISD::SUB, T,
6541 DAG.getConstant(0, T), Node->getOperand(2));
6542 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD,
6543 cast<AtomicSDNode>(Node)->getMemoryVT(),
6544 Node->getOperand(0),
6545 Node->getOperand(1), negOp,
6546 cast<AtomicSDNode>(Node)->getSrcValue(),
6547 cast<AtomicSDNode>(Node)->getAlignment());
6550 /// LowerOperation - Provide custom lowering hooks for some operations.
6552 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6553 switch (Op.getOpcode()) {
6554 default: assert(0 && "Should not custom lower this!");
6555 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6556 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6557 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6558 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6559 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6560 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6561 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6562 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6563 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6564 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6565 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6566 case ISD::SHL_PARTS:
6567 case ISD::SRA_PARTS:
6568 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6569 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6570 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6571 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6572 case ISD::FABS: return LowerFABS(Op, DAG);
6573 case ISD::FNEG: return LowerFNEG(Op, DAG);
6574 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6575 case ISD::SETCC: return LowerSETCC(Op, DAG);
6576 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6577 case ISD::SELECT: return LowerSELECT(Op, DAG);
6578 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6579 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6580 case ISD::CALL: return LowerCALL(Op, DAG);
6581 case ISD::RET: return LowerRET(Op, DAG);
6582 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6583 case ISD::VASTART: return LowerVASTART(Op, DAG);
6584 case ISD::VAARG: return LowerVAARG(Op, DAG);
6585 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6586 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6587 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6588 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6589 case ISD::FRAME_TO_ARGS_OFFSET:
6590 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6591 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6592 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6593 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6594 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6595 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6596 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6597 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6603 case ISD::UMULO: return LowerXALUO(Op, DAG);
6604 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6608 void X86TargetLowering::
6609 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6610 SelectionDAG &DAG, unsigned NewOp) {
6611 MVT T = Node->getValueType(0);
6612 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6614 SDValue Chain = Node->getOperand(0);
6615 SDValue In1 = Node->getOperand(1);
6616 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6617 Node->getOperand(2), DAG.getIntPtrConstant(0));
6618 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6619 Node->getOperand(2), DAG.getIntPtrConstant(1));
6620 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6621 // have a MemOperand. Pass the info through as a normal operand.
6622 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6623 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6624 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6625 SDValue Result = DAG.getNode(NewOp, Tys, Ops, 5);
6626 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6627 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2));
6628 Results.push_back(Result.getValue(2));
6631 /// ReplaceNodeResults - Replace a node with an illegal result type
6632 /// with a new node built out of custom code.
6633 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6634 SmallVectorImpl<SDValue>&Results,
6635 SelectionDAG &DAG) {
6636 switch (N->getOpcode()) {
6638 assert(false && "Do not know how to custom type legalize this operation!");
6640 case ISD::FP_TO_SINT: {
6641 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
6642 SDValue FIST = Vals.first, StackSlot = Vals.second;
6643 if (FIST.getNode() != 0) {
6644 MVT VT = N->getValueType(0);
6645 // Return a load from the stack slot.
6646 Results.push_back(DAG.getLoad(VT, FIST, StackSlot, NULL, 0));
6650 case ISD::READCYCLECOUNTER: {
6651 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6652 SDValue TheChain = N->getOperand(0);
6653 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
6654 SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
6655 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX, MVT::i32,
6657 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6658 SDValue Ops[] = { eax, edx };
6659 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2));
6660 Results.push_back(edx.getValue(1));
6663 case ISD::ATOMIC_CMP_SWAP: {
6664 MVT T = N->getValueType(0);
6665 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6666 SDValue cpInL, cpInH;
6667 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(2),
6668 DAG.getConstant(0, MVT::i32));
6669 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(2),
6670 DAG.getConstant(1, MVT::i32));
6671 cpInL = DAG.getCopyToReg(N->getOperand(0), X86::EAX, cpInL, SDValue());
6672 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX, cpInH,
6674 SDValue swapInL, swapInH;
6675 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(3),
6676 DAG.getConstant(0, MVT::i32));
6677 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(3),
6678 DAG.getConstant(1, MVT::i32));
6679 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX, swapInL,
6681 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX, swapInH,
6682 swapInL.getValue(1));
6683 SDValue Ops[] = { swapInH.getValue(0),
6685 swapInH.getValue(1) };
6686 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6687 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
6688 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
6689 Result.getValue(1));
6690 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
6691 cpOutL.getValue(2));
6692 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6693 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2));
6694 Results.push_back(cpOutH.getValue(1));
6697 case ISD::ATOMIC_LOAD_ADD:
6698 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6700 case ISD::ATOMIC_LOAD_AND:
6701 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6703 case ISD::ATOMIC_LOAD_NAND:
6704 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6706 case ISD::ATOMIC_LOAD_OR:
6707 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6709 case ISD::ATOMIC_LOAD_SUB:
6710 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6712 case ISD::ATOMIC_LOAD_XOR:
6713 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6715 case ISD::ATOMIC_SWAP:
6716 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6721 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6723 default: return NULL;
6724 case X86ISD::BSF: return "X86ISD::BSF";
6725 case X86ISD::BSR: return "X86ISD::BSR";
6726 case X86ISD::SHLD: return "X86ISD::SHLD";
6727 case X86ISD::SHRD: return "X86ISD::SHRD";
6728 case X86ISD::FAND: return "X86ISD::FAND";
6729 case X86ISD::FOR: return "X86ISD::FOR";
6730 case X86ISD::FXOR: return "X86ISD::FXOR";
6731 case X86ISD::FSRL: return "X86ISD::FSRL";
6732 case X86ISD::FILD: return "X86ISD::FILD";
6733 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6734 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6735 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6736 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6737 case X86ISD::FLD: return "X86ISD::FLD";
6738 case X86ISD::FST: return "X86ISD::FST";
6739 case X86ISD::CALL: return "X86ISD::CALL";
6740 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6741 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6742 case X86ISD::BT: return "X86ISD::BT";
6743 case X86ISD::CMP: return "X86ISD::CMP";
6744 case X86ISD::COMI: return "X86ISD::COMI";
6745 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6746 case X86ISD::SETCC: return "X86ISD::SETCC";
6747 case X86ISD::CMOV: return "X86ISD::CMOV";
6748 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6749 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6750 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6751 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6752 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6753 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6754 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6755 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6756 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6757 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6758 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6759 case X86ISD::FMAX: return "X86ISD::FMAX";
6760 case X86ISD::FMIN: return "X86ISD::FMIN";
6761 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6762 case X86ISD::FRCP: return "X86ISD::FRCP";
6763 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6764 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6765 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6766 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6767 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6768 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6769 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6770 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6771 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6772 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6773 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6774 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6775 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6776 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6777 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6778 case X86ISD::VSHL: return "X86ISD::VSHL";
6779 case X86ISD::VSRL: return "X86ISD::VSRL";
6780 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6781 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6782 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6783 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6784 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6785 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6786 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6787 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6788 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6789 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6790 case X86ISD::ADD: return "X86ISD::ADD";
6791 case X86ISD::SUB: return "X86ISD::SUB";
6792 case X86ISD::SMUL: return "X86ISD::SMUL";
6793 case X86ISD::UMUL: return "X86ISD::UMUL";
6797 // isLegalAddressingMode - Return true if the addressing mode represented
6798 // by AM is legal for this target, for a load/store of the specified type.
6799 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6800 const Type *Ty) const {
6801 // X86 supports extremely general addressing modes.
6803 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6804 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6808 // We can only fold this if we don't need an extra load.
6809 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6811 // If BaseGV requires a register, we cannot also have a BaseReg.
6812 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6816 // X86-64 only supports addr of globals in small code model.
6817 if (Subtarget->is64Bit()) {
6818 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6820 // If lower 4G is not available, then we must use rip-relative addressing.
6821 if (AM.BaseOffs || AM.Scale > 1)
6832 // These scales always work.
6837 // These scales are formed with basereg+scalereg. Only accept if there is
6842 default: // Other stuff never works.
6850 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6851 if (!Ty1->isInteger() || !Ty2->isInteger())
6853 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6854 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6855 if (NumBits1 <= NumBits2)
6857 return Subtarget->is64Bit() || NumBits1 < 64;
6860 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6861 if (!VT1.isInteger() || !VT2.isInteger())
6863 unsigned NumBits1 = VT1.getSizeInBits();
6864 unsigned NumBits2 = VT2.getSizeInBits();
6865 if (NumBits1 <= NumBits2)
6867 return Subtarget->is64Bit() || NumBits1 < 64;
6870 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6871 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6872 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6873 /// are assumed to be legal.
6875 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6876 // Only do shuffles on 128-bit vector types for now.
6877 if (VT.getSizeInBits() == 64) return false;
6878 return (Mask.getNode()->getNumOperands() <= 4 ||
6879 isIdentityMask(Mask.getNode()) ||
6880 isIdentityMask(Mask.getNode(), true) ||
6881 isSplatMask(Mask.getNode()) ||
6882 isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6883 X86::isUNPCKLMask(Mask.getNode()) ||
6884 X86::isUNPCKHMask(Mask.getNode()) ||
6885 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6886 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6890 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6891 MVT EVT, SelectionDAG &DAG) const {
6892 unsigned NumElts = BVOps.size();
6893 // Only do shuffles on 128-bit vector types for now.
6894 if (EVT.getSizeInBits() * NumElts == 64) return false;
6895 if (NumElts == 2) return true;
6897 return (isMOVLMask(&BVOps[0], 4) ||
6898 isCommutedMOVL(&BVOps[0], 4, true) ||
6899 isSHUFPMask(&BVOps[0], 4) ||
6900 isCommutedSHUFP(&BVOps[0], 4));
6905 //===----------------------------------------------------------------------===//
6906 // X86 Scheduler Hooks
6907 //===----------------------------------------------------------------------===//
6909 // private utility function
6911 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6912 MachineBasicBlock *MBB,
6920 TargetRegisterClass *RC,
6922 // For the atomic bitwise operator, we generate
6925 // ld t1 = [bitinstr.addr]
6926 // op t2 = t1, [bitinstr.val]
6928 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6930 // fallthrough -->nextMBB
6931 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6932 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6933 MachineFunction::iterator MBBIter = MBB;
6936 /// First build the CFG
6937 MachineFunction *F = MBB->getParent();
6938 MachineBasicBlock *thisMBB = MBB;
6939 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6940 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6941 F->insert(MBBIter, newMBB);
6942 F->insert(MBBIter, nextMBB);
6944 // Move all successors to thisMBB to nextMBB
6945 nextMBB->transferSuccessors(thisMBB);
6947 // Update thisMBB to fall through to newMBB
6948 thisMBB->addSuccessor(newMBB);
6950 // newMBB jumps to itself and fall through to nextMBB
6951 newMBB->addSuccessor(nextMBB);
6952 newMBB->addSuccessor(newMBB);
6954 // Insert instructions into newMBB based on incoming instruction
6955 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6956 MachineOperand& destOper = bInstr->getOperand(0);
6957 MachineOperand* argOpers[6];
6958 int numArgs = bInstr->getNumOperands() - 1;
6959 for (int i=0; i < numArgs; ++i)
6960 argOpers[i] = &bInstr->getOperand(i+1);
6962 // x86 address has 4 operands: base, index, scale, and displacement
6963 int lastAddrIndx = 3; // [0,3]
6966 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6967 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
6968 for (int i=0; i <= lastAddrIndx; ++i)
6969 (*MIB).addOperand(*argOpers[i]);
6971 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6973 MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
6978 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6979 assert((argOpers[valArgIndx]->isReg() ||
6980 argOpers[valArgIndx]->isImm()) &&
6982 if (argOpers[valArgIndx]->isReg())
6983 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6985 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6987 (*MIB).addOperand(*argOpers[valArgIndx]);
6989 MIB = BuildMI(newMBB, TII->get(copyOpc), EAXreg);
6992 MIB = BuildMI(newMBB, TII->get(CXchgOpc));
6993 for (int i=0; i <= lastAddrIndx; ++i)
6994 (*MIB).addOperand(*argOpers[i]);
6996 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6997 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6999 MIB = BuildMI(newMBB, TII->get(copyOpc), destOper.getReg());
7003 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
7005 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7009 // private utility function: 64 bit atomics on 32 bit host.
7011 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7012 MachineBasicBlock *MBB,
7018 // For the atomic bitwise operator, we generate
7019 // thisMBB (instructions are in pairs, except cmpxchg8b)
7020 // ld t1,t2 = [bitinstr.addr]
7022 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7023 // op t5, t6 <- out1, out2, [bitinstr.val]
7024 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7025 // mov ECX, EBX <- t5, t6
7026 // mov EAX, EDX <- t1, t2
7027 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7028 // mov t3, t4 <- EAX, EDX
7030 // result in out1, out2
7031 // fallthrough -->nextMBB
7033 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7034 const unsigned LoadOpc = X86::MOV32rm;
7035 const unsigned copyOpc = X86::MOV32rr;
7036 const unsigned NotOpc = X86::NOT32r;
7037 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7038 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7039 MachineFunction::iterator MBBIter = MBB;
7042 /// First build the CFG
7043 MachineFunction *F = MBB->getParent();
7044 MachineBasicBlock *thisMBB = MBB;
7045 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7046 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7047 F->insert(MBBIter, newMBB);
7048 F->insert(MBBIter, nextMBB);
7050 // Move all successors to thisMBB to nextMBB
7051 nextMBB->transferSuccessors(thisMBB);
7053 // Update thisMBB to fall through to newMBB
7054 thisMBB->addSuccessor(newMBB);
7056 // newMBB jumps to itself and fall through to nextMBB
7057 newMBB->addSuccessor(nextMBB);
7058 newMBB->addSuccessor(newMBB);
7060 // Insert instructions into newMBB based on incoming instruction
7061 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7062 assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
7063 MachineOperand& dest1Oper = bInstr->getOperand(0);
7064 MachineOperand& dest2Oper = bInstr->getOperand(1);
7065 MachineOperand* argOpers[6];
7066 for (int i=0; i < 6; ++i)
7067 argOpers[i] = &bInstr->getOperand(i+2);
7069 // x86 address has 4 operands: base, index, scale, and displacement
7070 int lastAddrIndx = 3; // [0,3]
7072 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7073 MachineInstrBuilder MIB = BuildMI(thisMBB, TII->get(LoadOpc), t1);
7074 for (int i=0; i <= lastAddrIndx; ++i)
7075 (*MIB).addOperand(*argOpers[i]);
7076 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7077 MIB = BuildMI(thisMBB, TII->get(LoadOpc), t2);
7078 // add 4 to displacement.
7079 for (int i=0; i <= lastAddrIndx-1; ++i)
7080 (*MIB).addOperand(*argOpers[i]);
7081 MachineOperand newOp3 = *(argOpers[3]);
7083 newOp3.setImm(newOp3.getImm()+4);
7085 newOp3.setOffset(newOp3.getOffset()+4);
7086 (*MIB).addOperand(newOp3);
7088 // t3/4 are defined later, at the bottom of the loop
7089 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7090 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7091 BuildMI(newMBB, TII->get(X86::PHI), dest1Oper.getReg())
7092 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7093 BuildMI(newMBB, TII->get(X86::PHI), dest2Oper.getReg())
7094 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7096 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7097 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7099 MIB = BuildMI(newMBB, TII->get(NotOpc), tt1).addReg(t1);
7100 MIB = BuildMI(newMBB, TII->get(NotOpc), tt2).addReg(t2);
7106 assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
7108 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7109 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7110 if (argOpers[4]->isReg())
7111 MIB = BuildMI(newMBB, TII->get(regOpcL), t5);
7113 MIB = BuildMI(newMBB, TII->get(immOpcL), t5);
7114 if (regOpcL != X86::MOV32rr)
7116 (*MIB).addOperand(*argOpers[4]);
7117 assert(argOpers[5]->isReg() == argOpers[4]->isReg());
7118 assert(argOpers[5]->isImm() == argOpers[4]->isImm());
7119 if (argOpers[5]->isReg())
7120 MIB = BuildMI(newMBB, TII->get(regOpcH), t6);
7122 MIB = BuildMI(newMBB, TII->get(immOpcH), t6);
7123 if (regOpcH != X86::MOV32rr)
7125 (*MIB).addOperand(*argOpers[5]);
7127 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EAX);
7129 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EDX);
7132 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EBX);
7134 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::ECX);
7137 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG8B));
7138 for (int i=0; i <= lastAddrIndx; ++i)
7139 (*MIB).addOperand(*argOpers[i]);
7141 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7142 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7144 MIB = BuildMI(newMBB, TII->get(copyOpc), t3);
7145 MIB.addReg(X86::EAX);
7146 MIB = BuildMI(newMBB, TII->get(copyOpc), t4);
7147 MIB.addReg(X86::EDX);
7150 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
7152 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7156 // private utility function
7158 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7159 MachineBasicBlock *MBB,
7161 // For the atomic min/max operator, we generate
7164 // ld t1 = [min/max.addr]
7165 // mov t2 = [min/max.val]
7167 // cmov[cond] t2 = t1
7169 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7171 // fallthrough -->nextMBB
7173 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7174 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7175 MachineFunction::iterator MBBIter = MBB;
7178 /// First build the CFG
7179 MachineFunction *F = MBB->getParent();
7180 MachineBasicBlock *thisMBB = MBB;
7181 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7182 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7183 F->insert(MBBIter, newMBB);
7184 F->insert(MBBIter, nextMBB);
7186 // Move all successors to thisMBB to nextMBB
7187 nextMBB->transferSuccessors(thisMBB);
7189 // Update thisMBB to fall through to newMBB
7190 thisMBB->addSuccessor(newMBB);
7192 // newMBB jumps to newMBB and fall through to nextMBB
7193 newMBB->addSuccessor(nextMBB);
7194 newMBB->addSuccessor(newMBB);
7196 // Insert instructions into newMBB based on incoming instruction
7197 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
7198 MachineOperand& destOper = mInstr->getOperand(0);
7199 MachineOperand* argOpers[6];
7200 int numArgs = mInstr->getNumOperands() - 1;
7201 for (int i=0; i < numArgs; ++i)
7202 argOpers[i] = &mInstr->getOperand(i+1);
7204 // x86 address has 4 operands: base, index, scale, and displacement
7205 int lastAddrIndx = 3; // [0,3]
7208 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7209 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
7210 for (int i=0; i <= lastAddrIndx; ++i)
7211 (*MIB).addOperand(*argOpers[i]);
7213 // We only support register and immediate values
7214 assert((argOpers[valArgIndx]->isReg() ||
7215 argOpers[valArgIndx]->isImm()) &&
7218 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7219 if (argOpers[valArgIndx]->isReg())
7220 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
7222 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
7223 (*MIB).addOperand(*argOpers[valArgIndx]);
7225 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
7228 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
7233 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7234 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
7238 // Cmp and exchange if none has modified the memory location
7239 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
7240 for (int i=0; i <= lastAddrIndx; ++i)
7241 (*MIB).addOperand(*argOpers[i]);
7243 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7244 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7246 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
7247 MIB.addReg(X86::EAX);
7250 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
7252 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7258 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7259 MachineBasicBlock *BB) {
7260 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7261 switch (MI->getOpcode()) {
7262 default: assert(false && "Unexpected instr type to insert");
7263 case X86::CMOV_V1I64:
7264 case X86::CMOV_FR32:
7265 case X86::CMOV_FR64:
7266 case X86::CMOV_V4F32:
7267 case X86::CMOV_V2F64:
7268 case X86::CMOV_V2I64: {
7269 // To "insert" a SELECT_CC instruction, we actually have to insert the
7270 // diamond control-flow pattern. The incoming instruction knows the
7271 // destination vreg to set, the condition code register to branch on, the
7272 // true/false values to select between, and a branch opcode to use.
7273 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7274 MachineFunction::iterator It = BB;
7280 // cmpTY ccX, r1, r2
7282 // fallthrough --> copy0MBB
7283 MachineBasicBlock *thisMBB = BB;
7284 MachineFunction *F = BB->getParent();
7285 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7286 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7288 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7289 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
7290 F->insert(It, copy0MBB);
7291 F->insert(It, sinkMBB);
7292 // Update machine-CFG edges by transferring all successors of the current
7293 // block to the new block which will contain the Phi node for the select.
7294 sinkMBB->transferSuccessors(BB);
7296 // Add the true and fallthrough blocks as its successors.
7297 BB->addSuccessor(copy0MBB);
7298 BB->addSuccessor(sinkMBB);
7301 // %FalseValue = ...
7302 // # fallthrough to sinkMBB
7305 // Update machine-CFG edges
7306 BB->addSuccessor(sinkMBB);
7309 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7312 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
7313 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7314 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7316 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7320 case X86::FP32_TO_INT16_IN_MEM:
7321 case X86::FP32_TO_INT32_IN_MEM:
7322 case X86::FP32_TO_INT64_IN_MEM:
7323 case X86::FP64_TO_INT16_IN_MEM:
7324 case X86::FP64_TO_INT32_IN_MEM:
7325 case X86::FP64_TO_INT64_IN_MEM:
7326 case X86::FP80_TO_INT16_IN_MEM:
7327 case X86::FP80_TO_INT32_IN_MEM:
7328 case X86::FP80_TO_INT64_IN_MEM: {
7329 // Change the floating point control register to use "round towards zero"
7330 // mode when truncating to an integer value.
7331 MachineFunction *F = BB->getParent();
7332 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7333 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7335 // Load the old value of the high byte of the control word...
7337 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7338 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
7340 // Set the high part to be round to zero...
7341 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
7344 // Reload the modified control word now...
7345 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
7347 // Restore the memory image of control word to original value
7348 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
7351 // Get the X86 opcode to use.
7353 switch (MI->getOpcode()) {
7354 default: assert(0 && "illegal opcode!");
7355 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7356 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7357 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7358 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7359 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7360 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7361 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7362 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7363 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7367 MachineOperand &Op = MI->getOperand(0);
7369 AM.BaseType = X86AddressMode::RegBase;
7370 AM.Base.Reg = Op.getReg();
7372 AM.BaseType = X86AddressMode::FrameIndexBase;
7373 AM.Base.FrameIndex = Op.getIndex();
7375 Op = MI->getOperand(1);
7377 AM.Scale = Op.getImm();
7378 Op = MI->getOperand(2);
7380 AM.IndexReg = Op.getImm();
7381 Op = MI->getOperand(3);
7382 if (Op.isGlobal()) {
7383 AM.GV = Op.getGlobal();
7385 AM.Disp = Op.getImm();
7387 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
7388 .addReg(MI->getOperand(4).getReg());
7390 // Reload the original control word now.
7391 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
7393 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7396 case X86::ATOMAND32:
7397 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7398 X86::AND32ri, X86::MOV32rm,
7399 X86::LCMPXCHG32, X86::MOV32rr,
7400 X86::NOT32r, X86::EAX,
7401 X86::GR32RegisterClass);
7403 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7404 X86::OR32ri, X86::MOV32rm,
7405 X86::LCMPXCHG32, X86::MOV32rr,
7406 X86::NOT32r, X86::EAX,
7407 X86::GR32RegisterClass);
7408 case X86::ATOMXOR32:
7409 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7410 X86::XOR32ri, X86::MOV32rm,
7411 X86::LCMPXCHG32, X86::MOV32rr,
7412 X86::NOT32r, X86::EAX,
7413 X86::GR32RegisterClass);
7414 case X86::ATOMNAND32:
7415 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7416 X86::AND32ri, X86::MOV32rm,
7417 X86::LCMPXCHG32, X86::MOV32rr,
7418 X86::NOT32r, X86::EAX,
7419 X86::GR32RegisterClass, true);
7420 case X86::ATOMMIN32:
7421 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7422 case X86::ATOMMAX32:
7423 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7424 case X86::ATOMUMIN32:
7425 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7426 case X86::ATOMUMAX32:
7427 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7429 case X86::ATOMAND16:
7430 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7431 X86::AND16ri, X86::MOV16rm,
7432 X86::LCMPXCHG16, X86::MOV16rr,
7433 X86::NOT16r, X86::AX,
7434 X86::GR16RegisterClass);
7436 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7437 X86::OR16ri, X86::MOV16rm,
7438 X86::LCMPXCHG16, X86::MOV16rr,
7439 X86::NOT16r, X86::AX,
7440 X86::GR16RegisterClass);
7441 case X86::ATOMXOR16:
7442 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7443 X86::XOR16ri, X86::MOV16rm,
7444 X86::LCMPXCHG16, X86::MOV16rr,
7445 X86::NOT16r, X86::AX,
7446 X86::GR16RegisterClass);
7447 case X86::ATOMNAND16:
7448 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7449 X86::AND16ri, X86::MOV16rm,
7450 X86::LCMPXCHG16, X86::MOV16rr,
7451 X86::NOT16r, X86::AX,
7452 X86::GR16RegisterClass, true);
7453 case X86::ATOMMIN16:
7454 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7455 case X86::ATOMMAX16:
7456 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7457 case X86::ATOMUMIN16:
7458 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7459 case X86::ATOMUMAX16:
7460 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7463 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7464 X86::AND8ri, X86::MOV8rm,
7465 X86::LCMPXCHG8, X86::MOV8rr,
7466 X86::NOT8r, X86::AL,
7467 X86::GR8RegisterClass);
7469 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7470 X86::OR8ri, X86::MOV8rm,
7471 X86::LCMPXCHG8, X86::MOV8rr,
7472 X86::NOT8r, X86::AL,
7473 X86::GR8RegisterClass);
7475 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7476 X86::XOR8ri, X86::MOV8rm,
7477 X86::LCMPXCHG8, X86::MOV8rr,
7478 X86::NOT8r, X86::AL,
7479 X86::GR8RegisterClass);
7480 case X86::ATOMNAND8:
7481 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7482 X86::AND8ri, X86::MOV8rm,
7483 X86::LCMPXCHG8, X86::MOV8rr,
7484 X86::NOT8r, X86::AL,
7485 X86::GR8RegisterClass, true);
7486 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7487 // This group is for 64-bit host.
7488 case X86::ATOMAND64:
7489 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7490 X86::AND64ri32, X86::MOV64rm,
7491 X86::LCMPXCHG64, X86::MOV64rr,
7492 X86::NOT64r, X86::RAX,
7493 X86::GR64RegisterClass);
7495 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7496 X86::OR64ri32, X86::MOV64rm,
7497 X86::LCMPXCHG64, X86::MOV64rr,
7498 X86::NOT64r, X86::RAX,
7499 X86::GR64RegisterClass);
7500 case X86::ATOMXOR64:
7501 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7502 X86::XOR64ri32, X86::MOV64rm,
7503 X86::LCMPXCHG64, X86::MOV64rr,
7504 X86::NOT64r, X86::RAX,
7505 X86::GR64RegisterClass);
7506 case X86::ATOMNAND64:
7507 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7508 X86::AND64ri32, X86::MOV64rm,
7509 X86::LCMPXCHG64, X86::MOV64rr,
7510 X86::NOT64r, X86::RAX,
7511 X86::GR64RegisterClass, true);
7512 case X86::ATOMMIN64:
7513 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7514 case X86::ATOMMAX64:
7515 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7516 case X86::ATOMUMIN64:
7517 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7518 case X86::ATOMUMAX64:
7519 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7521 // This group does 64-bit operations on a 32-bit host.
7522 case X86::ATOMAND6432:
7523 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7524 X86::AND32rr, X86::AND32rr,
7525 X86::AND32ri, X86::AND32ri,
7527 case X86::ATOMOR6432:
7528 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7529 X86::OR32rr, X86::OR32rr,
7530 X86::OR32ri, X86::OR32ri,
7532 case X86::ATOMXOR6432:
7533 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7534 X86::XOR32rr, X86::XOR32rr,
7535 X86::XOR32ri, X86::XOR32ri,
7537 case X86::ATOMNAND6432:
7538 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7539 X86::AND32rr, X86::AND32rr,
7540 X86::AND32ri, X86::AND32ri,
7542 case X86::ATOMADD6432:
7543 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7544 X86::ADD32rr, X86::ADC32rr,
7545 X86::ADD32ri, X86::ADC32ri,
7547 case X86::ATOMSUB6432:
7548 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7549 X86::SUB32rr, X86::SBB32rr,
7550 X86::SUB32ri, X86::SBB32ri,
7552 case X86::ATOMSWAP6432:
7553 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7554 X86::MOV32rr, X86::MOV32rr,
7555 X86::MOV32ri, X86::MOV32ri,
7560 //===----------------------------------------------------------------------===//
7561 // X86 Optimization Hooks
7562 //===----------------------------------------------------------------------===//
7564 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7568 const SelectionDAG &DAG,
7569 unsigned Depth) const {
7570 unsigned Opc = Op.getOpcode();
7571 assert((Opc >= ISD::BUILTIN_OP_END ||
7572 Opc == ISD::INTRINSIC_WO_CHAIN ||
7573 Opc == ISD::INTRINSIC_W_CHAIN ||
7574 Opc == ISD::INTRINSIC_VOID) &&
7575 "Should use MaskedValueIsZero if you don't know whether Op"
7576 " is a target node!");
7578 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7585 // These nodes' second result is a boolean.
7586 if (Op.getResNo() == 0)
7590 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7591 Mask.getBitWidth() - 1);
7596 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7597 /// node is a GlobalAddress + offset.
7598 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7599 GlobalValue* &GA, int64_t &Offset) const{
7600 if (N->getOpcode() == X86ISD::Wrapper) {
7601 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7602 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7603 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7607 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7610 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7611 const TargetLowering &TLI) {
7614 if (TLI.isGAPlusOffset(Base, GV, Offset))
7615 return (GV->getAlignment() >= N && (Offset % N) == 0);
7616 // DAG combine handles the stack object case.
7620 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
7621 unsigned NumElems, MVT EVT,
7623 SelectionDAG &DAG, MachineFrameInfo *MFI,
7624 const TargetLowering &TLI) {
7626 for (unsigned i = 0; i < NumElems; ++i) {
7627 SDValue Idx = PermMask.getOperand(i);
7628 if (Idx.getOpcode() == ISD::UNDEF) {
7634 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7635 if (!Elt.getNode() ||
7636 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7639 Base = Elt.getNode();
7640 if (Base->getOpcode() == ISD::UNDEF)
7644 if (Elt.getOpcode() == ISD::UNDEF)
7647 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7648 EVT.getSizeInBits()/8, i, MFI))
7654 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7655 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7656 /// if the load addresses are consecutive, non-overlapping, and in the right
7658 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7659 const TargetLowering &TLI) {
7660 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7661 MVT VT = N->getValueType(0);
7662 MVT EVT = VT.getVectorElementType();
7663 SDValue PermMask = N->getOperand(2);
7664 unsigned NumElems = PermMask.getNumOperands();
7665 SDNode *Base = NULL;
7666 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
7670 LoadSDNode *LD = cast<LoadSDNode>(Base);
7671 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7672 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7673 LD->getSrcValueOffset(), LD->isVolatile());
7674 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7675 LD->getSrcValueOffset(), LD->isVolatile(),
7676 LD->getAlignment());
7679 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7680 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7681 TargetLowering::DAGCombinerInfo &DCI,
7682 const X86Subtarget *Subtarget,
7683 const TargetLowering &TLI) {
7684 unsigned NumOps = N->getNumOperands();
7686 // Ignore single operand BUILD_VECTOR.
7690 MVT VT = N->getValueType(0);
7691 MVT EVT = VT.getVectorElementType();
7692 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7693 // We are looking for load i64 and zero extend. We want to transform
7694 // it before legalizer has a chance to expand it. Also look for i64
7695 // BUILD_PAIR bit casted to f64.
7697 // This must be an insertion into a zero vector.
7698 SDValue HighElt = N->getOperand(1);
7699 if (!isZeroNode(HighElt))
7702 // Value must be a load.
7703 SDNode *Base = N->getOperand(0).getNode();
7704 if (!isa<LoadSDNode>(Base)) {
7705 if (Base->getOpcode() != ISD::BIT_CONVERT)
7707 Base = Base->getOperand(0).getNode();
7708 if (!isa<LoadSDNode>(Base))
7712 // Transform it into VZEXT_LOAD addr.
7713 LoadSDNode *LD = cast<LoadSDNode>(Base);
7715 // Load must not be an extload.
7716 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7719 // Load type should legal type so we don't have to legalize it.
7720 if (!TLI.isTypeLegal(VT))
7723 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7724 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7725 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, Tys, Ops, 2);
7726 TargetLowering::TargetLoweringOpt TLO(DAG);
7727 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
7728 DCI.CommitTargetLoweringOpt(TLO);
7732 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7733 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7734 const X86Subtarget *Subtarget) {
7735 SDValue Cond = N->getOperand(0);
7737 // If we have SSE[12] support, try to form min/max nodes.
7738 if (Subtarget->hasSSE2() &&
7739 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
7740 if (Cond.getOpcode() == ISD::SETCC) {
7741 // Get the LHS/RHS of the select.
7742 SDValue LHS = N->getOperand(1);
7743 SDValue RHS = N->getOperand(2);
7744 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7746 unsigned Opcode = 0;
7747 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7750 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7753 if (!UnsafeFPMath) break;
7755 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7757 Opcode = X86ISD::FMIN;
7760 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7763 if (!UnsafeFPMath) break;
7765 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7767 Opcode = X86ISD::FMAX;
7770 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7773 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7776 if (!UnsafeFPMath) break;
7778 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7780 Opcode = X86ISD::FMIN;
7783 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7786 if (!UnsafeFPMath) break;
7788 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7790 Opcode = X86ISD::FMAX;
7796 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
7804 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
7806 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
7807 const X86Subtarget *Subtarget) {
7808 // On X86 with SSE2 support, we can transform this to a vector shift if
7809 // all elements are shifted by the same amount. We can't do this in legalize
7810 // because the a constant vector is typically transformed to a constant pool
7811 // so we have no knowledge of the shift amount.
7812 if (!Subtarget->hasSSE2())
7815 MVT VT = N->getValueType(0);
7816 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
7819 SDValue ShAmtOp = N->getOperand(1);
7820 MVT EltVT = VT.getVectorElementType();
7822 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
7823 unsigned NumElts = VT.getVectorNumElements();
7825 for (; i != NumElts; ++i) {
7826 SDValue Arg = ShAmtOp.getOperand(i);
7827 if (Arg.getOpcode() == ISD::UNDEF) continue;
7831 for (; i != NumElts; ++i) {
7832 SDValue Arg = ShAmtOp.getOperand(i);
7833 if (Arg.getOpcode() == ISD::UNDEF) continue;
7834 if (Arg != BaseShAmt) {
7838 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
7839 isSplatMask(ShAmtOp.getOperand(2).getNode())) {
7840 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, ShAmtOp,
7841 DAG.getIntPtrConstant(0));
7845 if (EltVT.bitsGT(MVT::i32))
7846 BaseShAmt = DAG.getNode(ISD::TRUNCATE, MVT::i32, BaseShAmt);
7847 else if (EltVT.bitsLT(MVT::i32))
7848 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, BaseShAmt);
7850 // The shift amount is identical so we can do a vector shift.
7851 SDValue ValOp = N->getOperand(0);
7852 switch (N->getOpcode()) {
7854 assert(0 && "Unknown shift opcode!");
7857 if (VT == MVT::v2i64)
7858 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7859 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7861 if (VT == MVT::v4i32)
7862 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7863 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
7865 if (VT == MVT::v8i16)
7866 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7867 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
7871 if (VT == MVT::v4i32)
7872 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7873 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
7875 if (VT == MVT::v8i16)
7876 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7877 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
7881 if (VT == MVT::v2i64)
7882 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7883 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7885 if (VT == MVT::v4i32)
7886 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7887 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
7889 if (VT == MVT::v8i16)
7890 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
7891 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
7898 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
7899 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
7900 const X86Subtarget *Subtarget) {
7901 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
7902 // the FP state in cases where an emms may be missing.
7903 // A preferable solution to the general problem is to figure out the right
7904 // places to insert EMMS. This qualifies as a quick hack.
7905 StoreSDNode *St = cast<StoreSDNode>(N);
7906 if (St->getValue().getValueType().isVector() &&
7907 St->getValue().getValueType().getSizeInBits() == 64 &&
7908 isa<LoadSDNode>(St->getValue()) &&
7909 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
7910 St->getChain().hasOneUse() && !St->isVolatile()) {
7911 SDNode* LdVal = St->getValue().getNode();
7913 int TokenFactorIndex = -1;
7914 SmallVector<SDValue, 8> Ops;
7915 SDNode* ChainVal = St->getChain().getNode();
7916 // Must be a store of a load. We currently handle two cases: the load
7917 // is a direct child, and it's under an intervening TokenFactor. It is
7918 // possible to dig deeper under nested TokenFactors.
7919 if (ChainVal == LdVal)
7920 Ld = cast<LoadSDNode>(St->getChain());
7921 else if (St->getValue().hasOneUse() &&
7922 ChainVal->getOpcode() == ISD::TokenFactor) {
7923 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
7924 if (ChainVal->getOperand(i).getNode() == LdVal) {
7925 TokenFactorIndex = i;
7926 Ld = cast<LoadSDNode>(St->getValue());
7928 Ops.push_back(ChainVal->getOperand(i));
7932 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
7933 if (Subtarget->is64Bit()) {
7934 SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
7935 Ld->getBasePtr(), Ld->getSrcValue(),
7936 Ld->getSrcValueOffset(), Ld->isVolatile(),
7937 Ld->getAlignment());
7938 SDValue NewChain = NewLd.getValue(1);
7939 if (TokenFactorIndex != -1) {
7940 Ops.push_back(NewChain);
7941 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7944 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
7945 St->getSrcValue(), St->getSrcValueOffset(),
7946 St->isVolatile(), St->getAlignment());
7949 // Otherwise, lower to two 32-bit copies.
7950 SDValue LoAddr = Ld->getBasePtr();
7951 SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7952 DAG.getConstant(4, MVT::i32));
7954 SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
7955 Ld->getSrcValue(), Ld->getSrcValueOffset(),
7956 Ld->isVolatile(), Ld->getAlignment());
7957 SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
7958 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
7960 MinAlign(Ld->getAlignment(), 4));
7962 SDValue NewChain = LoLd.getValue(1);
7963 if (TokenFactorIndex != -1) {
7964 Ops.push_back(LoLd);
7965 Ops.push_back(HiLd);
7966 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7970 LoAddr = St->getBasePtr();
7971 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7972 DAG.getConstant(4, MVT::i32));
7974 SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
7975 St->getSrcValue(), St->getSrcValueOffset(),
7976 St->isVolatile(), St->getAlignment());
7977 SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
7979 St->getSrcValueOffset() + 4,
7981 MinAlign(St->getAlignment(), 4));
7982 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
7988 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
7989 /// X86ISD::FXOR nodes.
7990 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
7991 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
7992 // F[X]OR(0.0, x) -> x
7993 // F[X]OR(x, 0.0) -> x
7994 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7995 if (C->getValueAPF().isPosZero())
7996 return N->getOperand(1);
7997 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7998 if (C->getValueAPF().isPosZero())
7999 return N->getOperand(0);
8003 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8004 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8005 // FAND(0.0, x) -> 0.0
8006 // FAND(x, 0.0) -> 0.0
8007 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8008 if (C->getValueAPF().isPosZero())
8009 return N->getOperand(0);
8010 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8011 if (C->getValueAPF().isPosZero())
8012 return N->getOperand(1);
8016 static SDValue PerformBTCombine(SDNode *N,
8018 TargetLowering::DAGCombinerInfo &DCI) {
8019 // BT ignores high bits in the bit index operand.
8020 SDValue Op1 = N->getOperand(1);
8021 if (Op1.hasOneUse()) {
8022 unsigned BitWidth = Op1.getValueSizeInBits();
8023 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8024 APInt KnownZero, KnownOne;
8025 TargetLowering::TargetLoweringOpt TLO(DAG);
8026 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8027 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8028 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8029 DCI.CommitTargetLoweringOpt(TLO);
8034 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8035 DAGCombinerInfo &DCI) const {
8036 SelectionDAG &DAG = DCI.DAG;
8037 switch (N->getOpcode()) {
8039 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8040 case ISD::BUILD_VECTOR:
8041 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8042 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8045 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8046 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8048 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8049 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8050 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8056 //===----------------------------------------------------------------------===//
8057 // X86 Inline Assembly Support
8058 //===----------------------------------------------------------------------===//
8060 /// getConstraintType - Given a constraint letter, return the type of
8061 /// constraint it is for this target.
8062 X86TargetLowering::ConstraintType
8063 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8064 if (Constraint.size() == 1) {
8065 switch (Constraint[0]) {
8077 return C_RegisterClass;
8082 return TargetLowering::getConstraintType(Constraint);
8085 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8086 /// with another that has more specific requirements based on the type of the
8087 /// corresponding operand.
8088 const char *X86TargetLowering::
8089 LowerXConstraint(MVT ConstraintVT) const {
8090 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8091 // 'f' like normal targets.
8092 if (ConstraintVT.isFloatingPoint()) {
8093 if (Subtarget->hasSSE2())
8095 if (Subtarget->hasSSE1())
8099 return TargetLowering::LowerXConstraint(ConstraintVT);
8102 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8103 /// vector. If it is invalid, don't add anything to Ops.
8104 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8107 std::vector<SDValue>&Ops,
8108 SelectionDAG &DAG) const {
8109 SDValue Result(0, 0);
8111 switch (Constraint) {
8114 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8115 if (C->getZExtValue() <= 31) {
8116 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8122 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8123 if (C->getZExtValue() <= 63) {
8124 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8130 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8131 if (C->getZExtValue() <= 255) {
8132 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8138 // Literal immediates are always ok.
8139 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8140 Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
8144 // If we are in non-pic codegen mode, we allow the address of a global (with
8145 // an optional displacement) to be used with 'i'.
8146 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
8149 // Match either (GA) or (GA+C)
8151 Offset = GA->getOffset();
8152 } else if (Op.getOpcode() == ISD::ADD) {
8153 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8154 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8156 Offset = GA->getOffset()+C->getZExtValue();
8158 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8159 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8161 Offset = GA->getOffset()+C->getZExtValue();
8169 Op = LowerGlobalAddress(GA->getGlobal(), Offset, DAG);
8171 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8177 // Otherwise, not valid for this mode.
8182 if (Result.getNode()) {
8183 Ops.push_back(Result);
8186 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8190 std::vector<unsigned> X86TargetLowering::
8191 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8193 if (Constraint.size() == 1) {
8194 // FIXME: not handling fp-stack yet!
8195 switch (Constraint[0]) { // GCC X86 Constraint Letters
8196 default: break; // Unknown constraint letter
8197 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8200 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8201 else if (VT == MVT::i16)
8202 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8203 else if (VT == MVT::i8)
8204 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8205 else if (VT == MVT::i64)
8206 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8211 return std::vector<unsigned>();
8214 std::pair<unsigned, const TargetRegisterClass*>
8215 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8217 // First, see if this is a constraint that directly corresponds to an LLVM
8219 if (Constraint.size() == 1) {
8220 // GCC Constraint Letters
8221 switch (Constraint[0]) {
8223 case 'r': // GENERAL_REGS
8224 case 'R': // LEGACY_REGS
8225 case 'l': // INDEX_REGS
8227 return std::make_pair(0U, X86::GR8RegisterClass);
8229 return std::make_pair(0U, X86::GR16RegisterClass);
8230 if (VT == MVT::i32 || !Subtarget->is64Bit())
8231 return std::make_pair(0U, X86::GR32RegisterClass);
8232 return std::make_pair(0U, X86::GR64RegisterClass);
8233 case 'f': // FP Stack registers.
8234 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8235 // value to the correct fpstack register class.
8236 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8237 return std::make_pair(0U, X86::RFP32RegisterClass);
8238 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8239 return std::make_pair(0U, X86::RFP64RegisterClass);
8240 return std::make_pair(0U, X86::RFP80RegisterClass);
8241 case 'y': // MMX_REGS if MMX allowed.
8242 if (!Subtarget->hasMMX()) break;
8243 return std::make_pair(0U, X86::VR64RegisterClass);
8244 case 'Y': // SSE_REGS if SSE2 allowed
8245 if (!Subtarget->hasSSE2()) break;
8247 case 'x': // SSE_REGS if SSE1 allowed
8248 if (!Subtarget->hasSSE1()) break;
8250 switch (VT.getSimpleVT()) {
8252 // Scalar SSE types.
8255 return std::make_pair(0U, X86::FR32RegisterClass);
8258 return std::make_pair(0U, X86::FR64RegisterClass);
8266 return std::make_pair(0U, X86::VR128RegisterClass);
8272 // Use the default implementation in TargetLowering to convert the register
8273 // constraint into a member of a register class.
8274 std::pair<unsigned, const TargetRegisterClass*> Res;
8275 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8277 // Not found as a standard register?
8278 if (Res.second == 0) {
8279 // GCC calls "st(0)" just plain "st".
8280 if (StringsEqualNoCase("{st}", Constraint)) {
8281 Res.first = X86::ST0;
8282 Res.second = X86::RFP80RegisterClass;
8284 // 'A' means EAX + EDX.
8285 if (Constraint == "A") {
8286 Res.first = X86::EAX;
8287 Res.second = X86::GRADRegisterClass;
8292 // Otherwise, check to see if this is a register class of the wrong value
8293 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8294 // turn into {ax},{dx}.
8295 if (Res.second->hasType(VT))
8296 return Res; // Correct type already, nothing to do.
8298 // All of the single-register GCC register classes map their values onto
8299 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8300 // really want an 8-bit or 32-bit register, map to the appropriate register
8301 // class and return the appropriate register.
8302 if (Res.second == X86::GR16RegisterClass) {
8303 if (VT == MVT::i8) {
8304 unsigned DestReg = 0;
8305 switch (Res.first) {
8307 case X86::AX: DestReg = X86::AL; break;
8308 case X86::DX: DestReg = X86::DL; break;
8309 case X86::CX: DestReg = X86::CL; break;
8310 case X86::BX: DestReg = X86::BL; break;
8313 Res.first = DestReg;
8314 Res.second = Res.second = X86::GR8RegisterClass;
8316 } else if (VT == MVT::i32) {
8317 unsigned DestReg = 0;
8318 switch (Res.first) {
8320 case X86::AX: DestReg = X86::EAX; break;
8321 case X86::DX: DestReg = X86::EDX; break;
8322 case X86::CX: DestReg = X86::ECX; break;
8323 case X86::BX: DestReg = X86::EBX; break;
8324 case X86::SI: DestReg = X86::ESI; break;
8325 case X86::DI: DestReg = X86::EDI; break;
8326 case X86::BP: DestReg = X86::EBP; break;
8327 case X86::SP: DestReg = X86::ESP; break;
8330 Res.first = DestReg;
8331 Res.second = Res.second = X86::GR32RegisterClass;
8333 } else if (VT == MVT::i64) {
8334 unsigned DestReg = 0;
8335 switch (Res.first) {
8337 case X86::AX: DestReg = X86::RAX; break;
8338 case X86::DX: DestReg = X86::RDX; break;
8339 case X86::CX: DestReg = X86::RCX; break;
8340 case X86::BX: DestReg = X86::RBX; break;
8341 case X86::SI: DestReg = X86::RSI; break;
8342 case X86::DI: DestReg = X86::RDI; break;
8343 case X86::BP: DestReg = X86::RBP; break;
8344 case X86::SP: DestReg = X86::RSP; break;
8347 Res.first = DestReg;
8348 Res.second = Res.second = X86::GR64RegisterClass;
8351 } else if (Res.second == X86::FR32RegisterClass ||
8352 Res.second == X86::FR64RegisterClass ||
8353 Res.second == X86::VR128RegisterClass) {
8354 // Handle references to XMM physical registers that got mapped into the
8355 // wrong class. This can happen with constraints like {xmm0} where the
8356 // target independent register mapper will just pick the first match it can
8357 // find, ignoring the required type.
8359 Res.second = X86::FR32RegisterClass;
8360 else if (VT == MVT::f64)
8361 Res.second = X86::FR64RegisterClass;
8362 else if (X86::VR128RegisterClass->hasType(VT))
8363 Res.second = X86::VR128RegisterClass;
8369 //===----------------------------------------------------------------------===//
8370 // X86 Widen vector type
8371 //===----------------------------------------------------------------------===//
8373 /// getWidenVectorType: given a vector type, returns the type to widen
8374 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8375 /// If there is no vector type that we want to widen to, returns MVT::Other
8376 /// When and where to widen is target dependent based on the cost of
8377 /// scalarizing vs using the wider vector type.
8379 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8380 assert(VT.isVector());
8381 if (isTypeLegal(VT))
8384 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8385 // type based on element type. This would speed up our search (though
8386 // it may not be worth it since the size of the list is relatively
8388 MVT EltVT = VT.getVectorElementType();
8389 unsigned NElts = VT.getVectorNumElements();
8391 // On X86, it make sense to widen any vector wider than 1
8395 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8396 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8397 MVT SVT = (MVT::SimpleValueType)nVT;
8399 if (isTypeLegal(SVT) &&
8400 SVT.getVectorElementType() == EltVT &&
8401 SVT.getVectorNumElements() > NElts)