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, dl, 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, dl, Reg, getPointerTy());
1009 Chain = DAG.getCopyToReg(Chain, dl, 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, dl, 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,
1204 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1205 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1206 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1209 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1210 const CCValAssign &VA,
1211 MachineFrameInfo *MFI,
1213 SDValue Root, unsigned i) {
1214 // Create the nodes corresponding to a load from this parameter slot.
1215 ISD::ArgFlagsTy Flags =
1216 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1217 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1218 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1220 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1221 // changed with more analysis.
1222 // In case of tail call optimization mark all arguments mutable. Since they
1223 // could be overwritten by lowering of arguments in case of a tail call.
1224 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1225 VA.getLocMemOffset(), isImmutable);
1226 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1227 if (Flags.isByVal())
1229 return DAG.getLoad(VA.getValVT(), Op.getNode()->getDebugLoc(), Root, FIN,
1230 PseudoSourceValue::getFixedStack(FI), 0);
1234 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1235 MachineFunction &MF = DAG.getMachineFunction();
1236 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1237 DebugLoc dl = Op.getNode()->getDebugLoc();
1239 const Function* Fn = MF.getFunction();
1240 if (Fn->hasExternalLinkage() &&
1241 Subtarget->isTargetCygMing() &&
1242 Fn->getName() == "main")
1243 FuncInfo->setForceFramePointer(true);
1245 // Decorate the function name.
1246 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1248 MachineFrameInfo *MFI = MF.getFrameInfo();
1249 SDValue Root = Op.getOperand(0);
1250 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1251 unsigned CC = MF.getFunction()->getCallingConv();
1252 bool Is64Bit = Subtarget->is64Bit();
1253 bool IsWin64 = Subtarget->isTargetWin64();
1255 assert(!(isVarArg && CC == CallingConv::Fast) &&
1256 "Var args not supported with calling convention fastcc");
1258 // Assign locations to all of the incoming arguments.
1259 SmallVector<CCValAssign, 16> ArgLocs;
1260 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1261 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1263 SmallVector<SDValue, 8> ArgValues;
1264 unsigned LastVal = ~0U;
1265 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1266 CCValAssign &VA = ArgLocs[i];
1267 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1269 assert(VA.getValNo() != LastVal &&
1270 "Don't support value assigned to multiple locs yet");
1271 LastVal = VA.getValNo();
1273 if (VA.isRegLoc()) {
1274 MVT RegVT = VA.getLocVT();
1275 TargetRegisterClass *RC = NULL;
1276 if (RegVT == MVT::i32)
1277 RC = X86::GR32RegisterClass;
1278 else if (Is64Bit && RegVT == MVT::i64)
1279 RC = X86::GR64RegisterClass;
1280 else if (RegVT == MVT::f32)
1281 RC = X86::FR32RegisterClass;
1282 else if (RegVT == MVT::f64)
1283 RC = X86::FR64RegisterClass;
1284 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1285 RC = X86::VR128RegisterClass;
1286 else if (RegVT.isVector()) {
1287 assert(RegVT.getSizeInBits() == 64);
1289 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1291 // Darwin calling convention passes MMX values in either GPRs or
1292 // XMMs in x86-64. Other targets pass them in memory.
1293 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1294 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1297 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1302 assert(0 && "Unknown argument type!");
1305 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1306 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1308 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1309 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1311 if (VA.getLocInfo() == CCValAssign::SExt)
1312 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1313 DAG.getValueType(VA.getValVT()));
1314 else if (VA.getLocInfo() == CCValAssign::ZExt)
1315 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1316 DAG.getValueType(VA.getValVT()));
1318 if (VA.getLocInfo() != CCValAssign::Full)
1319 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1321 // Handle MMX values passed in GPRs.
1322 if (Is64Bit && RegVT != VA.getLocVT()) {
1323 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1324 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1325 else if (RC == X86::VR128RegisterClass) {
1326 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1327 ArgValue, DAG.getConstant(0, MVT::i64));
1328 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1332 ArgValues.push_back(ArgValue);
1334 assert(VA.isMemLoc());
1335 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1339 // The x86-64 ABI for returning structs by value requires that we copy
1340 // the sret argument into %rax for the return. Save the argument into
1341 // a virtual register so that we can access it from the return points.
1342 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1343 MachineFunction &MF = DAG.getMachineFunction();
1344 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1345 unsigned Reg = FuncInfo->getSRetReturnReg();
1347 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1348 FuncInfo->setSRetReturnReg(Reg);
1350 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1351 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1354 unsigned StackSize = CCInfo.getNextStackOffset();
1355 // align stack specially for tail calls
1356 if (PerformTailCallOpt && CC == CallingConv::Fast)
1357 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1359 // If the function takes variable number of arguments, make a frame index for
1360 // the start of the first vararg value... for expansion of llvm.va_start.
1362 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1363 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1366 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1368 // FIXME: We should really autogenerate these arrays
1369 static const unsigned GPR64ArgRegsWin64[] = {
1370 X86::RCX, X86::RDX, X86::R8, X86::R9
1372 static const unsigned XMMArgRegsWin64[] = {
1373 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1375 static const unsigned GPR64ArgRegs64Bit[] = {
1376 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1378 static const unsigned XMMArgRegs64Bit[] = {
1379 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1380 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1382 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1385 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1386 GPR64ArgRegs = GPR64ArgRegsWin64;
1387 XMMArgRegs = XMMArgRegsWin64;
1389 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1390 GPR64ArgRegs = GPR64ArgRegs64Bit;
1391 XMMArgRegs = XMMArgRegs64Bit;
1393 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1395 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1398 assert((Subtarget->hasSSE1() || !NumXMMRegs) &&
1399 "SSE register cannot be used when SSE is disabled!");
1400 if (!Subtarget->hasSSE1()) {
1401 // Kernel mode asks for SSE to be disabled, so don't push them
1403 TotalNumXMMRegs = 0;
1405 // For X86-64, if there are vararg parameters that are passed via
1406 // registers, then we must store them to their spots on the stack so they
1407 // may be loaded by deferencing the result of va_next.
1408 VarArgsGPOffset = NumIntRegs * 8;
1409 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1410 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1411 TotalNumXMMRegs * 16, 16);
1413 // Store the integer parameter registers.
1414 SmallVector<SDValue, 8> MemOps;
1415 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1416 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1417 DAG.getIntPtrConstant(VarArgsGPOffset));
1418 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1419 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1420 X86::GR64RegisterClass);
1421 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1423 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1424 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1425 MemOps.push_back(Store);
1426 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1427 DAG.getIntPtrConstant(8));
1430 // Now store the XMM (fp + vector) parameter registers.
1431 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1432 DAG.getIntPtrConstant(VarArgsFPOffset));
1433 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1434 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1435 X86::VR128RegisterClass);
1436 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1438 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1439 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1440 MemOps.push_back(Store);
1441 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1442 DAG.getIntPtrConstant(16));
1444 if (!MemOps.empty())
1445 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1446 &MemOps[0], MemOps.size());
1450 ArgValues.push_back(Root);
1452 // Some CCs need callee pop.
1453 if (IsCalleePop(isVarArg, CC)) {
1454 BytesToPopOnReturn = StackSize; // Callee pops everything.
1455 BytesCallerReserves = 0;
1457 BytesToPopOnReturn = 0; // Callee pops nothing.
1458 // If this is an sret function, the return should pop the hidden pointer.
1459 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1460 BytesToPopOnReturn = 4;
1461 BytesCallerReserves = StackSize;
1465 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1466 if (CC == CallingConv::X86_FastCall)
1467 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1470 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1472 // Return the new list of results.
1473 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1474 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1478 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1479 const SDValue &StackPtr,
1480 const CCValAssign &VA,
1482 SDValue Arg, ISD::ArgFlagsTy Flags) {
1483 DebugLoc dl = TheCall->getDebugLoc();
1484 unsigned LocMemOffset = VA.getLocMemOffset();
1485 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1486 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1487 if (Flags.isByVal()) {
1488 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1490 return DAG.getStore(Chain, dl, Arg, PtrOff,
1491 PseudoSourceValue::getStack(), LocMemOffset);
1494 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1495 /// optimization is performed and it is required.
1497 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1498 SDValue &OutRetAddr,
1504 if (!IsTailCall || FPDiff==0) return Chain;
1506 // Adjust the Return address stack slot.
1507 MVT VT = getPointerTy();
1508 OutRetAddr = getReturnAddressFrameIndex(DAG);
1510 // Load the "old" Return address.
1511 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1512 return SDValue(OutRetAddr.getNode(), 1);
1515 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1516 /// optimization is performed and it is required (FPDiff!=0).
1518 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1519 SDValue Chain, SDValue RetAddrFrIdx,
1520 bool Is64Bit, int FPDiff, DebugLoc dl) {
1521 // Store the return address to the appropriate stack slot.
1522 if (!FPDiff) return Chain;
1523 // Calculate the new stack slot for the return address.
1524 int SlotSize = Is64Bit ? 8 : 4;
1525 int NewReturnAddrFI =
1526 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1527 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1528 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1529 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1530 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1534 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1535 MachineFunction &MF = DAG.getMachineFunction();
1536 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1537 SDValue Chain = TheCall->getChain();
1538 unsigned CC = TheCall->getCallingConv();
1539 bool isVarArg = TheCall->isVarArg();
1540 bool IsTailCall = TheCall->isTailCall() &&
1541 CC == CallingConv::Fast && PerformTailCallOpt;
1542 SDValue Callee = TheCall->getCallee();
1543 bool Is64Bit = Subtarget->is64Bit();
1544 bool IsStructRet = CallIsStructReturn(TheCall);
1545 DebugLoc dl = TheCall->getDebugLoc();
1547 assert(!(isVarArg && CC == CallingConv::Fast) &&
1548 "Var args not supported with calling convention fastcc");
1550 // Analyze operands of the call, assigning locations to each operand.
1551 SmallVector<CCValAssign, 16> ArgLocs;
1552 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1553 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1555 // Get a count of how many bytes are to be pushed on the stack.
1556 unsigned NumBytes = CCInfo.getNextStackOffset();
1557 if (PerformTailCallOpt && CC == CallingConv::Fast)
1558 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1562 // Lower arguments at fp - stackoffset + fpdiff.
1563 unsigned NumBytesCallerPushed =
1564 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1565 FPDiff = NumBytesCallerPushed - NumBytes;
1567 // Set the delta of movement of the returnaddr stackslot.
1568 // But only set if delta is greater than previous delta.
1569 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1570 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1573 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1575 SDValue RetAddrFrIdx;
1576 // Load return adress for tail calls.
1577 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1580 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1581 SmallVector<SDValue, 8> MemOpChains;
1584 // Walk the register/memloc assignments, inserting copies/loads. In the case
1585 // of tail call optimization arguments are handle later.
1586 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1587 CCValAssign &VA = ArgLocs[i];
1588 SDValue Arg = TheCall->getArg(i);
1589 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1590 bool isByVal = Flags.isByVal();
1592 // Promote the value if needed.
1593 switch (VA.getLocInfo()) {
1594 default: assert(0 && "Unknown loc info!");
1595 case CCValAssign::Full: break;
1596 case CCValAssign::SExt:
1597 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1599 case CCValAssign::ZExt:
1600 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1602 case CCValAssign::AExt:
1603 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1607 if (VA.isRegLoc()) {
1609 MVT RegVT = VA.getLocVT();
1610 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1611 switch (VA.getLocReg()) {
1614 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1616 // Special case: passing MMX values in GPR registers.
1617 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1620 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1621 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1622 // Special case: passing MMX values in XMM registers.
1623 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1624 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1625 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
1626 DAG.getNode(ISD::UNDEF, dl, MVT::v2i64), Arg,
1627 getMOVLMask(2, DAG, dl));
1632 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1634 if (!IsTailCall || (IsTailCall && isByVal)) {
1635 assert(VA.isMemLoc());
1636 if (StackPtr.getNode() == 0)
1637 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1639 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1640 Chain, Arg, Flags));
1645 if (!MemOpChains.empty())
1646 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1647 &MemOpChains[0], MemOpChains.size());
1649 // Build a sequence of copy-to-reg nodes chained together with token chain
1650 // and flag operands which copy the outgoing args into registers.
1652 // Tail call byval lowering might overwrite argument registers so in case of
1653 // tail call optimization the copies to registers are lowered later.
1655 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1656 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1657 RegsToPass[i].second, InFlag);
1658 InFlag = Chain.getValue(1);
1661 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1663 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1664 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1665 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1667 InFlag = Chain.getValue(1);
1669 // If we are tail calling and generating PIC/GOT style code load the address
1670 // of the callee into ecx. The value in ecx is used as target of the tail
1671 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1672 // calls on PIC/GOT architectures. Normally we would just put the address of
1673 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1674 // restored (since ebx is callee saved) before jumping to the target@PLT.
1675 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1676 // Note: The actual moving to ecx is done further down.
1677 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1678 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1679 !G->getGlobal()->hasProtectedVisibility())
1680 Callee = LowerGlobalAddress(Callee, DAG);
1681 else if (isa<ExternalSymbolSDNode>(Callee))
1682 Callee = LowerExternalSymbol(Callee,DAG);
1685 if (Is64Bit && isVarArg) {
1686 // From AMD64 ABI document:
1687 // For calls that may call functions that use varargs or stdargs
1688 // (prototype-less calls or calls to functions containing ellipsis (...) in
1689 // the declaration) %al is used as hidden argument to specify the number
1690 // of SSE registers used. The contents of %al do not need to match exactly
1691 // the number of registers, but must be an ubound on the number of SSE
1692 // registers used and is in the range 0 - 8 inclusive.
1694 // FIXME: Verify this on Win64
1695 // Count the number of XMM registers allocated.
1696 static const unsigned XMMArgRegs[] = {
1697 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1698 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1700 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1701 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1702 && "SSE registers cannot be used when SSE is disabled");
1704 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1705 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1706 InFlag = Chain.getValue(1);
1710 // For tail calls lower the arguments to the 'real' stack slot.
1712 SmallVector<SDValue, 8> MemOpChains2;
1715 // Do not flag preceeding copytoreg stuff together with the following stuff.
1717 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1718 CCValAssign &VA = ArgLocs[i];
1719 if (!VA.isRegLoc()) {
1720 assert(VA.isMemLoc());
1721 SDValue Arg = TheCall->getArg(i);
1722 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1723 // Create frame index.
1724 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1725 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1726 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1727 FIN = DAG.getFrameIndex(FI, getPointerTy());
1729 if (Flags.isByVal()) {
1730 // Copy relative to framepointer.
1731 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1732 if (StackPtr.getNode() == 0)
1733 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1735 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1737 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1740 // Store relative to framepointer.
1741 MemOpChains2.push_back(
1742 DAG.getStore(Chain, dl, Arg, FIN,
1743 PseudoSourceValue::getFixedStack(FI), 0));
1748 if (!MemOpChains2.empty())
1749 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1750 &MemOpChains2[0], MemOpChains2.size());
1752 // Copy arguments to their registers.
1753 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1754 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1755 RegsToPass[i].second, InFlag);
1756 InFlag = Chain.getValue(1);
1760 // Store the return address to the appropriate stack slot.
1761 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1765 // If the callee is a GlobalAddress node (quite common, every direct call is)
1766 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1767 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1768 // We should use extra load for direct calls to dllimported functions in
1770 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1771 getTargetMachine(), true))
1772 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1774 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1775 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1776 } else if (IsTailCall) {
1777 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1779 Chain = DAG.getCopyToReg(Chain, dl,
1780 DAG.getRegister(Opc, getPointerTy()),
1782 Callee = DAG.getRegister(Opc, getPointerTy());
1783 // Add register as live out.
1784 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1787 // Returns a chain & a flag for retval copy to use.
1788 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1789 SmallVector<SDValue, 8> Ops;
1792 Ops.push_back(Chain);
1793 Ops.push_back(DAG.getIntPtrConstant(NumBytes, true));
1794 Ops.push_back(DAG.getIntPtrConstant(0, true));
1795 if (InFlag.getNode())
1796 Ops.push_back(InFlag);
1797 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1798 InFlag = Chain.getValue(1);
1800 // Returns a chain & a flag for retval copy to use.
1801 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1805 Ops.push_back(Chain);
1806 Ops.push_back(Callee);
1809 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1811 // Add argument registers to the end of the list so that they are known live
1813 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1814 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1815 RegsToPass[i].second.getValueType()));
1817 // Add an implicit use GOT pointer in EBX.
1818 if (!IsTailCall && !Is64Bit &&
1819 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1820 Subtarget->isPICStyleGOT())
1821 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1823 // Add an implicit use of AL for x86 vararg functions.
1824 if (Is64Bit && isVarArg)
1825 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1827 if (InFlag.getNode())
1828 Ops.push_back(InFlag);
1831 assert(InFlag.getNode() &&
1832 "Flag must be set. Depend on flag being set in LowerRET");
1833 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1834 TheCall->getVTList(), &Ops[0], Ops.size());
1836 return SDValue(Chain.getNode(), Op.getResNo());
1839 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1840 InFlag = Chain.getValue(1);
1842 // Create the CALLSEQ_END node.
1843 unsigned NumBytesForCalleeToPush;
1844 if (IsCalleePop(isVarArg, CC))
1845 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1846 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1847 // If this is is a call to a struct-return function, the callee
1848 // pops the hidden struct pointer, so we have to push it back.
1849 // This is common for Darwin/X86, Linux & Mingw32 targets.
1850 NumBytesForCalleeToPush = 4;
1852 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1854 // Returns a flag for retval copy to use.
1855 Chain = DAG.getCALLSEQ_END(Chain,
1856 DAG.getIntPtrConstant(NumBytes, true),
1857 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1860 InFlag = Chain.getValue(1);
1862 // Handle result values, copying them out of physregs into vregs that we
1864 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1869 //===----------------------------------------------------------------------===//
1870 // Fast Calling Convention (tail call) implementation
1871 //===----------------------------------------------------------------------===//
1873 // Like std call, callee cleans arguments, convention except that ECX is
1874 // reserved for storing the tail called function address. Only 2 registers are
1875 // free for argument passing (inreg). Tail call optimization is performed
1877 // * tailcallopt is enabled
1878 // * caller/callee are fastcc
1879 // On X86_64 architecture with GOT-style position independent code only local
1880 // (within module) calls are supported at the moment.
1881 // To keep the stack aligned according to platform abi the function
1882 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1883 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1884 // If a tail called function callee has more arguments than the caller the
1885 // caller needs to make sure that there is room to move the RETADDR to. This is
1886 // achieved by reserving an area the size of the argument delta right after the
1887 // original REtADDR, but before the saved framepointer or the spilled registers
1888 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1900 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1901 /// for a 16 byte align requirement.
1902 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1903 SelectionDAG& DAG) {
1904 MachineFunction &MF = DAG.getMachineFunction();
1905 const TargetMachine &TM = MF.getTarget();
1906 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1907 unsigned StackAlignment = TFI.getStackAlignment();
1908 uint64_t AlignMask = StackAlignment - 1;
1909 int64_t Offset = StackSize;
1910 uint64_t SlotSize = TD->getPointerSize();
1911 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1912 // Number smaller than 12 so just add the difference.
1913 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1915 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1916 Offset = ((~AlignMask) & Offset) + StackAlignment +
1917 (StackAlignment-SlotSize);
1922 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1923 /// following the call is a return. A function is eligible if caller/callee
1924 /// calling conventions match, currently only fastcc supports tail calls, and
1925 /// the function CALL is immediatly followed by a RET.
1926 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1928 SelectionDAG& DAG) const {
1929 if (!PerformTailCallOpt)
1932 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1933 MachineFunction &MF = DAG.getMachineFunction();
1934 unsigned CallerCC = MF.getFunction()->getCallingConv();
1935 unsigned CalleeCC= TheCall->getCallingConv();
1936 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1937 SDValue Callee = TheCall->getCallee();
1938 // On x86/32Bit PIC/GOT tail calls are supported.
1939 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1940 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1943 // Can only do local tail calls (in same module, hidden or protected) on
1944 // x86_64 PIC/GOT at the moment.
1945 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1946 return G->getGlobal()->hasHiddenVisibility()
1947 || G->getGlobal()->hasProtectedVisibility();
1955 X86TargetLowering::createFastISel(MachineFunction &mf,
1956 MachineModuleInfo *mmo,
1958 DenseMap<const Value *, unsigned> &vm,
1959 DenseMap<const BasicBlock *,
1960 MachineBasicBlock *> &bm,
1961 DenseMap<const AllocaInst *, int> &am
1963 , SmallSet<Instruction*, 8> &cil
1966 return X86::createFastISel(mf, mmo, dw, vm, bm, am
1974 //===----------------------------------------------------------------------===//
1975 // Other Lowering Hooks
1976 //===----------------------------------------------------------------------===//
1979 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1980 MachineFunction &MF = DAG.getMachineFunction();
1981 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1982 int ReturnAddrIndex = FuncInfo->getRAIndex();
1984 if (ReturnAddrIndex == 0) {
1985 // Set up a frame object for the return address.
1986 uint64_t SlotSize = TD->getPointerSize();
1987 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1988 FuncInfo->setRAIndex(ReturnAddrIndex);
1991 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1995 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
1996 /// specific condition code, returning the condition code and the LHS/RHS of the
1997 /// comparison to make.
1998 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1999 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2001 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2002 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2003 // X > -1 -> X == 0, jump !sign.
2004 RHS = DAG.getConstant(0, RHS.getValueType());
2005 return X86::COND_NS;
2006 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2007 // X < 0 -> X == 0, jump on sign.
2009 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2011 RHS = DAG.getConstant(0, RHS.getValueType());
2012 return X86::COND_LE;
2016 switch (SetCCOpcode) {
2017 default: assert(0 && "Invalid integer condition!");
2018 case ISD::SETEQ: return X86::COND_E;
2019 case ISD::SETGT: return X86::COND_G;
2020 case ISD::SETGE: return X86::COND_GE;
2021 case ISD::SETLT: return X86::COND_L;
2022 case ISD::SETLE: return X86::COND_LE;
2023 case ISD::SETNE: return X86::COND_NE;
2024 case ISD::SETULT: return X86::COND_B;
2025 case ISD::SETUGT: return X86::COND_A;
2026 case ISD::SETULE: return X86::COND_BE;
2027 case ISD::SETUGE: return X86::COND_AE;
2031 // First determine if it is required or is profitable to flip the operands.
2033 // If LHS is a foldable load, but RHS is not, flip the condition.
2034 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2035 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2036 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2037 std::swap(LHS, RHS);
2040 switch (SetCCOpcode) {
2046 std::swap(LHS, RHS);
2050 // On a floating point condition, the flags are set as follows:
2052 // 0 | 0 | 0 | X > Y
2053 // 0 | 0 | 1 | X < Y
2054 // 1 | 0 | 0 | X == Y
2055 // 1 | 1 | 1 | unordered
2056 switch (SetCCOpcode) {
2057 default: assert(0 && "Condcode should be pre-legalized away");
2059 case ISD::SETEQ: return X86::COND_E;
2060 case ISD::SETOLT: // flipped
2062 case ISD::SETGT: return X86::COND_A;
2063 case ISD::SETOLE: // flipped
2065 case ISD::SETGE: return X86::COND_AE;
2066 case ISD::SETUGT: // flipped
2068 case ISD::SETLT: return X86::COND_B;
2069 case ISD::SETUGE: // flipped
2071 case ISD::SETLE: return X86::COND_BE;
2073 case ISD::SETNE: return X86::COND_NE;
2074 case ISD::SETUO: return X86::COND_P;
2075 case ISD::SETO: return X86::COND_NP;
2079 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2080 /// code. Current x86 isa includes the following FP cmov instructions:
2081 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2082 static bool hasFPCMov(unsigned X86CC) {
2098 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2099 /// true if Op is undef or if its value falls within the specified range (L, H].
2100 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2101 if (Op.getOpcode() == ISD::UNDEF)
2104 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2105 return (Val >= Low && Val < Hi);
2108 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2109 /// true if Op is undef or if its value equal to the specified value.
2110 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2111 if (Op.getOpcode() == ISD::UNDEF)
2113 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2116 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2117 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2118 bool X86::isPSHUFDMask(SDNode *N) {
2119 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2121 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2124 // Check if the value doesn't reference the second vector.
2125 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2126 SDValue Arg = N->getOperand(i);
2127 if (Arg.getOpcode() == ISD::UNDEF) continue;
2128 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2129 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2136 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2137 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2138 bool X86::isPSHUFHWMask(SDNode *N) {
2139 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2141 if (N->getNumOperands() != 8)
2144 // Lower quadword copied in order.
2145 for (unsigned i = 0; i != 4; ++i) {
2146 SDValue Arg = N->getOperand(i);
2147 if (Arg.getOpcode() == ISD::UNDEF) continue;
2148 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2149 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2153 // Upper quadword shuffled.
2154 for (unsigned i = 4; i != 8; ++i) {
2155 SDValue Arg = N->getOperand(i);
2156 if (Arg.getOpcode() == ISD::UNDEF) continue;
2157 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2158 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2159 if (Val < 4 || Val > 7)
2166 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2167 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2168 bool X86::isPSHUFLWMask(SDNode *N) {
2169 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2171 if (N->getNumOperands() != 8)
2174 // Upper quadword copied in order.
2175 for (unsigned i = 4; i != 8; ++i)
2176 if (!isUndefOrEqual(N->getOperand(i), i))
2179 // Lower quadword shuffled.
2180 for (unsigned i = 0; i != 4; ++i)
2181 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2187 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2188 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2189 template<class SDOperand>
2190 static bool isSHUFPMask(SDOperand *Elems, unsigned NumElems) {
2191 if (NumElems != 2 && NumElems != 4) return false;
2193 unsigned Half = NumElems / 2;
2194 for (unsigned i = 0; i < Half; ++i)
2195 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2197 for (unsigned i = Half; i < NumElems; ++i)
2198 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2204 bool X86::isSHUFPMask(SDNode *N) {
2205 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2206 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2209 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2210 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2211 /// half elements to come from vector 1 (which would equal the dest.) and
2212 /// the upper half to come from vector 2.
2213 template<class SDOperand>
2214 static bool isCommutedSHUFP(SDOperand *Ops, unsigned NumOps) {
2215 if (NumOps != 2 && NumOps != 4) return false;
2217 unsigned Half = NumOps / 2;
2218 for (unsigned i = 0; i < Half; ++i)
2219 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2221 for (unsigned i = Half; i < NumOps; ++i)
2222 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2227 static bool isCommutedSHUFP(SDNode *N) {
2228 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2229 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2232 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2233 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2234 bool X86::isMOVHLPSMask(SDNode *N) {
2235 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2237 if (N->getNumOperands() != 4)
2240 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2241 return isUndefOrEqual(N->getOperand(0), 6) &&
2242 isUndefOrEqual(N->getOperand(1), 7) &&
2243 isUndefOrEqual(N->getOperand(2), 2) &&
2244 isUndefOrEqual(N->getOperand(3), 3);
2247 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2248 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2250 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2251 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2253 if (N->getNumOperands() != 4)
2256 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2257 return isUndefOrEqual(N->getOperand(0), 2) &&
2258 isUndefOrEqual(N->getOperand(1), 3) &&
2259 isUndefOrEqual(N->getOperand(2), 2) &&
2260 isUndefOrEqual(N->getOperand(3), 3);
2263 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2264 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2265 bool X86::isMOVLPMask(SDNode *N) {
2266 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2268 unsigned NumElems = N->getNumOperands();
2269 if (NumElems != 2 && NumElems != 4)
2272 for (unsigned i = 0; i < NumElems/2; ++i)
2273 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2276 for (unsigned i = NumElems/2; i < NumElems; ++i)
2277 if (!isUndefOrEqual(N->getOperand(i), i))
2283 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2284 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2286 bool X86::isMOVHPMask(SDNode *N) {
2287 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2289 unsigned NumElems = N->getNumOperands();
2290 if (NumElems != 2 && NumElems != 4)
2293 for (unsigned i = 0; i < NumElems/2; ++i)
2294 if (!isUndefOrEqual(N->getOperand(i), i))
2297 for (unsigned i = 0; i < NumElems/2; ++i) {
2298 SDValue Arg = N->getOperand(i + NumElems/2);
2299 if (!isUndefOrEqual(Arg, i + NumElems))
2306 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2307 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2308 template<class SDOperand>
2309 bool static isUNPCKLMask(SDOperand *Elts, unsigned NumElts,
2310 bool V2IsSplat = false) {
2311 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2314 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2315 SDValue BitI = Elts[i];
2316 SDValue BitI1 = Elts[i+1];
2317 if (!isUndefOrEqual(BitI, j))
2320 if (!isUndefOrEqual(BitI1, NumElts))
2323 if (!isUndefOrEqual(BitI1, j + NumElts))
2331 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2332 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2333 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2336 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2337 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2338 template<class SDOperand>
2339 bool static isUNPCKHMask(SDOperand *Elts, unsigned NumElts,
2340 bool V2IsSplat = false) {
2341 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2344 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2345 SDValue BitI = Elts[i];
2346 SDValue BitI1 = Elts[i+1];
2347 if (!isUndefOrEqual(BitI, j + NumElts/2))
2350 if (isUndefOrEqual(BitI1, NumElts))
2353 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2361 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2362 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2363 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2366 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2367 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2369 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2370 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2372 unsigned NumElems = N->getNumOperands();
2373 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2376 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2377 SDValue BitI = N->getOperand(i);
2378 SDValue BitI1 = N->getOperand(i+1);
2380 if (!isUndefOrEqual(BitI, j))
2382 if (!isUndefOrEqual(BitI1, j))
2389 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2390 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2392 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2393 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2395 unsigned NumElems = N->getNumOperands();
2396 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2399 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2400 SDValue BitI = N->getOperand(i);
2401 SDValue BitI1 = N->getOperand(i + 1);
2403 if (!isUndefOrEqual(BitI, j))
2405 if (!isUndefOrEqual(BitI1, j))
2412 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2413 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2414 /// MOVSD, and MOVD, i.e. setting the lowest element.
2415 template<class SDOperand>
2416 static bool isMOVLMask(SDOperand *Elts, unsigned NumElts) {
2417 if (NumElts != 2 && NumElts != 4)
2420 if (!isUndefOrEqual(Elts[0], NumElts))
2423 for (unsigned i = 1; i < NumElts; ++i) {
2424 if (!isUndefOrEqual(Elts[i], i))
2431 bool X86::isMOVLMask(SDNode *N) {
2432 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2433 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2436 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2437 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2438 /// element of vector 2 and the other elements to come from vector 1 in order.
2439 template<class SDOperand>
2440 static bool isCommutedMOVL(SDOperand *Ops, unsigned NumOps,
2441 bool V2IsSplat = false,
2442 bool V2IsUndef = false) {
2443 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2446 if (!isUndefOrEqual(Ops[0], 0))
2449 for (unsigned i = 1; i < NumOps; ++i) {
2450 SDValue Arg = Ops[i];
2451 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2452 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2453 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2460 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2461 bool V2IsUndef = false) {
2462 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2463 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2464 V2IsSplat, V2IsUndef);
2467 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2468 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2469 bool X86::isMOVSHDUPMask(SDNode *N) {
2470 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2472 if (N->getNumOperands() != 4)
2475 // Expect 1, 1, 3, 3
2476 for (unsigned i = 0; i < 2; ++i) {
2477 SDValue Arg = N->getOperand(i);
2478 if (Arg.getOpcode() == ISD::UNDEF) continue;
2479 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2480 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2481 if (Val != 1) return false;
2485 for (unsigned i = 2; i < 4; ++i) {
2486 SDValue Arg = N->getOperand(i);
2487 if (Arg.getOpcode() == ISD::UNDEF) continue;
2488 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2489 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2490 if (Val != 3) return false;
2494 // Don't use movshdup if it can be done with a shufps.
2498 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2499 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2500 bool X86::isMOVSLDUPMask(SDNode *N) {
2501 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2503 if (N->getNumOperands() != 4)
2506 // Expect 0, 0, 2, 2
2507 for (unsigned i = 0; i < 2; ++i) {
2508 SDValue Arg = N->getOperand(i);
2509 if (Arg.getOpcode() == ISD::UNDEF) continue;
2510 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2511 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2512 if (Val != 0) return false;
2516 for (unsigned i = 2; i < 4; ++i) {
2517 SDValue Arg = N->getOperand(i);
2518 if (Arg.getOpcode() == ISD::UNDEF) continue;
2519 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2520 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2521 if (Val != 2) return false;
2525 // Don't use movshdup if it can be done with a shufps.
2529 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2530 /// specifies a identity operation on the LHS or RHS.
2531 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2532 unsigned NumElems = N->getNumOperands();
2533 for (unsigned i = 0; i < NumElems; ++i)
2534 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2539 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2540 /// a splat of a single element.
2541 static bool isSplatMask(SDNode *N) {
2542 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2544 // This is a splat operation if each element of the permute is the same, and
2545 // if the value doesn't reference the second vector.
2546 unsigned NumElems = N->getNumOperands();
2547 SDValue ElementBase;
2549 for (; i != NumElems; ++i) {
2550 SDValue Elt = N->getOperand(i);
2551 if (isa<ConstantSDNode>(Elt)) {
2557 if (!ElementBase.getNode())
2560 for (; i != NumElems; ++i) {
2561 SDValue Arg = N->getOperand(i);
2562 if (Arg.getOpcode() == ISD::UNDEF) continue;
2563 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2564 if (Arg != ElementBase) return false;
2567 // Make sure it is a splat of the first vector operand.
2568 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2571 /// getSplatMaskEltNo - Given a splat mask, return the index to the element
2572 /// we want to splat.
2573 static SDValue getSplatMaskEltNo(SDNode *N) {
2574 assert(isSplatMask(N) && "Not a splat mask");
2575 unsigned NumElems = N->getNumOperands();
2576 SDValue ElementBase;
2578 for (; i != NumElems; ++i) {
2579 SDValue Elt = N->getOperand(i);
2580 if (isa<ConstantSDNode>(Elt))
2583 assert(0 && " No splat value found!");
2588 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2589 /// a splat of a single element and it's a 2 or 4 element mask.
2590 bool X86::isSplatMask(SDNode *N) {
2591 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2593 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2594 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2596 return ::isSplatMask(N);
2599 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2600 /// specifies a splat of zero element.
2601 bool X86::isSplatLoMask(SDNode *N) {
2602 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2604 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2605 if (!isUndefOrEqual(N->getOperand(i), 0))
2610 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2611 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2612 bool X86::isMOVDDUPMask(SDNode *N) {
2613 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2615 unsigned e = N->getNumOperands() / 2;
2616 for (unsigned i = 0; i < e; ++i)
2617 if (!isUndefOrEqual(N->getOperand(i), i))
2619 for (unsigned i = 0; i < e; ++i)
2620 if (!isUndefOrEqual(N->getOperand(e+i), i))
2625 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2626 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2628 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2629 unsigned NumOperands = N->getNumOperands();
2630 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2632 for (unsigned i = 0; i < NumOperands; ++i) {
2634 SDValue Arg = N->getOperand(NumOperands-i-1);
2635 if (Arg.getOpcode() != ISD::UNDEF)
2636 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2637 if (Val >= NumOperands) Val -= NumOperands;
2639 if (i != NumOperands - 1)
2646 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2647 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2649 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2651 // 8 nodes, but we only care about the last 4.
2652 for (unsigned i = 7; i >= 4; --i) {
2654 SDValue Arg = N->getOperand(i);
2655 if (Arg.getOpcode() != ISD::UNDEF) {
2656 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2666 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2667 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2669 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2671 // 8 nodes, but we only care about the first 4.
2672 for (int i = 3; i >= 0; --i) {
2674 SDValue Arg = N->getOperand(i);
2675 if (Arg.getOpcode() != ISD::UNDEF)
2676 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2685 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2686 /// specifies a 8 element shuffle that can be broken into a pair of
2687 /// PSHUFHW and PSHUFLW.
2688 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2689 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2691 if (N->getNumOperands() != 8)
2694 // Lower quadword shuffled.
2695 for (unsigned i = 0; i != 4; ++i) {
2696 SDValue Arg = N->getOperand(i);
2697 if (Arg.getOpcode() == ISD::UNDEF) continue;
2698 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2699 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2704 // Upper quadword shuffled.
2705 for (unsigned i = 4; i != 8; ++i) {
2706 SDValue Arg = N->getOperand(i);
2707 if (Arg.getOpcode() == ISD::UNDEF) continue;
2708 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2709 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2710 if (Val < 4 || Val > 7)
2717 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2718 /// values in ther permute mask.
2719 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2720 SDValue &V2, SDValue &Mask,
2721 SelectionDAG &DAG) {
2722 MVT VT = Op.getValueType();
2723 MVT MaskVT = Mask.getValueType();
2724 MVT EltVT = MaskVT.getVectorElementType();
2725 unsigned NumElems = Mask.getNumOperands();
2726 SmallVector<SDValue, 8> MaskVec;
2727 DebugLoc dl = Op.getNode()->getDebugLoc();
2729 for (unsigned i = 0; i != NumElems; ++i) {
2730 SDValue Arg = Mask.getOperand(i);
2731 if (Arg.getOpcode() == ISD::UNDEF) {
2732 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, EltVT));
2735 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2736 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2738 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2740 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2744 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2745 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
2748 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2749 /// the two vector operands have swapped position.
2751 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG, DebugLoc dl) {
2752 MVT MaskVT = Mask.getValueType();
2753 MVT EltVT = MaskVT.getVectorElementType();
2754 unsigned NumElems = Mask.getNumOperands();
2755 SmallVector<SDValue, 8> MaskVec;
2756 for (unsigned i = 0; i != NumElems; ++i) {
2757 SDValue Arg = Mask.getOperand(i);
2758 if (Arg.getOpcode() == ISD::UNDEF) {
2759 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, EltVT));
2762 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2763 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2765 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2767 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2769 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2773 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2774 /// match movhlps. The lower half elements should come from upper half of
2775 /// V1 (and in order), and the upper half elements should come from the upper
2776 /// half of V2 (and in order).
2777 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2778 unsigned NumElems = Mask->getNumOperands();
2781 for (unsigned i = 0, e = 2; i != e; ++i)
2782 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2784 for (unsigned i = 2; i != 4; ++i)
2785 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2790 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2791 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2793 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2794 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2796 N = N->getOperand(0).getNode();
2797 if (!ISD::isNON_EXTLoad(N))
2800 *LD = cast<LoadSDNode>(N);
2804 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2805 /// match movlp{s|d}. The lower half elements should come from lower half of
2806 /// V1 (and in order), and the upper half elements should come from the upper
2807 /// half of V2 (and in order). And since V1 will become the source of the
2808 /// MOVLP, it must be either a vector load or a scalar load to vector.
2809 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2810 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2812 // Is V2 is a vector load, don't do this transformation. We will try to use
2813 // load folding shufps op.
2814 if (ISD::isNON_EXTLoad(V2))
2817 unsigned NumElems = Mask->getNumOperands();
2818 if (NumElems != 2 && NumElems != 4)
2820 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2821 if (!isUndefOrEqual(Mask->getOperand(i), i))
2823 for (unsigned i = NumElems/2; i != NumElems; ++i)
2824 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2829 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2831 static bool isSplatVector(SDNode *N) {
2832 if (N->getOpcode() != ISD::BUILD_VECTOR)
2835 SDValue SplatValue = N->getOperand(0);
2836 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2837 if (N->getOperand(i) != SplatValue)
2842 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2844 static bool isUndefShuffle(SDNode *N) {
2845 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2848 SDValue V1 = N->getOperand(0);
2849 SDValue V2 = N->getOperand(1);
2850 SDValue Mask = N->getOperand(2);
2851 unsigned NumElems = Mask.getNumOperands();
2852 for (unsigned i = 0; i != NumElems; ++i) {
2853 SDValue Arg = Mask.getOperand(i);
2854 if (Arg.getOpcode() != ISD::UNDEF) {
2855 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2856 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2858 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2865 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2867 static inline bool isZeroNode(SDValue Elt) {
2868 return ((isa<ConstantSDNode>(Elt) &&
2869 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2870 (isa<ConstantFPSDNode>(Elt) &&
2871 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2874 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2875 /// to an zero vector.
2876 static bool isZeroShuffle(SDNode *N) {
2877 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2880 SDValue V1 = N->getOperand(0);
2881 SDValue V2 = N->getOperand(1);
2882 SDValue Mask = N->getOperand(2);
2883 unsigned NumElems = Mask.getNumOperands();
2884 for (unsigned i = 0; i != NumElems; ++i) {
2885 SDValue Arg = Mask.getOperand(i);
2886 if (Arg.getOpcode() == ISD::UNDEF)
2889 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2890 if (Idx < NumElems) {
2891 unsigned Opc = V1.getNode()->getOpcode();
2892 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2894 if (Opc != ISD::BUILD_VECTOR ||
2895 !isZeroNode(V1.getNode()->getOperand(Idx)))
2897 } else if (Idx >= NumElems) {
2898 unsigned Opc = V2.getNode()->getOpcode();
2899 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2901 if (Opc != ISD::BUILD_VECTOR ||
2902 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2909 /// getZeroVector - Returns a vector of specified type with all zero elements.
2911 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2913 assert(VT.isVector() && "Expected a vector type");
2915 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2916 // type. This ensures they get CSE'd.
2918 if (VT.getSizeInBits() == 64) { // MMX
2919 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2920 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2921 } else if (HasSSE2) { // SSE2
2922 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2923 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2925 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2926 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2928 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2931 /// getOnesVector - Returns a vector of specified type with all bits set.
2933 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2934 assert(VT.isVector() && "Expected a vector type");
2936 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2937 // type. This ensures they get CSE'd.
2938 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2940 if (VT.getSizeInBits() == 64) // MMX
2941 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2943 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2944 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2948 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2949 /// that point to V2 points to its first element.
2950 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2951 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2953 bool Changed = false;
2954 SmallVector<SDValue, 8> MaskVec;
2955 unsigned NumElems = Mask.getNumOperands();
2956 for (unsigned i = 0; i != NumElems; ++i) {
2957 SDValue Arg = Mask.getOperand(i);
2958 if (Arg.getOpcode() != ISD::UNDEF) {
2959 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2960 if (Val > NumElems) {
2961 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2965 MaskVec.push_back(Arg);
2969 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getNode()->getDebugLoc(),
2970 Mask.getValueType(),
2971 &MaskVec[0], MaskVec.size());
2975 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2976 /// operation of specified width.
2977 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG, DebugLoc dl) {
2978 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2979 MVT BaseVT = MaskVT.getVectorElementType();
2981 SmallVector<SDValue, 8> MaskVec;
2982 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2983 for (unsigned i = 1; i != NumElems; ++i)
2984 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2985 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
2986 &MaskVec[0], MaskVec.size());
2989 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2990 /// of specified width.
2991 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG,
2993 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2994 MVT BaseVT = MaskVT.getVectorElementType();
2995 SmallVector<SDValue, 8> MaskVec;
2996 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2997 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2998 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
3000 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3001 &MaskVec[0], MaskVec.size());
3004 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3005 /// of specified width.
3006 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG,
3008 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3009 MVT BaseVT = MaskVT.getVectorElementType();
3010 unsigned Half = NumElems/2;
3011 SmallVector<SDValue, 8> MaskVec;
3012 for (unsigned i = 0; i != Half; ++i) {
3013 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3014 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3016 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3017 &MaskVec[0], MaskVec.size());
3020 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
3021 /// element #0 of a vector with the specified index, leaving the rest of the
3022 /// elements in place.
3023 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
3024 SelectionDAG &DAG, DebugLoc dl) {
3025 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3026 MVT BaseVT = MaskVT.getVectorElementType();
3027 SmallVector<SDValue, 8> MaskVec;
3028 // Element #0 of the result gets the elt we are replacing.
3029 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
3030 for (unsigned i = 1; i != NumElems; ++i)
3031 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
3032 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3033 &MaskVec[0], MaskVec.size());
3036 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3037 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
3038 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
3039 MVT VT = Op.getValueType();
3042 SDValue V1 = Op.getOperand(0);
3043 SDValue Mask = Op.getOperand(2);
3044 unsigned MaskNumElems = Mask.getNumOperands();
3045 unsigned NumElems = MaskNumElems;
3046 DebugLoc dl = Op.getNode()->getDebugLoc();
3047 // Special handling of v4f32 -> v4i32.
3048 if (VT != MVT::v4f32) {
3049 // Find which element we want to splat.
3050 SDNode* EltNoNode = getSplatMaskEltNo(Mask.getNode()).getNode();
3051 unsigned EltNo = cast<ConstantSDNode>(EltNoNode)->getZExtValue();
3052 // unpack elements to the correct location
3053 while (NumElems > 4) {
3054 if (EltNo < NumElems/2) {
3055 Mask = getUnpacklMask(MaskNumElems, DAG, dl);
3057 Mask = getUnpackhMask(MaskNumElems, DAG, dl);
3058 EltNo -= NumElems/2;
3060 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1, Mask);
3063 SDValue Cst = DAG.getConstant(EltNo, MVT::i32);
3064 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3067 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3068 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3069 DAG.getNode(ISD::UNDEF, PVT), Mask);
3070 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3073 /// isVectorLoad - Returns true if the node is a vector load, a scalar
3074 /// load that's promoted to vector, or a load bitcasted.
3075 static bool isVectorLoad(SDValue Op) {
3076 assert(Op.getValueType().isVector() && "Expected a vector type");
3077 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
3078 Op.getOpcode() == ISD::BIT_CONVERT) {
3079 return isa<LoadSDNode>(Op.getOperand(0));
3081 return isa<LoadSDNode>(Op);
3085 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3087 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3088 SelectionDAG &DAG, bool HasSSE3) {
3089 // If we have sse3 and shuffle has more than one use or input is a load, then
3090 // use movddup. Otherwise, use movlhps.
3091 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3092 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3093 MVT VT = Op.getValueType();
3096 DebugLoc dl = Op.getNode()->getDebugLoc();
3097 unsigned NumElems = PVT.getVectorNumElements();
3098 if (NumElems == 2) {
3099 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3100 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3102 assert(NumElems == 4);
3103 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3104 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3105 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
3106 Cst0, Cst1, Cst0, Cst1);
3109 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3110 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3111 DAG.getNode(ISD::UNDEF, dl, PVT), Mask);
3112 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3115 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3116 /// vector of zero or undef vector. This produces a shuffle where the low
3117 /// element of V2 is swizzled into the zero/undef vector, landing at element
3118 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3119 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3120 bool isZero, bool HasSSE2,
3121 SelectionDAG &DAG) {
3122 DebugLoc dl = V2.getNode()->getDebugLoc();
3123 MVT VT = V2.getValueType();
3125 ? getZeroVector(VT, HasSSE2, DAG, dl) : DAG.getNode(ISD::UNDEF, dl, VT);
3126 unsigned NumElems = V2.getValueType().getVectorNumElements();
3127 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3128 MVT EVT = MaskVT.getVectorElementType();
3129 SmallVector<SDValue, 16> MaskVec;
3130 for (unsigned i = 0; i != NumElems; ++i)
3131 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3132 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3134 MaskVec.push_back(DAG.getConstant(i, EVT));
3135 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3136 &MaskVec[0], MaskVec.size());
3137 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
3140 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3141 /// a shuffle that is zero.
3143 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3144 unsigned NumElems, bool Low,
3145 SelectionDAG &DAG) {
3146 unsigned NumZeros = 0;
3147 for (unsigned i = 0; i < NumElems; ++i) {
3148 unsigned Index = Low ? i : NumElems-i-1;
3149 SDValue Idx = Mask.getOperand(Index);
3150 if (Idx.getOpcode() == ISD::UNDEF) {
3154 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3155 if (Elt.getNode() && isZeroNode(Elt))
3163 /// isVectorShift - Returns true if the shuffle can be implemented as a
3164 /// logical left or right shift of a vector.
3165 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3166 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3167 unsigned NumElems = Mask.getNumOperands();
3170 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3173 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3178 bool SeenV1 = false;
3179 bool SeenV2 = false;
3180 for (unsigned i = NumZeros; i < NumElems; ++i) {
3181 unsigned Val = isLeft ? (i - NumZeros) : i;
3182 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3183 if (Idx.getOpcode() == ISD::UNDEF)
3185 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3186 if (Index < NumElems)
3195 if (SeenV1 && SeenV2)
3198 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3204 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3206 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3207 unsigned NumNonZero, unsigned NumZero,
3208 SelectionDAG &DAG, TargetLowering &TLI) {
3212 DebugLoc dl = Op.getNode()->getDebugLoc();
3215 for (unsigned i = 0; i < 16; ++i) {
3216 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3217 if (ThisIsNonZero && First) {
3219 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3221 V = DAG.getNode(ISD::UNDEF, dl, MVT::v8i16);
3226 SDValue ThisElt(0, 0), LastElt(0, 0);
3227 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3228 if (LastIsNonZero) {
3229 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3230 MVT::i16, Op.getOperand(i-1));
3232 if (ThisIsNonZero) {
3233 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3234 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3235 ThisElt, DAG.getConstant(8, MVT::i8));
3237 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3241 if (ThisElt.getNode())
3242 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3243 DAG.getIntPtrConstant(i/2));
3247 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3250 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3252 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3253 unsigned NumNonZero, unsigned NumZero,
3254 SelectionDAG &DAG, TargetLowering &TLI) {
3258 DebugLoc dl = Op.getNode()->getDebugLoc();
3261 for (unsigned i = 0; i < 8; ++i) {
3262 bool isNonZero = (NonZeros & (1 << i)) != 0;
3266 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3268 V = DAG.getNode(ISD::UNDEF, dl, MVT::v8i16);
3271 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3272 MVT::v8i16, V, Op.getOperand(i),
3273 DAG.getIntPtrConstant(i));
3280 /// getVShift - Return a vector logical shift node.
3282 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3283 unsigned NumBits, SelectionDAG &DAG,
3284 const TargetLowering &TLI, DebugLoc dl) {
3285 bool isMMX = VT.getSizeInBits() == 64;
3286 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3287 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3288 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3289 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3290 DAG.getNode(Opc, dl, ShVT, SrcOp,
3291 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3295 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3296 DebugLoc dl = Op.getNode()->getDebugLoc();
3297 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3298 if (ISD::isBuildVectorAllZeros(Op.getNode())
3299 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3300 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3301 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3302 // eliminated on x86-32 hosts.
3303 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3306 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3307 return getOnesVector(Op.getValueType(), DAG, dl);
3308 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3311 MVT VT = Op.getValueType();
3312 MVT EVT = VT.getVectorElementType();
3313 unsigned EVTBits = EVT.getSizeInBits();
3315 unsigned NumElems = Op.getNumOperands();
3316 unsigned NumZero = 0;
3317 unsigned NumNonZero = 0;
3318 unsigned NonZeros = 0;
3319 bool IsAllConstants = true;
3320 SmallSet<SDValue, 8> Values;
3321 for (unsigned i = 0; i < NumElems; ++i) {
3322 SDValue Elt = Op.getOperand(i);
3323 if (Elt.getOpcode() == ISD::UNDEF)
3326 if (Elt.getOpcode() != ISD::Constant &&
3327 Elt.getOpcode() != ISD::ConstantFP)
3328 IsAllConstants = false;
3329 if (isZeroNode(Elt))
3332 NonZeros |= (1 << i);
3337 if (NumNonZero == 0) {
3338 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3339 return DAG.getNode(ISD::UNDEF, dl, VT);
3342 // Special case for single non-zero, non-undef, element.
3343 if (NumNonZero == 1 && NumElems <= 4) {
3344 unsigned Idx = CountTrailingZeros_32(NonZeros);
3345 SDValue Item = Op.getOperand(Idx);
3347 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3348 // the value are obviously zero, truncate the value to i32 and do the
3349 // insertion that way. Only do this if the value is non-constant or if the
3350 // value is a constant being inserted into element 0. It is cheaper to do
3351 // a constant pool load than it is to do a movd + shuffle.
3352 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3353 (!IsAllConstants || Idx == 0)) {
3354 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3355 // Handle MMX and SSE both.
3356 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3357 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3359 // Truncate the value (which may itself be a constant) to i32, and
3360 // convert it to a vector with movd (S2V+shuffle to zero extend).
3361 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3362 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3363 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3364 Subtarget->hasSSE2(), DAG);
3366 // Now we have our 32-bit value zero extended in the low element of
3367 // a vector. If Idx != 0, swizzle it into place.
3370 Item, DAG.getNode(ISD::UNDEF, dl, Item.getValueType()),
3371 getSwapEltZeroMask(VecElts, Idx, DAG, dl)
3373 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VecVT, Ops, 3);
3375 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3379 // If we have a constant or non-constant insertion into the low element of
3380 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3381 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3382 // depending on what the source datatype is. Because we can only get here
3383 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3385 // Don't do this for i64 values on x86-32.
3386 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3387 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3388 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3389 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3390 Subtarget->hasSSE2(), DAG);
3393 // Is it a vector logical left shift?
3394 if (NumElems == 2 && Idx == 1 &&
3395 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3396 unsigned NumBits = VT.getSizeInBits();
3397 return getVShift(true, VT,
3398 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3399 NumBits/2, DAG, *this, dl);
3402 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3405 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3406 // is a non-constant being inserted into an element other than the low one,
3407 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3408 // movd/movss) to move this into the low element, then shuffle it into
3410 if (EVTBits == 32) {
3411 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3413 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3414 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3415 Subtarget->hasSSE2(), DAG);
3416 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3417 MVT MaskEVT = MaskVT.getVectorElementType();
3418 SmallVector<SDValue, 8> MaskVec;
3419 for (unsigned i = 0; i < NumElems; i++)
3420 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3421 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3422 &MaskVec[0], MaskVec.size());
3423 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, Item,
3424 DAG.getNode(ISD::UNDEF, VT), Mask);
3428 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3429 if (Values.size() == 1)
3432 // A vector full of immediates; various special cases are already
3433 // handled, so this is best done with a single constant-pool load.
3437 // Let legalizer expand 2-wide build_vectors.
3438 if (EVTBits == 64) {
3439 if (NumNonZero == 1) {
3440 // One half is zero or undef.
3441 unsigned Idx = CountTrailingZeros_32(NonZeros);
3442 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3443 Op.getOperand(Idx));
3444 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3445 Subtarget->hasSSE2(), DAG);
3450 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3451 if (EVTBits == 8 && NumElems == 16) {
3452 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3454 if (V.getNode()) return V;
3457 if (EVTBits == 16 && NumElems == 8) {
3458 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3460 if (V.getNode()) return V;
3463 // If element VT is == 32 bits, turn it into a number of shuffles.
3464 SmallVector<SDValue, 8> V;
3466 if (NumElems == 4 && NumZero > 0) {
3467 for (unsigned i = 0; i < 4; ++i) {
3468 bool isZero = !(NonZeros & (1 << i));
3470 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3472 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3475 for (unsigned i = 0; i < 2; ++i) {
3476 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3479 V[i] = V[i*2]; // Must be a zero vector.
3482 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2+1], V[i*2],
3483 getMOVLMask(NumElems, DAG, dl));
3486 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3487 getMOVLMask(NumElems, DAG, dl));
3490 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3491 getUnpacklMask(NumElems, DAG, dl));
3496 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3497 MVT EVT = MaskVT.getVectorElementType();
3498 SmallVector<SDValue, 8> MaskVec;
3499 bool Reverse = (NonZeros & 0x3) == 2;
3500 for (unsigned i = 0; i < 2; ++i)
3502 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3504 MaskVec.push_back(DAG.getConstant(i, EVT));
3505 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3506 for (unsigned i = 0; i < 2; ++i)
3508 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3510 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3511 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3512 &MaskVec[0], MaskVec.size());
3513 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[0], V[1], ShufMask);
3516 if (Values.size() > 2) {
3517 // Expand into a number of unpckl*.
3519 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3520 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3521 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3522 SDValue UnpckMask = getUnpacklMask(NumElems, DAG, dl);
3523 for (unsigned i = 0; i < NumElems; ++i)
3524 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3526 while (NumElems != 0) {
3527 for (unsigned i = 0; i < NumElems; ++i)
3528 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i], V[i + NumElems],
3539 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3540 SDValue PermMask, SelectionDAG &DAG,
3541 TargetLowering &TLI, DebugLoc dl) {
3543 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3544 MVT MaskEVT = MaskVT.getVectorElementType();
3545 MVT PtrVT = TLI.getPointerTy();
3546 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3547 PermMask.getNode()->op_end());
3549 // First record which half of which vector the low elements come from.
3550 SmallVector<unsigned, 4> LowQuad(4);
3551 for (unsigned i = 0; i < 4; ++i) {
3552 SDValue Elt = MaskElts[i];
3553 if (Elt.getOpcode() == ISD::UNDEF)
3555 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3556 int QuadIdx = EltIdx / 4;
3560 int BestLowQuad = -1;
3561 unsigned MaxQuad = 1;
3562 for (unsigned i = 0; i < 4; ++i) {
3563 if (LowQuad[i] > MaxQuad) {
3565 MaxQuad = LowQuad[i];
3569 // Record which half of which vector the high elements come from.
3570 SmallVector<unsigned, 4> HighQuad(4);
3571 for (unsigned i = 4; i < 8; ++i) {
3572 SDValue Elt = MaskElts[i];
3573 if (Elt.getOpcode() == ISD::UNDEF)
3575 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3576 int QuadIdx = EltIdx / 4;
3577 ++HighQuad[QuadIdx];
3580 int BestHighQuad = -1;
3582 for (unsigned i = 0; i < 4; ++i) {
3583 if (HighQuad[i] > MaxQuad) {
3585 MaxQuad = HighQuad[i];
3589 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3590 if (BestLowQuad != -1 || BestHighQuad != -1) {
3591 // First sort the 4 chunks in order using shufpd.
3592 SmallVector<SDValue, 8> MaskVec;
3594 if (BestLowQuad != -1)
3595 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3597 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3599 if (BestHighQuad != -1)
3600 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3602 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3604 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, &MaskVec[0],2);
3605 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
3606 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3607 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), Mask);
3608 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3610 // Now sort high and low parts separately.
3611 BitVector InOrder(8);
3612 if (BestLowQuad != -1) {
3613 // Sort lower half in order using PSHUFLW.
3615 bool AnyOutOrder = false;
3617 for (unsigned i = 0; i != 4; ++i) {
3618 SDValue Elt = MaskElts[i];
3619 if (Elt.getOpcode() == ISD::UNDEF) {
3620 MaskVec.push_back(Elt);
3623 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3627 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3629 // If this element is in the right place after this shuffle, then
3631 if ((int)(EltIdx / 4) == BestLowQuad)
3636 for (unsigned i = 4; i != 8; ++i)
3637 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3638 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3640 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16,
3645 if (BestHighQuad != -1) {
3646 // Sort high half in order using PSHUFHW if possible.
3649 for (unsigned i = 0; i != 4; ++i)
3650 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3652 bool AnyOutOrder = false;
3653 for (unsigned i = 4; i != 8; ++i) {
3654 SDValue Elt = MaskElts[i];
3655 if (Elt.getOpcode() == ISD::UNDEF) {
3656 MaskVec.push_back(Elt);
3659 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3663 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3665 // If this element is in the right place after this shuffle, then
3667 if ((int)(EltIdx / 4) == BestHighQuad)
3673 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl,
3674 MaskVT, &MaskVec[0], 8);
3675 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16,
3680 // The other elements are put in the right place using pextrw and pinsrw.
3681 for (unsigned i = 0; i != 8; ++i) {
3684 SDValue Elt = MaskElts[i];
3685 if (Elt.getOpcode() == ISD::UNDEF)
3687 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3688 SDValue ExtOp = (EltIdx < 8)
3689 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3690 DAG.getConstant(EltIdx, PtrVT))
3691 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3692 DAG.getConstant(EltIdx - 8, PtrVT));
3693 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3694 DAG.getConstant(i, PtrVT));
3700 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3701 // few as possible. First, let's find out how many elements are already in the
3703 unsigned V1InOrder = 0;
3704 unsigned V1FromV1 = 0;
3705 unsigned V2InOrder = 0;
3706 unsigned V2FromV2 = 0;
3707 SmallVector<SDValue, 8> V1Elts;
3708 SmallVector<SDValue, 8> V2Elts;
3709 for (unsigned i = 0; i < 8; ++i) {
3710 SDValue Elt = MaskElts[i];
3711 if (Elt.getOpcode() == ISD::UNDEF) {
3712 V1Elts.push_back(Elt);
3713 V2Elts.push_back(Elt);
3718 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3720 V1Elts.push_back(Elt);
3721 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3723 } else if (EltIdx == i+8) {
3724 V1Elts.push_back(Elt);
3725 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3727 } else if (EltIdx < 8) {
3728 V1Elts.push_back(Elt);
3729 V2Elts.push_back(DAG.getConstant(EltIdx+8, MaskEVT));
3732 V1Elts.push_back(Elt);
3733 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3738 if (V2InOrder > V1InOrder) {
3739 PermMask = CommuteVectorShuffleMask(PermMask, DAG, dl);
3741 std::swap(V1Elts, V2Elts);
3742 std::swap(V1FromV1, V2FromV2);
3745 if ((V1FromV1 + V1InOrder) != 8) {
3746 // Some elements are from V2.
3748 // If there are elements that are from V1 but out of place,
3749 // then first sort them in place
3750 SmallVector<SDValue, 8> MaskVec;
3751 for (unsigned i = 0; i < 8; ++i) {
3752 SDValue Elt = V1Elts[i];
3753 if (Elt.getOpcode() == ISD::UNDEF) {
3754 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3757 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3759 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3761 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3763 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], 8);
3764 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, V1, V1, Mask);
3768 for (unsigned i = 0; i < 8; ++i) {
3769 SDValue Elt = V1Elts[i];
3770 if (Elt.getOpcode() == ISD::UNDEF)
3772 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3775 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3776 DAG.getConstant(EltIdx - 8, PtrVT));
3777 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3778 DAG.getConstant(i, PtrVT));
3782 // All elements are from V1.
3784 for (unsigned i = 0; i < 8; ++i) {
3785 SDValue Elt = V1Elts[i];
3786 if (Elt.getOpcode() == ISD::UNDEF)
3788 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3789 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3790 DAG.getConstant(EltIdx, PtrVT));
3791 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3792 DAG.getConstant(i, PtrVT));
3798 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3799 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3800 /// done when every pair / quad of shuffle mask elements point to elements in
3801 /// the right sequence. e.g.
3802 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3804 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3806 SDValue PermMask, SelectionDAG &DAG,
3807 TargetLowering &TLI, DebugLoc dl) {
3808 unsigned NumElems = PermMask.getNumOperands();
3809 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3810 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3811 MVT MaskEltVT = MaskVT.getVectorElementType();
3813 switch (VT.getSimpleVT()) {
3814 default: assert(false && "Unexpected!");
3815 case MVT::v4f32: NewVT = MVT::v2f64; break;
3816 case MVT::v4i32: NewVT = MVT::v2i64; break;
3817 case MVT::v8i16: NewVT = MVT::v4i32; break;
3818 case MVT::v16i8: NewVT = MVT::v4i32; break;
3821 if (NewWidth == 2) {
3827 unsigned Scale = NumElems / NewWidth;
3828 SmallVector<SDValue, 8> MaskVec;
3829 for (unsigned i = 0; i < NumElems; i += Scale) {
3830 unsigned StartIdx = ~0U;
3831 for (unsigned j = 0; j < Scale; ++j) {
3832 SDValue Elt = PermMask.getOperand(i+j);
3833 if (Elt.getOpcode() == ISD::UNDEF)
3835 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3836 if (StartIdx == ~0U)
3837 StartIdx = EltIdx - (EltIdx % Scale);
3838 if (EltIdx != StartIdx + j)
3841 if (StartIdx == ~0U)
3842 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEltVT));
3844 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3847 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3848 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3849 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, NewVT, V1, V2,
3850 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3851 &MaskVec[0], MaskVec.size()));
3854 /// getVZextMovL - Return a zero-extending vector move low node.
3856 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3857 SDValue SrcOp, SelectionDAG &DAG,
3858 const X86Subtarget *Subtarget, DebugLoc dl) {
3859 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3860 LoadSDNode *LD = NULL;
3861 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3862 LD = dyn_cast<LoadSDNode>(SrcOp);
3864 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3866 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3867 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3868 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3869 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3870 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3872 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3873 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3874 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3875 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3883 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3884 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3885 DAG.getNode(ISD::BIT_CONVERT, dl,
3889 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3892 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3893 SDValue PermMask, MVT VT, SelectionDAG &DAG,
3895 MVT MaskVT = PermMask.getValueType();
3896 MVT MaskEVT = MaskVT.getVectorElementType();
3897 SmallVector<std::pair<int, int>, 8> Locs;
3899 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3902 for (unsigned i = 0; i != 4; ++i) {
3903 SDValue Elt = PermMask.getOperand(i);
3904 if (Elt.getOpcode() == ISD::UNDEF) {
3905 Locs[i] = std::make_pair(-1, -1);
3907 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3908 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3910 Locs[i] = std::make_pair(0, NumLo);
3914 Locs[i] = std::make_pair(1, NumHi);
3916 Mask1[2+NumHi] = Elt;
3922 if (NumLo <= 2 && NumHi <= 2) {
3923 // If no more than two elements come from either vector. This can be
3924 // implemented with two shuffles. First shuffle gather the elements.
3925 // The second shuffle, which takes the first shuffle as both of its
3926 // vector operands, put the elements into the right order.
3927 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3928 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3929 &Mask1[0], Mask1.size()));
3931 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3932 for (unsigned i = 0; i != 4; ++i) {
3933 if (Locs[i].first == -1)
3936 unsigned Idx = (i < 2) ? 0 : 4;
3937 Idx += Locs[i].first * 2 + Locs[i].second;
3938 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3942 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1,
3943 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3944 &Mask2[0], Mask2.size()));
3945 } else if (NumLo == 3 || NumHi == 3) {
3946 // Otherwise, we must have three elements from one vector, call it X, and
3947 // one element from the other, call it Y. First, use a shufps to build an
3948 // intermediate vector with the one element from Y and the element from X
3949 // that will be in the same half in the final destination (the indexes don't
3950 // matter). Then, use a shufps to build the final vector, taking the half
3951 // containing the element from Y from the intermediate, and the other half
3954 // Normalize it so the 3 elements come from V1.
3955 PermMask = CommuteVectorShuffleMask(PermMask, DAG, dl);
3959 // Find the element from V2.
3961 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3962 SDValue Elt = PermMask.getOperand(HiIndex);
3963 if (Elt.getOpcode() == ISD::UNDEF)
3965 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3970 Mask1[0] = PermMask.getOperand(HiIndex);
3971 Mask1[1] = DAG.getNode(ISD::UNDEF, dl, MaskEVT);
3972 Mask1[2] = PermMask.getOperand(HiIndex^1);
3973 Mask1[3] = DAG.getNode(ISD::UNDEF, dl, MaskEVT);
3974 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3975 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3978 Mask1[0] = PermMask.getOperand(0);
3979 Mask1[1] = PermMask.getOperand(1);
3980 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3981 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3982 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3983 DAG.getNode(ISD::BUILD_VECTOR, dl,
3984 MaskVT, &Mask1[0], 4));
3986 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3987 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3988 Mask1[2] = PermMask.getOperand(2);
3989 Mask1[3] = PermMask.getOperand(3);
3990 if (Mask1[2].getOpcode() != ISD::UNDEF)
3992 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3994 if (Mask1[3].getOpcode() != ISD::UNDEF)
3996 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3998 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V2, V1,
3999 DAG.getNode(ISD::BUILD_VECTOR, dl,
4000 MaskVT, &Mask1[0], 4));
4004 // Break it into (shuffle shuffle_hi, shuffle_lo).
4006 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
4007 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
4008 SmallVector<SDValue,8> *MaskPtr = &LoMask;
4009 unsigned MaskIdx = 0;
4012 for (unsigned i = 0; i != 4; ++i) {
4019 SDValue Elt = PermMask.getOperand(i);
4020 if (Elt.getOpcode() == ISD::UNDEF) {
4021 Locs[i] = std::make_pair(-1, -1);
4022 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
4023 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4024 (*MaskPtr)[LoIdx] = Elt;
4027 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4028 (*MaskPtr)[HiIdx] = Elt;
4033 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4034 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4035 &LoMask[0], LoMask.size()));
4036 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4037 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4038 &HiMask[0], HiMask.size()));
4039 SmallVector<SDValue, 8> MaskOps;
4040 for (unsigned i = 0; i != 4; ++i) {
4041 if (Locs[i].first == -1) {
4042 MaskOps.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
4044 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4045 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
4048 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, LoShuffle, HiShuffle,
4049 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4050 &MaskOps[0], MaskOps.size()));
4054 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4055 SDValue V1 = Op.getOperand(0);
4056 SDValue V2 = Op.getOperand(1);
4057 SDValue PermMask = Op.getOperand(2);
4058 MVT VT = Op.getValueType();
4059 DebugLoc dl = Op.getNode()->getDebugLoc();
4060 unsigned NumElems = PermMask.getNumOperands();
4061 bool isMMX = VT.getSizeInBits() == 64;
4062 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4063 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4064 bool V1IsSplat = false;
4065 bool V2IsSplat = false;
4067 if (isUndefShuffle(Op.getNode()))
4068 return DAG.getNode(ISD::UNDEF, dl, VT);
4070 if (isZeroShuffle(Op.getNode()))
4071 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4073 if (isIdentityMask(PermMask.getNode()))
4075 else if (isIdentityMask(PermMask.getNode(), true))
4078 // Canonicalize movddup shuffles.
4079 if (V2IsUndef && Subtarget->hasSSE2() &&
4080 VT.getSizeInBits() == 128 &&
4081 X86::isMOVDDUPMask(PermMask.getNode()))
4082 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
4084 if (isSplatMask(PermMask.getNode())) {
4085 if (isMMX || NumElems < 4) return Op;
4086 // Promote it to a v4{if}32 splat.
4087 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
4090 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4092 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4093 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG,
4095 if (NewOp.getNode())
4096 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4097 LowerVECTOR_SHUFFLE(NewOp, DAG));
4098 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4099 // FIXME: Figure out a cleaner way to do this.
4100 // Try to make use of movq to zero out the top part.
4101 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4102 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4104 if (NewOp.getNode()) {
4105 SDValue NewV1 = NewOp.getOperand(0);
4106 SDValue NewV2 = NewOp.getOperand(1);
4107 SDValue NewMask = NewOp.getOperand(2);
4108 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4109 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4110 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget,
4114 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4115 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4117 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4118 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4119 DAG, Subtarget, dl);
4123 // Check if this can be converted into a logical shift.
4124 bool isLeft = false;
4127 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4128 if (isShift && ShVal.hasOneUse()) {
4129 // If the shifted value has multiple uses, it may be cheaper to use
4130 // v_set0 + movlhps or movhlps, etc.
4131 MVT EVT = VT.getVectorElementType();
4132 ShAmt *= EVT.getSizeInBits();
4133 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4136 if (X86::isMOVLMask(PermMask.getNode())) {
4139 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4140 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4145 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4146 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4147 X86::isMOVHLPSMask(PermMask.getNode()) ||
4148 X86::isMOVHPMask(PermMask.getNode()) ||
4149 X86::isMOVLPMask(PermMask.getNode())))
4152 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4153 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4154 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4157 // No better options. Use a vshl / vsrl.
4158 MVT EVT = VT.getVectorElementType();
4159 ShAmt *= EVT.getSizeInBits();
4160 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4163 bool Commuted = false;
4164 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4165 // 1,1,1,1 -> v8i16 though.
4166 V1IsSplat = isSplatVector(V1.getNode());
4167 V2IsSplat = isSplatVector(V2.getNode());
4169 // Canonicalize the splat or undef, if present, to be on the RHS.
4170 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4171 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4172 std::swap(V1IsSplat, V2IsSplat);
4173 std::swap(V1IsUndef, V2IsUndef);
4177 // FIXME: Figure out a cleaner way to do this.
4178 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4179 if (V2IsUndef) return V1;
4180 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4182 // V2 is a splat, so the mask may be malformed. That is, it may point
4183 // to any V2 element. The instruction selectior won't like this. Get
4184 // a corrected mask and commute to form a proper MOVS{S|D}.
4185 SDValue NewMask = getMOVLMask(NumElems, DAG, dl);
4186 if (NewMask.getNode() != PermMask.getNode())
4187 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4192 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4193 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4194 X86::isUNPCKLMask(PermMask.getNode()) ||
4195 X86::isUNPCKHMask(PermMask.getNode()))
4199 // Normalize mask so all entries that point to V2 points to its first
4200 // element then try to match unpck{h|l} again. If match, return a
4201 // new vector_shuffle with the corrected mask.
4202 SDValue NewMask = NormalizeMask(PermMask, DAG);
4203 if (NewMask.getNode() != PermMask.getNode()) {
4204 if (X86::isUNPCKLMask(NewMask.getNode(), true)) {
4205 SDValue NewMask = getUnpacklMask(NumElems, DAG, dl);
4206 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4207 } else if (X86::isUNPCKHMask(NewMask.getNode(), true)) {
4208 SDValue NewMask = getUnpackhMask(NumElems, DAG, dl);
4209 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4214 // Normalize the node to match x86 shuffle ops if needed
4215 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4216 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4219 // Commute is back and try unpck* again.
4220 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4221 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4222 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4223 X86::isUNPCKLMask(PermMask.getNode()) ||
4224 X86::isUNPCKHMask(PermMask.getNode()))
4228 // Try PSHUF* first, then SHUFP*.
4229 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4230 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4231 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4232 if (V2.getOpcode() != ISD::UNDEF)
4233 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1,
4234 DAG.getNode(ISD::UNDEF, VT), PermMask);
4239 if (Subtarget->hasSSE2() &&
4240 (X86::isPSHUFDMask(PermMask.getNode()) ||
4241 X86::isPSHUFHWMask(PermMask.getNode()) ||
4242 X86::isPSHUFLWMask(PermMask.getNode()))) {
4244 if (VT == MVT::v4f32) {
4246 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT,
4247 DAG.getNode(ISD::BIT_CONVERT, dl, RVT, V1),
4248 DAG.getNode(ISD::UNDEF, dl, RVT), PermMask);
4249 } else if (V2.getOpcode() != ISD::UNDEF)
4250 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT, V1,
4251 DAG.getNode(ISD::UNDEF, dl, RVT), PermMask);
4253 Op = DAG.getNode(ISD::BIT_CONVERT, dl, VT, Op);
4257 // Binary or unary shufps.
4258 if (X86::isSHUFPMask(PermMask.getNode()) ||
4259 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4263 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4264 if (VT == MVT::v8i16) {
4265 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this, dl);
4266 if (NewOp.getNode())
4270 // Handle all 4 wide cases with a number of shuffles except for MMX.
4271 if (NumElems == 4 && !isMMX)
4272 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG, dl);
4278 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4279 SelectionDAG &DAG) {
4280 MVT VT = Op.getValueType();
4281 DebugLoc dl = Op.getNode()->getDebugLoc();
4282 if (VT.getSizeInBits() == 8) {
4283 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4284 Op.getOperand(0), Op.getOperand(1));
4285 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4286 DAG.getValueType(VT));
4287 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4288 } else if (VT.getSizeInBits() == 16) {
4289 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4290 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4292 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4293 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4294 DAG.getNode(ISD::BIT_CONVERT, dl,
4298 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4299 Op.getOperand(0), Op.getOperand(1));
4300 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4301 DAG.getValueType(VT));
4302 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4303 } else if (VT == MVT::f32) {
4304 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4305 // the result back to FR32 register. It's only worth matching if the
4306 // result has a single use which is a store or a bitcast to i32. And in
4307 // the case of a store, it's not worth it if the index is a constant 0,
4308 // because a MOVSSmr can be used instead, which is smaller and faster.
4309 if (!Op.hasOneUse())
4311 SDNode *User = *Op.getNode()->use_begin();
4312 if ((User->getOpcode() != ISD::STORE ||
4313 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4314 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4315 (User->getOpcode() != ISD::BIT_CONVERT ||
4316 User->getValueType(0) != MVT::i32))
4318 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4319 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4322 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4323 } else if (VT == MVT::i32) {
4324 // ExtractPS works with constant index.
4325 if (isa<ConstantSDNode>(Op.getOperand(1)))
4333 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4334 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4337 if (Subtarget->hasSSE41()) {
4338 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4343 MVT VT = Op.getValueType();
4344 DebugLoc dl = Op.getNode()->getDebugLoc();
4345 // TODO: handle v16i8.
4346 if (VT.getSizeInBits() == 16) {
4347 SDValue Vec = Op.getOperand(0);
4348 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4350 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4351 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4352 DAG.getNode(ISD::BIT_CONVERT, dl,
4355 // Transform it so it match pextrw which produces a 32-bit result.
4356 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4357 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4358 Op.getOperand(0), Op.getOperand(1));
4359 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4360 DAG.getValueType(VT));
4361 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4362 } else if (VT.getSizeInBits() == 32) {
4363 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4366 // SHUFPS the element to the lowest double word, then movss.
4367 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4368 SmallVector<SDValue, 8> IdxVec;
4370 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4372 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4374 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4376 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4377 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4378 &IdxVec[0], IdxVec.size());
4379 SDValue Vec = Op.getOperand(0);
4380 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4381 Vec, DAG.getNode(ISD::UNDEF, dl, Vec.getValueType()),
4383 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4384 DAG.getIntPtrConstant(0));
4385 } else if (VT.getSizeInBits() == 64) {
4386 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4387 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4388 // to match extract_elt for f64.
4389 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4393 // UNPCKHPD the element to the lowest double word, then movsd.
4394 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4395 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4396 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4397 SmallVector<SDValue, 8> IdxVec;
4398 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4400 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4401 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4402 &IdxVec[0], IdxVec.size());
4403 SDValue Vec = Op.getOperand(0);
4404 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4405 Vec, DAG.getNode(ISD::UNDEF, dl, Vec.getValueType()),
4407 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4408 DAG.getIntPtrConstant(0));
4415 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4416 MVT VT = Op.getValueType();
4417 MVT EVT = VT.getVectorElementType();
4418 DebugLoc dl = Op.getNode()->getDebugLoc();
4420 SDValue N0 = Op.getOperand(0);
4421 SDValue N1 = Op.getOperand(1);
4422 SDValue N2 = Op.getOperand(2);
4424 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4425 isa<ConstantSDNode>(N2)) {
4426 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4428 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4430 if (N1.getValueType() != MVT::i32)
4431 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4432 if (N2.getValueType() != MVT::i32)
4433 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4434 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4435 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4436 // Bits [7:6] of the constant are the source select. This will always be
4437 // zero here. The DAG Combiner may combine an extract_elt index into these
4438 // bits. For example (insert (extract, 3), 2) could be matched by putting
4439 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4440 // Bits [5:4] of the constant are the destination select. This is the
4441 // value of the incoming immediate.
4442 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4443 // combine either bitwise AND or insert of float 0.0 to set these bits.
4444 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4445 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4446 } else if (EVT == MVT::i32) {
4447 // InsertPS works with constant index.
4448 if (isa<ConstantSDNode>(N2))
4455 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4456 MVT VT = Op.getValueType();
4457 MVT EVT = VT.getVectorElementType();
4459 if (Subtarget->hasSSE41())
4460 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4465 DebugLoc dl = Op.getNode()->getDebugLoc();
4466 SDValue N0 = Op.getOperand(0);
4467 SDValue N1 = Op.getOperand(1);
4468 SDValue N2 = Op.getOperand(2);
4470 if (EVT.getSizeInBits() == 16) {
4471 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4472 // as its second argument.
4473 if (N1.getValueType() != MVT::i32)
4474 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4475 if (N2.getValueType() != MVT::i32)
4476 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4477 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4483 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4484 DebugLoc dl = Op.getNode()->getDebugLoc();
4485 if (Op.getValueType() == MVT::v2f32)
4486 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4487 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4488 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4489 Op.getOperand(0))));
4491 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4492 MVT VT = MVT::v2i32;
4493 switch (Op.getValueType().getSimpleVT()) {
4500 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4501 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4504 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4505 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4506 // one of the above mentioned nodes. It has to be wrapped because otherwise
4507 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4508 // be used to form addressing mode. These wrapped nodes will be selected
4511 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4512 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4513 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4515 CP->getAlignment());
4516 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4517 // With PIC, the address is actually $g + Offset.
4518 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4519 !Subtarget->isPICStyleRIPRel()) {
4520 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4521 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4529 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
4531 SelectionDAG &DAG) const {
4532 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4533 bool ExtraLoadRequired =
4534 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4536 // Create the TargetGlobalAddress node, folding in the constant
4537 // offset if it is legal.
4539 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4540 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4543 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4544 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4546 // With PIC, the address is actually $g + Offset.
4547 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4548 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4549 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4553 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4554 // load the value at address GV, not the value of GV itself. This means that
4555 // the GlobalAddress must be in the base or index register of the address, not
4556 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4557 // The same applies for external symbols during PIC codegen
4558 if (ExtraLoadRequired)
4559 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4560 PseudoSourceValue::getGOT(), 0);
4562 // If there was a non-zero offset that we didn't fold, create an explicit
4565 Result = DAG.getNode(ISD::ADD, getPointerTy(), Result,
4566 DAG.getConstant(Offset, getPointerTy()));
4572 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4573 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4574 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4575 return LowerGlobalAddress(GV, Offset, DAG);
4578 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4580 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4583 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4584 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4585 DAG.getNode(X86ISD::GlobalBaseReg,
4587 InFlag = Chain.getValue(1);
4589 // emit leal symbol@TLSGD(,%ebx,1), %eax
4590 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4591 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4592 GA->getValueType(0),
4594 SDValue Ops[] = { Chain, TGA, InFlag };
4595 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4596 InFlag = Result.getValue(2);
4597 Chain = Result.getValue(1);
4599 // call ___tls_get_addr. This function receives its argument in
4600 // the register EAX.
4601 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Result, InFlag);
4602 InFlag = Chain.getValue(1);
4604 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4605 SDValue Ops1[] = { Chain,
4606 DAG.getTargetExternalSymbol("___tls_get_addr",
4608 DAG.getRegister(X86::EAX, PtrVT),
4609 DAG.getRegister(X86::EBX, PtrVT),
4611 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4612 InFlag = Chain.getValue(1);
4614 return DAG.getCopyFromReg(Chain, dl, X86::EAX, PtrVT, InFlag);
4617 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4619 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4621 SDValue InFlag, Chain;
4622 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4624 // emit leaq symbol@TLSGD(%rip), %rdi
4625 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4626 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4627 GA->getValueType(0),
4629 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4630 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4631 Chain = Result.getValue(1);
4632 InFlag = Result.getValue(2);
4634 // call __tls_get_addr. This function receives its argument in
4635 // the register RDI.
4636 Chain = DAG.getCopyToReg(Chain, dl, X86::RDI, Result, InFlag);
4637 InFlag = Chain.getValue(1);
4639 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4640 SDValue Ops1[] = { Chain,
4641 DAG.getTargetExternalSymbol("__tls_get_addr",
4643 DAG.getRegister(X86::RDI, PtrVT),
4645 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4646 InFlag = Chain.getValue(1);
4648 return DAG.getCopyFromReg(Chain, dl, X86::RAX, PtrVT, InFlag);
4651 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4652 // "local exec" model.
4653 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4655 // Get the Thread Pointer
4656 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4657 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4659 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4660 GA->getValueType(0),
4662 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4664 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4665 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4666 PseudoSourceValue::getGOT(), 0);
4668 // The address of the thread local variable is the add of the thread
4669 // pointer with the offset of the variable.
4670 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4674 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4675 // TODO: implement the "local dynamic" model
4676 // TODO: implement the "initial exec"model for pic executables
4677 assert(Subtarget->isTargetELF() &&
4678 "TLS not implemented for non-ELF targets");
4679 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4680 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4681 // otherwise use the "Local Exec"TLS Model
4682 if (Subtarget->is64Bit()) {
4683 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4685 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4686 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4688 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4693 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4694 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4695 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4696 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4697 // With PIC, the address is actually $g + Offset.
4698 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4699 !Subtarget->isPICStyleRIPRel()) {
4700 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4701 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4708 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4709 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4710 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4711 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4712 // With PIC, the address is actually $g + Offset.
4713 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4714 !Subtarget->isPICStyleRIPRel()) {
4715 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4716 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4723 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4724 /// take a 2 x i32 value to shift plus a shift amount.
4725 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4726 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4727 MVT VT = Op.getValueType();
4728 unsigned VTBits = VT.getSizeInBits();
4729 DebugLoc dl = Op.getNode()->getDebugLoc();
4730 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4731 SDValue ShOpLo = Op.getOperand(0);
4732 SDValue ShOpHi = Op.getOperand(1);
4733 SDValue ShAmt = Op.getOperand(2);
4734 SDValue Tmp1 = isSRA ?
4735 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4736 DAG.getConstant(VTBits - 1, MVT::i8)) :
4737 DAG.getConstant(0, VT);
4740 if (Op.getOpcode() == ISD::SHL_PARTS) {
4741 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4742 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4744 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4745 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4748 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4749 DAG.getConstant(VTBits, MVT::i8));
4750 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4751 AndNode, DAG.getConstant(0, MVT::i8));
4754 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4755 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4756 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4758 if (Op.getOpcode() == ISD::SHL_PARTS) {
4759 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4760 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4762 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4763 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4766 SDValue Ops[2] = { Lo, Hi };
4767 return DAG.getMergeValues(Ops, 2, dl);
4770 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4771 MVT SrcVT = Op.getOperand(0).getValueType();
4772 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4773 "Unknown SINT_TO_FP to lower!");
4775 // These are really Legal; caller falls through into that case.
4776 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4778 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4779 Subtarget->is64Bit())
4782 DebugLoc dl = Op.getNode()->getDebugLoc();
4783 unsigned Size = SrcVT.getSizeInBits()/8;
4784 MachineFunction &MF = DAG.getMachineFunction();
4785 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4786 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4787 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4789 PseudoSourceValue::getFixedStack(SSFI), 0);
4793 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4795 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4797 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4798 SmallVector<SDValue, 8> Ops;
4799 Ops.push_back(Chain);
4800 Ops.push_back(StackSlot);
4801 Ops.push_back(DAG.getValueType(SrcVT));
4802 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4803 Tys, &Ops[0], Ops.size());
4806 Chain = Result.getValue(1);
4807 SDValue InFlag = Result.getValue(2);
4809 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4810 // shouldn't be necessary except that RFP cannot be live across
4811 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4812 MachineFunction &MF = DAG.getMachineFunction();
4813 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4814 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4815 Tys = DAG.getVTList(MVT::Other);
4816 SmallVector<SDValue, 8> Ops;
4817 Ops.push_back(Chain);
4818 Ops.push_back(Result);
4819 Ops.push_back(StackSlot);
4820 Ops.push_back(DAG.getValueType(Op.getValueType()));
4821 Ops.push_back(InFlag);
4822 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4823 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4824 PseudoSourceValue::getFixedStack(SSFI), 0);
4830 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4831 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4832 // This algorithm is not obvious. Here it is in C code, more or less:
4834 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4835 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4836 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4838 // Copy ints to xmm registers.
4839 __m128i xh = _mm_cvtsi32_si128( hi );
4840 __m128i xl = _mm_cvtsi32_si128( lo );
4842 // Combine into low half of a single xmm register.
4843 __m128i x = _mm_unpacklo_epi32( xh, xl );
4847 // Merge in appropriate exponents to give the integer bits the right
4849 x = _mm_unpacklo_epi32( x, exp );
4851 // Subtract away the biases to deal with the IEEE-754 double precision
4853 d = _mm_sub_pd( (__m128d) x, bias );
4855 // All conversions up to here are exact. The correctly rounded result is
4856 // calculated using the current rounding mode using the following
4858 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4859 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4860 // store doesn't really need to be here (except
4861 // maybe to zero the other double)
4866 DebugLoc dl = Op.getNode()->getDebugLoc();
4868 // Build some magic constants.
4869 std::vector<Constant*> CV0;
4870 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4871 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4872 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4873 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4874 Constant *C0 = ConstantVector::get(CV0);
4875 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
4877 std::vector<Constant*> CV1;
4878 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4879 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4880 Constant *C1 = ConstantVector::get(CV1);
4881 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
4883 SmallVector<SDValue, 4> MaskVec;
4884 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
4885 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
4886 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
4887 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
4888 SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4889 &MaskVec[0], MaskVec.size());
4890 SmallVector<SDValue, 4> MaskVec2;
4891 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
4892 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
4893 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32,
4894 &MaskVec2[0], MaskVec2.size());
4896 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4897 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4899 DAG.getIntPtrConstant(1)));
4900 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4901 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4903 DAG.getIntPtrConstant(0)));
4904 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
4905 XR1, XR2, UnpcklMask);
4906 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4907 PseudoSourceValue::getConstantPool(), 0,
4909 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
4910 Unpck1, CLod0, UnpcklMask);
4911 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4912 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4913 PseudoSourceValue::getConstantPool(), 0,
4915 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4917 // Add the halves; easiest way is to swap them into another reg first.
4918 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2f64,
4919 Sub, Sub, ShufMask);
4920 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4921 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4922 DAG.getIntPtrConstant(0));
4925 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4926 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4927 DebugLoc dl = Op.getNode()->getDebugLoc();
4928 // FP constant to bias correct the final result.
4929 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4932 // Load the 32-bit value into an XMM register.
4933 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4934 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4936 DAG.getIntPtrConstant(0)));
4938 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4939 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4940 DAG.getIntPtrConstant(0));
4942 // Or the load with the bias.
4943 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4944 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4945 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4947 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4948 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4949 MVT::v2f64, Bias)));
4950 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4951 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4952 DAG.getIntPtrConstant(0));
4954 // Subtract the bias.
4955 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4957 // Handle final rounding.
4958 MVT DestVT = Op.getValueType();
4960 if (DestVT.bitsLT(MVT::f64)) {
4961 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4962 DAG.getIntPtrConstant(0));
4963 } else if (DestVT.bitsGT(MVT::f64)) {
4964 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4967 // Handle final rounding.
4971 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4972 SDValue N0 = Op.getOperand(0);
4973 DebugLoc dl = Op.getNode()->getDebugLoc();
4975 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4976 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4977 // the optimization here.
4978 if (DAG.SignBitIsZero(N0))
4979 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4981 MVT SrcVT = N0.getValueType();
4982 if (SrcVT == MVT::i64) {
4983 // We only handle SSE2 f64 target here; caller can handle the rest.
4984 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4987 return LowerUINT_TO_FP_i64(Op, DAG);
4988 } else if (SrcVT == MVT::i32) {
4989 return LowerUINT_TO_FP_i32(Op, DAG);
4992 assert(0 && "Unknown UINT_TO_FP to lower!");
4996 std::pair<SDValue,SDValue> X86TargetLowering::
4997 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4998 DebugLoc dl = Op.getNode()->getDebugLoc();
4999 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
5000 Op.getValueType().getSimpleVT() >= MVT::i16 &&
5001 "Unknown FP_TO_SINT to lower!");
5003 // These are really Legal.
5004 if (Op.getValueType() == MVT::i32 &&
5005 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5006 return std::make_pair(SDValue(), SDValue());
5007 if (Subtarget->is64Bit() &&
5008 Op.getValueType() == MVT::i64 &&
5009 Op.getOperand(0).getValueType() != MVT::f80)
5010 return std::make_pair(SDValue(), SDValue());
5012 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5014 MachineFunction &MF = DAG.getMachineFunction();
5015 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
5016 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5017 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5019 switch (Op.getValueType().getSimpleVT()) {
5020 default: assert(0 && "Invalid FP_TO_SINT to lower!");
5021 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5022 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5023 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5026 SDValue Chain = DAG.getEntryNode();
5027 SDValue Value = Op.getOperand(0);
5028 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5029 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5030 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5031 PseudoSourceValue::getFixedStack(SSFI), 0);
5032 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5034 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5036 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5037 Chain = Value.getValue(1);
5038 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5039 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5042 // Build the FP_TO_INT*_IN_MEM
5043 SDValue Ops[] = { Chain, Value, StackSlot };
5044 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5046 return std::make_pair(FIST, StackSlot);
5049 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5050 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
5051 SDValue FIST = Vals.first, StackSlot = Vals.second;
5052 if (FIST.getNode() == 0) return SDValue();
5055 return DAG.getLoad(Op.getValueType(), Op.getNode()->getDebugLoc(),
5056 FIST, StackSlot, NULL, 0);
5059 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5060 DebugLoc dl = Op.getNode()->getDebugLoc();
5061 MVT VT = Op.getValueType();
5064 EltVT = VT.getVectorElementType();
5065 std::vector<Constant*> CV;
5066 if (EltVT == MVT::f64) {
5067 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
5071 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
5077 Constant *C = ConstantVector::get(CV);
5078 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5079 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5080 PseudoSourceValue::getConstantPool(), 0,
5082 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5085 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5086 DebugLoc dl = Op.getNode()->getDebugLoc();
5087 MVT VT = Op.getValueType();
5089 unsigned EltNum = 1;
5090 if (VT.isVector()) {
5091 EltVT = VT.getVectorElementType();
5092 EltNum = VT.getVectorNumElements();
5094 std::vector<Constant*> CV;
5095 if (EltVT == MVT::f64) {
5096 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
5100 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
5106 Constant *C = ConstantVector::get(CV);
5107 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5108 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5109 PseudoSourceValue::getConstantPool(), 0,
5111 if (VT.isVector()) {
5112 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5113 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5114 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5116 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5118 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5122 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5123 SDValue Op0 = Op.getOperand(0);
5124 SDValue Op1 = Op.getOperand(1);
5125 DebugLoc dl = Op.getNode()->getDebugLoc();
5126 MVT VT = Op.getValueType();
5127 MVT SrcVT = Op1.getValueType();
5129 // If second operand is smaller, extend it first.
5130 if (SrcVT.bitsLT(VT)) {
5131 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5134 // And if it is bigger, shrink it first.
5135 if (SrcVT.bitsGT(VT)) {
5136 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5140 // At this point the operands and the result should have the same
5141 // type, and that won't be f80 since that is not custom lowered.
5143 // First get the sign bit of second operand.
5144 std::vector<Constant*> CV;
5145 if (SrcVT == MVT::f64) {
5146 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5147 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5149 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5150 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5151 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5152 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5154 Constant *C = ConstantVector::get(CV);
5155 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5156 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5157 PseudoSourceValue::getConstantPool(), 0,
5159 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5161 // Shift sign bit right or left if the two operands have different types.
5162 if (SrcVT.bitsGT(VT)) {
5163 // Op0 is MVT::f32, Op1 is MVT::f64.
5164 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5165 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5166 DAG.getConstant(32, MVT::i32));
5167 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5168 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5169 DAG.getIntPtrConstant(0));
5172 // Clear first operand sign bit.
5174 if (VT == MVT::f64) {
5175 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5176 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5178 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5179 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5180 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5181 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5183 C = ConstantVector::get(CV);
5184 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5185 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5186 PseudoSourceValue::getConstantPool(), 0,
5188 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5190 // Or the value with the sign bit.
5191 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5194 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5195 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5196 SDValue Op0 = Op.getOperand(0);
5197 SDValue Op1 = Op.getOperand(1);
5198 DebugLoc dl = Op.getNode()->getDebugLoc();
5199 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5201 // Lower (X & (1 << N)) == 0 to BT(X, N).
5202 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5203 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5204 if (Op0.getOpcode() == ISD::AND &&
5206 Op1.getOpcode() == ISD::Constant &&
5207 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5208 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5210 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5211 if (ConstantSDNode *Op010C =
5212 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5213 if (Op010C->getZExtValue() == 1) {
5214 LHS = Op0.getOperand(0);
5215 RHS = Op0.getOperand(1).getOperand(1);
5217 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5218 if (ConstantSDNode *Op000C =
5219 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5220 if (Op000C->getZExtValue() == 1) {
5221 LHS = Op0.getOperand(1);
5222 RHS = Op0.getOperand(0).getOperand(1);
5224 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5225 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5226 SDValue AndLHS = Op0.getOperand(0);
5227 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5228 LHS = AndLHS.getOperand(0);
5229 RHS = AndLHS.getOperand(1);
5233 if (LHS.getNode()) {
5234 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5235 // instruction. Since the shift amount is in-range-or-undefined, we know
5236 // that doing a bittest on the i16 value is ok. We extend to i32 because
5237 // the encoding for the i16 version is larger than the i32 version.
5238 if (LHS.getValueType() == MVT::i8)
5239 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5241 // If the operand types disagree, extend the shift amount to match. Since
5242 // BT ignores high bits (like shifts) we can use anyextend.
5243 if (LHS.getValueType() != RHS.getValueType())
5244 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5246 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5247 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5248 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5249 DAG.getConstant(Cond, MVT::i8), BT);
5253 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5254 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5256 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5257 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5258 DAG.getConstant(X86CC, MVT::i8), Cond);
5261 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5263 SDValue Op0 = Op.getOperand(0);
5264 SDValue Op1 = Op.getOperand(1);
5265 SDValue CC = Op.getOperand(2);
5266 MVT VT = Op.getValueType();
5267 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5268 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5269 DebugLoc dl = Op.getNode()->getDebugLoc();
5273 MVT VT0 = Op0.getValueType();
5274 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5275 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5278 switch (SetCCOpcode) {
5281 case ISD::SETEQ: SSECC = 0; break;
5283 case ISD::SETGT: Swap = true; // Fallthrough
5285 case ISD::SETOLT: SSECC = 1; break;
5287 case ISD::SETGE: Swap = true; // Fallthrough
5289 case ISD::SETOLE: SSECC = 2; break;
5290 case ISD::SETUO: SSECC = 3; break;
5292 case ISD::SETNE: SSECC = 4; break;
5293 case ISD::SETULE: Swap = true;
5294 case ISD::SETUGE: SSECC = 5; break;
5295 case ISD::SETULT: Swap = true;
5296 case ISD::SETUGT: SSECC = 6; break;
5297 case ISD::SETO: SSECC = 7; break;
5300 std::swap(Op0, Op1);
5302 // In the two special cases we can't handle, emit two comparisons.
5304 if (SetCCOpcode == ISD::SETUEQ) {
5306 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5307 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5308 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5310 else if (SetCCOpcode == ISD::SETONE) {
5312 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5313 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5314 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5316 assert(0 && "Illegal FP comparison");
5318 // Handle all other FP comparisons here.
5319 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5322 // We are handling one of the integer comparisons here. Since SSE only has
5323 // GT and EQ comparisons for integer, swapping operands and multiple
5324 // operations may be required for some comparisons.
5325 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5326 bool Swap = false, Invert = false, FlipSigns = false;
5328 switch (VT.getSimpleVT()) {
5330 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5331 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5332 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5333 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5336 switch (SetCCOpcode) {
5338 case ISD::SETNE: Invert = true;
5339 case ISD::SETEQ: Opc = EQOpc; break;
5340 case ISD::SETLT: Swap = true;
5341 case ISD::SETGT: Opc = GTOpc; break;
5342 case ISD::SETGE: Swap = true;
5343 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5344 case ISD::SETULT: Swap = true;
5345 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5346 case ISD::SETUGE: Swap = true;
5347 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5350 std::swap(Op0, Op1);
5352 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5353 // bits of the inputs before performing those operations.
5355 MVT EltVT = VT.getVectorElementType();
5356 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5358 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5359 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5361 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5362 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5365 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5367 // If the logical-not of the result is required, perform that now.
5369 Result = DAG.getNOT(dl, Result, VT);
5374 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5375 static bool isX86LogicalCmp(unsigned Opc) {
5376 return Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI;
5379 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5380 bool addTest = true;
5381 SDValue Cond = Op.getOperand(0);
5382 DebugLoc dl = Op.getNode()->getDebugLoc();
5385 if (Cond.getOpcode() == ISD::SETCC)
5386 Cond = LowerSETCC(Cond, DAG);
5388 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5389 // setting operand in place of the X86ISD::SETCC.
5390 if (Cond.getOpcode() == X86ISD::SETCC) {
5391 CC = Cond.getOperand(0);
5393 SDValue Cmp = Cond.getOperand(1);
5394 unsigned Opc = Cmp.getOpcode();
5395 MVT VT = Op.getValueType();
5397 bool IllegalFPCMov = false;
5398 if (VT.isFloatingPoint() && !VT.isVector() &&
5399 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5400 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5402 if ((isX86LogicalCmp(Opc) && !IllegalFPCMov) || Opc == X86ISD::BT) { // FIXME
5409 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5410 Cond= DAG.getNode(X86ISD::CMP, dl, MVT::i32, Cond,
5411 DAG.getConstant(0, MVT::i8));
5414 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5416 SmallVector<SDValue, 4> Ops;
5417 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5418 // condition is true.
5419 Ops.push_back(Op.getOperand(2));
5420 Ops.push_back(Op.getOperand(1));
5422 Ops.push_back(Cond);
5423 return DAG.getNode(X86ISD::CMOV, dl, VTs, 2, &Ops[0], Ops.size());
5426 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5427 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5428 // from the AND / OR.
5429 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5430 Opc = Op.getOpcode();
5431 if (Opc != ISD::OR && Opc != ISD::AND)
5433 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5434 Op.getOperand(0).hasOneUse() &&
5435 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5436 Op.getOperand(1).hasOneUse());
5439 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5440 // 1 and that the SETCC node has a single use.
5441 static bool isXor1OfSetCC(SDValue Op) {
5442 if (Op.getOpcode() != ISD::XOR)
5444 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5445 if (N1C && N1C->getAPIntValue() == 1) {
5446 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5447 Op.getOperand(0).hasOneUse();
5452 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5453 bool addTest = true;
5454 SDValue Chain = Op.getOperand(0);
5455 SDValue Cond = Op.getOperand(1);
5456 SDValue Dest = Op.getOperand(2);
5457 DebugLoc dl = Op.getNode()->getDebugLoc();
5460 if (Cond.getOpcode() == ISD::SETCC)
5461 Cond = LowerSETCC(Cond, DAG);
5463 // FIXME: LowerXALUO doesn't handle these!!
5464 else if (Cond.getOpcode() == X86ISD::ADD ||
5465 Cond.getOpcode() == X86ISD::SUB ||
5466 Cond.getOpcode() == X86ISD::SMUL ||
5467 Cond.getOpcode() == X86ISD::UMUL)
5468 Cond = LowerXALUO(Cond, DAG);
5471 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5472 // setting operand in place of the X86ISD::SETCC.
5473 if (Cond.getOpcode() == X86ISD::SETCC) {
5474 CC = Cond.getOperand(0);
5476 SDValue Cmp = Cond.getOperand(1);
5477 unsigned Opc = Cmp.getOpcode();
5478 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5479 if (isX86LogicalCmp(Opc) || Opc == X86ISD::BT) {
5483 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5487 // These can only come from an arithmetic instruction with overflow,
5488 // e.g. SADDO, UADDO.
5489 Cond = Cond.getNode()->getOperand(1);
5496 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5497 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5498 unsigned Opc = Cmp.getOpcode();
5499 if (CondOpc == ISD::OR) {
5500 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5501 // two branches instead of an explicit OR instruction with a
5503 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5504 isX86LogicalCmp(Opc)) {
5505 CC = Cond.getOperand(0).getOperand(0);
5506 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5507 Chain, Dest, CC, Cmp);
5508 CC = Cond.getOperand(1).getOperand(0);
5512 } else { // ISD::AND
5513 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5514 // two branches instead of an explicit AND instruction with a
5515 // separate test. However, we only do this if this block doesn't
5516 // have a fall-through edge, because this requires an explicit
5517 // jmp when the condition is false.
5518 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5519 isX86LogicalCmp(Opc) &&
5520 Op.getNode()->hasOneUse()) {
5521 X86::CondCode CCode =
5522 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5523 CCode = X86::GetOppositeBranchCondition(CCode);
5524 CC = DAG.getConstant(CCode, MVT::i8);
5525 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5526 // Look for an unconditional branch following this conditional branch.
5527 // We need this because we need to reverse the successors in order
5528 // to implement FCMP_OEQ.
5529 if (User.getOpcode() == ISD::BR) {
5530 SDValue FalseBB = User.getOperand(1);
5532 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5533 assert(NewBR == User);
5536 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5537 Chain, Dest, CC, Cmp);
5538 X86::CondCode CCode =
5539 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5540 CCode = X86::GetOppositeBranchCondition(CCode);
5541 CC = DAG.getConstant(CCode, MVT::i8);
5547 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5548 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5549 // It should be transformed during dag combiner except when the condition
5550 // is set by a arithmetics with overflow node.
5551 X86::CondCode CCode =
5552 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5553 CCode = X86::GetOppositeBranchCondition(CCode);
5554 CC = DAG.getConstant(CCode, MVT::i8);
5555 Cond = Cond.getOperand(0).getOperand(1);
5561 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5562 Cond= DAG.getNode(X86ISD::CMP, dl, MVT::i32, Cond,
5563 DAG.getConstant(0, MVT::i8));
5565 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5566 Chain, Dest, CC, Cond);
5570 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5571 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5572 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5573 // that the guard pages used by the OS virtual memory manager are allocated in
5574 // correct sequence.
5576 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5577 SelectionDAG &DAG) {
5578 assert(Subtarget->isTargetCygMing() &&
5579 "This should be used only on Cygwin/Mingw targets");
5580 DebugLoc dl = Op.getNode()->getDebugLoc();
5583 SDValue Chain = Op.getOperand(0);
5584 SDValue Size = Op.getOperand(1);
5585 // FIXME: Ensure alignment here
5589 MVT IntPtr = getPointerTy();
5590 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5592 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5594 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5595 Flag = Chain.getValue(1);
5597 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5598 SDValue Ops[] = { Chain,
5599 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5600 DAG.getRegister(X86::EAX, IntPtr),
5601 DAG.getRegister(X86StackPtr, SPTy),
5603 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5604 Flag = Chain.getValue(1);
5606 Chain = DAG.getCALLSEQ_END(Chain,
5607 DAG.getIntPtrConstant(0, true),
5608 DAG.getIntPtrConstant(0, true),
5611 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5613 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5614 return DAG.getMergeValues(Ops1, 2, dl);
5618 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5620 SDValue Dst, SDValue Src,
5621 SDValue Size, unsigned Align,
5623 uint64_t DstSVOff) {
5624 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5626 // If not DWORD aligned or size is more than the threshold, call the library.
5627 // The libc version is likely to be faster for these cases. It can use the
5628 // address value and run time information about the CPU.
5629 if ((Align & 3) != 0 ||
5631 ConstantSize->getZExtValue() >
5632 getSubtarget()->getMaxInlineSizeThreshold()) {
5633 SDValue InFlag(0, 0);
5635 // Check to see if there is a specialized entry-point for memory zeroing.
5636 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5638 if (const char *bzeroEntry = V &&
5639 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5640 MVT IntPtr = getPointerTy();
5641 const Type *IntPtrTy = TD->getIntPtrType();
5642 TargetLowering::ArgListTy Args;
5643 TargetLowering::ArgListEntry Entry;
5645 Entry.Ty = IntPtrTy;
5646 Args.push_back(Entry);
5648 Args.push_back(Entry);
5649 std::pair<SDValue,SDValue> CallResult =
5650 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5651 CallingConv::C, false,
5652 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5653 return CallResult.second;
5656 // Otherwise have the target-independent code call memset.
5660 uint64_t SizeVal = ConstantSize->getZExtValue();
5661 SDValue InFlag(0, 0);
5664 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5665 unsigned BytesLeft = 0;
5666 bool TwoRepStos = false;
5669 uint64_t Val = ValC->getZExtValue() & 255;
5671 // If the value is a constant, then we can potentially use larger sets.
5672 switch (Align & 3) {
5673 case 2: // WORD aligned
5676 Val = (Val << 8) | Val;
5678 case 0: // DWORD aligned
5681 Val = (Val << 8) | Val;
5682 Val = (Val << 16) | Val;
5683 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5686 Val = (Val << 32) | Val;
5689 default: // Byte aligned
5692 Count = DAG.getIntPtrConstant(SizeVal);
5696 if (AVT.bitsGT(MVT::i8)) {
5697 unsigned UBytes = AVT.getSizeInBits() / 8;
5698 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5699 BytesLeft = SizeVal % UBytes;
5702 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5704 InFlag = Chain.getValue(1);
5707 Count = DAG.getIntPtrConstant(SizeVal);
5708 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5709 InFlag = Chain.getValue(1);
5712 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5715 InFlag = Chain.getValue(1);
5716 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5719 InFlag = Chain.getValue(1);
5721 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5722 SmallVector<SDValue, 8> Ops;
5723 Ops.push_back(Chain);
5724 Ops.push_back(DAG.getValueType(AVT));
5725 Ops.push_back(InFlag);
5726 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5729 InFlag = Chain.getValue(1);
5731 MVT CVT = Count.getValueType();
5732 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5733 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5734 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5737 InFlag = Chain.getValue(1);
5738 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5740 Ops.push_back(Chain);
5741 Ops.push_back(DAG.getValueType(MVT::i8));
5742 Ops.push_back(InFlag);
5743 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5744 } else if (BytesLeft) {
5745 // Handle the last 1 - 7 bytes.
5746 unsigned Offset = SizeVal - BytesLeft;
5747 MVT AddrVT = Dst.getValueType();
5748 MVT SizeVT = Size.getValueType();
5750 Chain = DAG.getMemset(Chain, dl,
5751 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5752 DAG.getConstant(Offset, AddrVT)),
5754 DAG.getConstant(BytesLeft, SizeVT),
5755 Align, DstSV, DstSVOff + Offset);
5758 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5763 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5764 SDValue Chain, SDValue Dst, SDValue Src,
5765 SDValue Size, unsigned Align,
5767 const Value *DstSV, uint64_t DstSVOff,
5768 const Value *SrcSV, uint64_t SrcSVOff) {
5769 // This requires the copy size to be a constant, preferrably
5770 // within a subtarget-specific limit.
5771 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5774 uint64_t SizeVal = ConstantSize->getZExtValue();
5775 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5778 /// If not DWORD aligned, call the library.
5779 if ((Align & 3) != 0)
5784 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5787 unsigned UBytes = AVT.getSizeInBits() / 8;
5788 unsigned CountVal = SizeVal / UBytes;
5789 SDValue Count = DAG.getIntPtrConstant(CountVal);
5790 unsigned BytesLeft = SizeVal % UBytes;
5792 SDValue InFlag(0, 0);
5793 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5796 InFlag = Chain.getValue(1);
5797 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5800 InFlag = Chain.getValue(1);
5801 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5804 InFlag = Chain.getValue(1);
5806 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5807 SmallVector<SDValue, 8> Ops;
5808 Ops.push_back(Chain);
5809 Ops.push_back(DAG.getValueType(AVT));
5810 Ops.push_back(InFlag);
5811 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5813 SmallVector<SDValue, 4> Results;
5814 Results.push_back(RepMovs);
5816 // Handle the last 1 - 7 bytes.
5817 unsigned Offset = SizeVal - BytesLeft;
5818 MVT DstVT = Dst.getValueType();
5819 MVT SrcVT = Src.getValueType();
5820 MVT SizeVT = Size.getValueType();
5821 Results.push_back(DAG.getMemcpy(Chain, dl,
5822 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5823 DAG.getConstant(Offset, DstVT)),
5824 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5825 DAG.getConstant(Offset, SrcVT)),
5826 DAG.getConstant(BytesLeft, SizeVT),
5827 Align, AlwaysInline,
5828 DstSV, DstSVOff + Offset,
5829 SrcSV, SrcSVOff + Offset));
5832 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5833 &Results[0], Results.size());
5836 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5837 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5838 DebugLoc dl = Op.getNode()->getDebugLoc();
5840 if (!Subtarget->is64Bit()) {
5841 // vastart just stores the address of the VarArgsFrameIndex slot into the
5842 // memory location argument.
5843 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5844 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
5848 // gp_offset (0 - 6 * 8)
5849 // fp_offset (48 - 48 + 8 * 16)
5850 // overflow_arg_area (point to parameters coming in memory).
5852 SmallVector<SDValue, 8> MemOps;
5853 SDValue FIN = Op.getOperand(1);
5855 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
5856 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5858 MemOps.push_back(Store);
5861 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5862 FIN, DAG.getIntPtrConstant(4));
5863 Store = DAG.getStore(Op.getOperand(0), dl,
5864 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5866 MemOps.push_back(Store);
5868 // Store ptr to overflow_arg_area
5869 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5870 FIN, DAG.getIntPtrConstant(4));
5871 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5872 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
5873 MemOps.push_back(Store);
5875 // Store ptr to reg_save_area.
5876 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5877 FIN, DAG.getIntPtrConstant(8));
5878 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5879 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
5880 MemOps.push_back(Store);
5881 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5882 &MemOps[0], MemOps.size());
5885 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5886 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5887 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5888 SDValue Chain = Op.getOperand(0);
5889 SDValue SrcPtr = Op.getOperand(1);
5890 SDValue SrcSV = Op.getOperand(2);
5892 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5897 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5898 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5899 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5900 SDValue Chain = Op.getOperand(0);
5901 SDValue DstPtr = Op.getOperand(1);
5902 SDValue SrcPtr = Op.getOperand(2);
5903 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5904 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5905 DebugLoc dl = Op.getNode()->getDebugLoc();
5907 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
5908 DAG.getIntPtrConstant(24), 8, false,
5909 DstSV, 0, SrcSV, 0);
5913 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5914 DebugLoc dl = Op.getNode()->getDebugLoc();
5915 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5917 default: return SDValue(); // Don't custom lower most intrinsics.
5918 // Comparison intrinsics.
5919 case Intrinsic::x86_sse_comieq_ss:
5920 case Intrinsic::x86_sse_comilt_ss:
5921 case Intrinsic::x86_sse_comile_ss:
5922 case Intrinsic::x86_sse_comigt_ss:
5923 case Intrinsic::x86_sse_comige_ss:
5924 case Intrinsic::x86_sse_comineq_ss:
5925 case Intrinsic::x86_sse_ucomieq_ss:
5926 case Intrinsic::x86_sse_ucomilt_ss:
5927 case Intrinsic::x86_sse_ucomile_ss:
5928 case Intrinsic::x86_sse_ucomigt_ss:
5929 case Intrinsic::x86_sse_ucomige_ss:
5930 case Intrinsic::x86_sse_ucomineq_ss:
5931 case Intrinsic::x86_sse2_comieq_sd:
5932 case Intrinsic::x86_sse2_comilt_sd:
5933 case Intrinsic::x86_sse2_comile_sd:
5934 case Intrinsic::x86_sse2_comigt_sd:
5935 case Intrinsic::x86_sse2_comige_sd:
5936 case Intrinsic::x86_sse2_comineq_sd:
5937 case Intrinsic::x86_sse2_ucomieq_sd:
5938 case Intrinsic::x86_sse2_ucomilt_sd:
5939 case Intrinsic::x86_sse2_ucomile_sd:
5940 case Intrinsic::x86_sse2_ucomigt_sd:
5941 case Intrinsic::x86_sse2_ucomige_sd:
5942 case Intrinsic::x86_sse2_ucomineq_sd: {
5944 ISD::CondCode CC = ISD::SETCC_INVALID;
5947 case Intrinsic::x86_sse_comieq_ss:
5948 case Intrinsic::x86_sse2_comieq_sd:
5952 case Intrinsic::x86_sse_comilt_ss:
5953 case Intrinsic::x86_sse2_comilt_sd:
5957 case Intrinsic::x86_sse_comile_ss:
5958 case Intrinsic::x86_sse2_comile_sd:
5962 case Intrinsic::x86_sse_comigt_ss:
5963 case Intrinsic::x86_sse2_comigt_sd:
5967 case Intrinsic::x86_sse_comige_ss:
5968 case Intrinsic::x86_sse2_comige_sd:
5972 case Intrinsic::x86_sse_comineq_ss:
5973 case Intrinsic::x86_sse2_comineq_sd:
5977 case Intrinsic::x86_sse_ucomieq_ss:
5978 case Intrinsic::x86_sse2_ucomieq_sd:
5979 Opc = X86ISD::UCOMI;
5982 case Intrinsic::x86_sse_ucomilt_ss:
5983 case Intrinsic::x86_sse2_ucomilt_sd:
5984 Opc = X86ISD::UCOMI;
5987 case Intrinsic::x86_sse_ucomile_ss:
5988 case Intrinsic::x86_sse2_ucomile_sd:
5989 Opc = X86ISD::UCOMI;
5992 case Intrinsic::x86_sse_ucomigt_ss:
5993 case Intrinsic::x86_sse2_ucomigt_sd:
5994 Opc = X86ISD::UCOMI;
5997 case Intrinsic::x86_sse_ucomige_ss:
5998 case Intrinsic::x86_sse2_ucomige_sd:
5999 Opc = X86ISD::UCOMI;
6002 case Intrinsic::x86_sse_ucomineq_ss:
6003 case Intrinsic::x86_sse2_ucomineq_sd:
6004 Opc = X86ISD::UCOMI;
6009 SDValue LHS = Op.getOperand(1);
6010 SDValue RHS = Op.getOperand(2);
6011 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6012 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6013 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6014 DAG.getConstant(X86CC, MVT::i8), Cond);
6015 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6018 // Fix vector shift instructions where the last operand is a non-immediate
6020 case Intrinsic::x86_sse2_pslli_w:
6021 case Intrinsic::x86_sse2_pslli_d:
6022 case Intrinsic::x86_sse2_pslli_q:
6023 case Intrinsic::x86_sse2_psrli_w:
6024 case Intrinsic::x86_sse2_psrli_d:
6025 case Intrinsic::x86_sse2_psrli_q:
6026 case Intrinsic::x86_sse2_psrai_w:
6027 case Intrinsic::x86_sse2_psrai_d:
6028 case Intrinsic::x86_mmx_pslli_w:
6029 case Intrinsic::x86_mmx_pslli_d:
6030 case Intrinsic::x86_mmx_pslli_q:
6031 case Intrinsic::x86_mmx_psrli_w:
6032 case Intrinsic::x86_mmx_psrli_d:
6033 case Intrinsic::x86_mmx_psrli_q:
6034 case Intrinsic::x86_mmx_psrai_w:
6035 case Intrinsic::x86_mmx_psrai_d: {
6036 SDValue ShAmt = Op.getOperand(2);
6037 if (isa<ConstantSDNode>(ShAmt))
6040 unsigned NewIntNo = 0;
6041 MVT ShAmtVT = MVT::v4i32;
6043 case Intrinsic::x86_sse2_pslli_w:
6044 NewIntNo = Intrinsic::x86_sse2_psll_w;
6046 case Intrinsic::x86_sse2_pslli_d:
6047 NewIntNo = Intrinsic::x86_sse2_psll_d;
6049 case Intrinsic::x86_sse2_pslli_q:
6050 NewIntNo = Intrinsic::x86_sse2_psll_q;
6052 case Intrinsic::x86_sse2_psrli_w:
6053 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6055 case Intrinsic::x86_sse2_psrli_d:
6056 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6058 case Intrinsic::x86_sse2_psrli_q:
6059 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6061 case Intrinsic::x86_sse2_psrai_w:
6062 NewIntNo = Intrinsic::x86_sse2_psra_w;
6064 case Intrinsic::x86_sse2_psrai_d:
6065 NewIntNo = Intrinsic::x86_sse2_psra_d;
6068 ShAmtVT = MVT::v2i32;
6070 case Intrinsic::x86_mmx_pslli_w:
6071 NewIntNo = Intrinsic::x86_mmx_psll_w;
6073 case Intrinsic::x86_mmx_pslli_d:
6074 NewIntNo = Intrinsic::x86_mmx_psll_d;
6076 case Intrinsic::x86_mmx_pslli_q:
6077 NewIntNo = Intrinsic::x86_mmx_psll_q;
6079 case Intrinsic::x86_mmx_psrli_w:
6080 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6082 case Intrinsic::x86_mmx_psrli_d:
6083 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6085 case Intrinsic::x86_mmx_psrli_q:
6086 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6088 case Intrinsic::x86_mmx_psrai_w:
6089 NewIntNo = Intrinsic::x86_mmx_psra_w;
6091 case Intrinsic::x86_mmx_psrai_d:
6092 NewIntNo = Intrinsic::x86_mmx_psra_d;
6094 default: abort(); // Can't reach here.
6099 MVT VT = Op.getValueType();
6100 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6101 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6102 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6103 DAG.getConstant(NewIntNo, MVT::i32),
6104 Op.getOperand(1), ShAmt);
6109 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6110 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6111 DebugLoc dl = Op.getNode()->getDebugLoc();
6114 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6116 DAG.getConstant(TD->getPointerSize(),
6117 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6118 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6119 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6124 // Just load the return address.
6125 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6126 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6127 RetAddrFI, NULL, 0);
6130 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6131 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6132 MFI->setFrameAddressIsTaken(true);
6133 MVT VT = Op.getValueType();
6134 DebugLoc dl = Op.getNode()->getDebugLoc(); // FIXME probably not meaningful
6135 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6136 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6137 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6139 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6143 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6144 SelectionDAG &DAG) {
6145 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6148 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6150 MachineFunction &MF = DAG.getMachineFunction();
6151 SDValue Chain = Op.getOperand(0);
6152 SDValue Offset = Op.getOperand(1);
6153 SDValue Handler = Op.getOperand(2);
6154 DebugLoc dl = Op.getNode()->getDebugLoc();
6156 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6158 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6160 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6161 DAG.getIntPtrConstant(-TD->getPointerSize()));
6162 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6163 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6164 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6165 MF.getRegInfo().addLiveOut(StoreAddrReg);
6167 return DAG.getNode(X86ISD::EH_RETURN, dl,
6169 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6172 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6173 SelectionDAG &DAG) {
6174 SDValue Root = Op.getOperand(0);
6175 SDValue Trmp = Op.getOperand(1); // trampoline
6176 SDValue FPtr = Op.getOperand(2); // nested function
6177 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6178 DebugLoc dl = Op.getNode()->getDebugLoc();
6180 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6182 const X86InstrInfo *TII =
6183 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6185 if (Subtarget->is64Bit()) {
6186 SDValue OutChains[6];
6188 // Large code-model.
6190 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6191 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6193 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6194 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6196 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6198 // Load the pointer to the nested function into R11.
6199 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6200 SDValue Addr = Trmp;
6201 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6204 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6205 DAG.getConstant(2, MVT::i64));
6206 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6208 // Load the 'nest' parameter value into R10.
6209 // R10 is specified in X86CallingConv.td
6210 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6211 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6212 DAG.getConstant(10, MVT::i64));
6213 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6214 Addr, TrmpAddr, 10);
6216 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6217 DAG.getConstant(12, MVT::i64));
6218 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6220 // Jump to the nested function.
6221 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6222 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6223 DAG.getConstant(20, MVT::i64));
6224 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6225 Addr, TrmpAddr, 20);
6227 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6228 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6229 DAG.getConstant(22, MVT::i64));
6230 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6234 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6235 return DAG.getMergeValues(Ops, 2, dl);
6237 const Function *Func =
6238 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6239 unsigned CC = Func->getCallingConv();
6244 assert(0 && "Unsupported calling convention");
6245 case CallingConv::C:
6246 case CallingConv::X86_StdCall: {
6247 // Pass 'nest' parameter in ECX.
6248 // Must be kept in sync with X86CallingConv.td
6251 // Check that ECX wasn't needed by an 'inreg' parameter.
6252 const FunctionType *FTy = Func->getFunctionType();
6253 const AttrListPtr &Attrs = Func->getAttributes();
6255 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6256 unsigned InRegCount = 0;
6259 for (FunctionType::param_iterator I = FTy->param_begin(),
6260 E = FTy->param_end(); I != E; ++I, ++Idx)
6261 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6262 // FIXME: should only count parameters that are lowered to integers.
6263 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6265 if (InRegCount > 2) {
6266 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6272 case CallingConv::X86_FastCall:
6273 case CallingConv::Fast:
6274 // Pass 'nest' parameter in EAX.
6275 // Must be kept in sync with X86CallingConv.td
6280 SDValue OutChains[4];
6283 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6284 DAG.getConstant(10, MVT::i32));
6285 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6287 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6288 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6289 OutChains[0] = DAG.getStore(Root, dl,
6290 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6293 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6294 DAG.getConstant(1, MVT::i32));
6295 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6297 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6298 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6299 DAG.getConstant(5, MVT::i32));
6300 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6301 TrmpAddr, 5, false, 1);
6303 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6304 DAG.getConstant(6, MVT::i32));
6305 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6308 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6309 return DAG.getMergeValues(Ops, 2, dl);
6313 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6315 The rounding mode is in bits 11:10 of FPSR, and has the following
6322 FLT_ROUNDS, on the other hand, expects the following:
6329 To perform the conversion, we do:
6330 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6333 MachineFunction &MF = DAG.getMachineFunction();
6334 const TargetMachine &TM = MF.getTarget();
6335 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6336 unsigned StackAlignment = TFI.getStackAlignment();
6337 MVT VT = Op.getValueType();
6338 DebugLoc dl = Op.getNode()->getDebugLoc();
6340 // Save FP Control Word to stack slot
6341 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6342 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6344 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6345 DAG.getEntryNode(), StackSlot);
6347 // Load FP Control Word from stack slot
6348 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6350 // Transform as necessary
6352 DAG.getNode(ISD::SRL, dl, MVT::i16,
6353 DAG.getNode(ISD::AND, dl, MVT::i16,
6354 CWD, DAG.getConstant(0x800, MVT::i16)),
6355 DAG.getConstant(11, MVT::i8));
6357 DAG.getNode(ISD::SRL, dl, MVT::i16,
6358 DAG.getNode(ISD::AND, dl, MVT::i16,
6359 CWD, DAG.getConstant(0x400, MVT::i16)),
6360 DAG.getConstant(9, MVT::i8));
6363 DAG.getNode(ISD::AND, dl, MVT::i16,
6364 DAG.getNode(ISD::ADD, dl, MVT::i16,
6365 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6366 DAG.getConstant(1, MVT::i16)),
6367 DAG.getConstant(3, MVT::i16));
6370 return DAG.getNode((VT.getSizeInBits() < 16 ?
6371 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
6374 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6375 MVT VT = Op.getValueType();
6377 unsigned NumBits = VT.getSizeInBits();
6378 DebugLoc dl = Op.getNode()->getDebugLoc();
6380 Op = Op.getOperand(0);
6381 if (VT == MVT::i8) {
6382 // Zero extend to i32 since there is not an i8 bsr.
6384 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6387 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6388 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6389 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6391 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6392 SmallVector<SDValue, 4> Ops;
6394 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6395 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6396 Ops.push_back(Op.getValue(1));
6397 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6399 // Finally xor with NumBits-1.
6400 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6403 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6407 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6408 MVT VT = Op.getValueType();
6410 unsigned NumBits = VT.getSizeInBits();
6411 DebugLoc dl = Op.getNode()->getDebugLoc();
6413 Op = Op.getOperand(0);
6414 if (VT == MVT::i8) {
6416 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6419 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6420 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6421 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6423 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6424 SmallVector<SDValue, 4> Ops;
6426 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6427 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6428 Ops.push_back(Op.getValue(1));
6429 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6432 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6436 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6437 MVT VT = Op.getValueType();
6438 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6439 DebugLoc dl = Op.getNode()->getDebugLoc();
6441 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6442 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6443 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6444 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6445 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6447 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6448 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6449 // return AloBlo + AloBhi + AhiBlo;
6451 SDValue A = Op.getOperand(0);
6452 SDValue B = Op.getOperand(1);
6454 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6455 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6456 A, DAG.getConstant(32, MVT::i32));
6457 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6458 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6459 B, DAG.getConstant(32, MVT::i32));
6460 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6461 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6463 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6464 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6466 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6467 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6469 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6470 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6471 AloBhi, DAG.getConstant(32, MVT::i32));
6472 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6473 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6474 AhiBlo, DAG.getConstant(32, MVT::i32));
6475 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6476 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6481 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6482 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6483 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6484 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6485 // has only one use.
6486 SDNode *N = Op.getNode();
6487 SDValue LHS = N->getOperand(0);
6488 SDValue RHS = N->getOperand(1);
6489 unsigned BaseOp = 0;
6491 DebugLoc dl = Op.getNode()->getDebugLoc();
6493 switch (Op.getOpcode()) {
6494 default: assert(0 && "Unknown ovf instruction!");
6496 BaseOp = X86ISD::ADD;
6500 BaseOp = X86ISD::ADD;
6504 BaseOp = X86ISD::SUB;
6508 BaseOp = X86ISD::SUB;
6512 BaseOp = X86ISD::SMUL;
6516 BaseOp = X86ISD::UMUL;
6521 // Also sets EFLAGS.
6522 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6523 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6526 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6527 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6529 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6533 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6534 MVT T = Op.getValueType();
6535 DebugLoc dl = Op.getNode()->getDebugLoc();
6538 switch(T.getSimpleVT()) {
6540 assert(false && "Invalid value type!");
6541 case MVT::i8: Reg = X86::AL; size = 1; break;
6542 case MVT::i16: Reg = X86::AX; size = 2; break;
6543 case MVT::i32: Reg = X86::EAX; size = 4; break;
6545 assert(Subtarget->is64Bit() && "Node not type legal!");
6546 Reg = X86::RAX; size = 8;
6549 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6550 Op.getOperand(2), SDValue());
6551 SDValue Ops[] = { cpIn.getValue(0),
6554 DAG.getTargetConstant(size, MVT::i8),
6556 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6557 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6559 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6563 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6564 SelectionDAG &DAG) {
6565 assert(Subtarget->is64Bit() && "Result not type legalized?");
6566 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6567 SDValue TheChain = Op.getOperand(0);
6568 DebugLoc dl = Op.getNode()->getDebugLoc();
6569 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6570 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6571 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6573 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6574 DAG.getConstant(32, MVT::i8));
6576 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6579 return DAG.getMergeValues(Ops, 2, dl);
6582 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6583 SDNode *Node = Op.getNode();
6584 DebugLoc dl = Node->getDebugLoc();
6585 MVT T = Node->getValueType(0);
6586 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6587 DAG.getConstant(0, T), Node->getOperand(2));
6588 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6589 cast<AtomicSDNode>(Node)->getMemoryVT(),
6590 Node->getOperand(0),
6591 Node->getOperand(1), negOp,
6592 cast<AtomicSDNode>(Node)->getSrcValue(),
6593 cast<AtomicSDNode>(Node)->getAlignment());
6596 /// LowerOperation - Provide custom lowering hooks for some operations.
6598 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6599 switch (Op.getOpcode()) {
6600 default: assert(0 && "Should not custom lower this!");
6601 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6602 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6603 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6604 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6605 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6606 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6607 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6608 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6609 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6610 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6611 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6612 case ISD::SHL_PARTS:
6613 case ISD::SRA_PARTS:
6614 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6615 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6616 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6617 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6618 case ISD::FABS: return LowerFABS(Op, DAG);
6619 case ISD::FNEG: return LowerFNEG(Op, DAG);
6620 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6621 case ISD::SETCC: return LowerSETCC(Op, DAG);
6622 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6623 case ISD::SELECT: return LowerSELECT(Op, DAG);
6624 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6625 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6626 case ISD::CALL: return LowerCALL(Op, DAG);
6627 case ISD::RET: return LowerRET(Op, DAG);
6628 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6629 case ISD::VASTART: return LowerVASTART(Op, DAG);
6630 case ISD::VAARG: return LowerVAARG(Op, DAG);
6631 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6632 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6633 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6634 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6635 case ISD::FRAME_TO_ARGS_OFFSET:
6636 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6637 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6638 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6639 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6640 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6641 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6642 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6643 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6649 case ISD::UMULO: return LowerXALUO(Op, DAG);
6650 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6654 void X86TargetLowering::
6655 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6656 SelectionDAG &DAG, unsigned NewOp) {
6657 MVT T = Node->getValueType(0);
6658 DebugLoc dl = Node->getDebugLoc();
6659 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6661 SDValue Chain = Node->getOperand(0);
6662 SDValue In1 = Node->getOperand(1);
6663 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6664 Node->getOperand(2), DAG.getIntPtrConstant(0));
6665 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6666 Node->getOperand(2), DAG.getIntPtrConstant(1));
6667 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6668 // have a MemOperand. Pass the info through as a normal operand.
6669 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6670 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6671 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6672 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6673 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6674 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6675 Results.push_back(Result.getValue(2));
6678 /// ReplaceNodeResults - Replace a node with an illegal result type
6679 /// with a new node built out of custom code.
6680 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6681 SmallVectorImpl<SDValue>&Results,
6682 SelectionDAG &DAG) {
6683 DebugLoc dl = N->getDebugLoc();
6684 switch (N->getOpcode()) {
6686 assert(false && "Do not know how to custom type legalize this operation!");
6688 case ISD::FP_TO_SINT: {
6689 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
6690 SDValue FIST = Vals.first, StackSlot = Vals.second;
6691 if (FIST.getNode() != 0) {
6692 MVT VT = N->getValueType(0);
6693 // Return a load from the stack slot.
6694 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6698 case ISD::READCYCLECOUNTER: {
6699 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6700 SDValue TheChain = N->getOperand(0);
6701 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6702 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6704 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6706 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6707 SDValue Ops[] = { eax, edx };
6708 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6709 Results.push_back(edx.getValue(1));
6712 case ISD::ATOMIC_CMP_SWAP: {
6713 MVT T = N->getValueType(0);
6714 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6715 SDValue cpInL, cpInH;
6716 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6717 DAG.getConstant(0, MVT::i32));
6718 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6719 DAG.getConstant(1, MVT::i32));
6720 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6721 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6723 SDValue swapInL, swapInH;
6724 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6725 DAG.getConstant(0, MVT::i32));
6726 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6727 DAG.getConstant(1, MVT::i32));
6728 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6730 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6731 swapInL.getValue(1));
6732 SDValue Ops[] = { swapInH.getValue(0),
6734 swapInH.getValue(1) };
6735 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6736 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6737 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6738 MVT::i32, Result.getValue(1));
6739 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6740 MVT::i32, cpOutL.getValue(2));
6741 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6742 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6743 Results.push_back(cpOutH.getValue(1));
6746 case ISD::ATOMIC_LOAD_ADD:
6747 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6749 case ISD::ATOMIC_LOAD_AND:
6750 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6752 case ISD::ATOMIC_LOAD_NAND:
6753 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6755 case ISD::ATOMIC_LOAD_OR:
6756 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6758 case ISD::ATOMIC_LOAD_SUB:
6759 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6761 case ISD::ATOMIC_LOAD_XOR:
6762 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6764 case ISD::ATOMIC_SWAP:
6765 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6770 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6772 default: return NULL;
6773 case X86ISD::BSF: return "X86ISD::BSF";
6774 case X86ISD::BSR: return "X86ISD::BSR";
6775 case X86ISD::SHLD: return "X86ISD::SHLD";
6776 case X86ISD::SHRD: return "X86ISD::SHRD";
6777 case X86ISD::FAND: return "X86ISD::FAND";
6778 case X86ISD::FOR: return "X86ISD::FOR";
6779 case X86ISD::FXOR: return "X86ISD::FXOR";
6780 case X86ISD::FSRL: return "X86ISD::FSRL";
6781 case X86ISD::FILD: return "X86ISD::FILD";
6782 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6783 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6784 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6785 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6786 case X86ISD::FLD: return "X86ISD::FLD";
6787 case X86ISD::FST: return "X86ISD::FST";
6788 case X86ISD::CALL: return "X86ISD::CALL";
6789 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6790 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6791 case X86ISD::BT: return "X86ISD::BT";
6792 case X86ISD::CMP: return "X86ISD::CMP";
6793 case X86ISD::COMI: return "X86ISD::COMI";
6794 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6795 case X86ISD::SETCC: return "X86ISD::SETCC";
6796 case X86ISD::CMOV: return "X86ISD::CMOV";
6797 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6798 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6799 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6800 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6801 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6802 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6803 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6804 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6805 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6806 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6807 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6808 case X86ISD::FMAX: return "X86ISD::FMAX";
6809 case X86ISD::FMIN: return "X86ISD::FMIN";
6810 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6811 case X86ISD::FRCP: return "X86ISD::FRCP";
6812 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6813 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6814 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6815 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6816 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6817 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6818 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6819 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6820 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6821 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6822 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6823 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6824 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6825 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6826 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6827 case X86ISD::VSHL: return "X86ISD::VSHL";
6828 case X86ISD::VSRL: return "X86ISD::VSRL";
6829 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6830 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6831 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6832 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6833 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6834 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6835 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6836 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6837 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6838 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6839 case X86ISD::ADD: return "X86ISD::ADD";
6840 case X86ISD::SUB: return "X86ISD::SUB";
6841 case X86ISD::SMUL: return "X86ISD::SMUL";
6842 case X86ISD::UMUL: return "X86ISD::UMUL";
6846 // isLegalAddressingMode - Return true if the addressing mode represented
6847 // by AM is legal for this target, for a load/store of the specified type.
6848 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6849 const Type *Ty) const {
6850 // X86 supports extremely general addressing modes.
6852 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6853 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6857 // We can only fold this if we don't need an extra load.
6858 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6860 // If BaseGV requires a register, we cannot also have a BaseReg.
6861 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6865 // X86-64 only supports addr of globals in small code model.
6866 if (Subtarget->is64Bit()) {
6867 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6869 // If lower 4G is not available, then we must use rip-relative addressing.
6870 if (AM.BaseOffs || AM.Scale > 1)
6881 // These scales always work.
6886 // These scales are formed with basereg+scalereg. Only accept if there is
6891 default: // Other stuff never works.
6899 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6900 if (!Ty1->isInteger() || !Ty2->isInteger())
6902 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6903 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6904 if (NumBits1 <= NumBits2)
6906 return Subtarget->is64Bit() || NumBits1 < 64;
6909 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6910 if (!VT1.isInteger() || !VT2.isInteger())
6912 unsigned NumBits1 = VT1.getSizeInBits();
6913 unsigned NumBits2 = VT2.getSizeInBits();
6914 if (NumBits1 <= NumBits2)
6916 return Subtarget->is64Bit() || NumBits1 < 64;
6919 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6920 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6921 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6922 /// are assumed to be legal.
6924 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6925 // Only do shuffles on 128-bit vector types for now.
6926 if (VT.getSizeInBits() == 64) return false;
6927 return (Mask.getNode()->getNumOperands() <= 4 ||
6928 isIdentityMask(Mask.getNode()) ||
6929 isIdentityMask(Mask.getNode(), true) ||
6930 isSplatMask(Mask.getNode()) ||
6931 isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6932 X86::isUNPCKLMask(Mask.getNode()) ||
6933 X86::isUNPCKHMask(Mask.getNode()) ||
6934 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6935 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6939 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6940 MVT EVT, SelectionDAG &DAG) const {
6941 unsigned NumElts = BVOps.size();
6942 // Only do shuffles on 128-bit vector types for now.
6943 if (EVT.getSizeInBits() * NumElts == 64) return false;
6944 if (NumElts == 2) return true;
6946 return (isMOVLMask(&BVOps[0], 4) ||
6947 isCommutedMOVL(&BVOps[0], 4, true) ||
6948 isSHUFPMask(&BVOps[0], 4) ||
6949 isCommutedSHUFP(&BVOps[0], 4));
6954 //===----------------------------------------------------------------------===//
6955 // X86 Scheduler Hooks
6956 //===----------------------------------------------------------------------===//
6958 // private utility function
6960 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6961 MachineBasicBlock *MBB,
6969 TargetRegisterClass *RC,
6971 // For the atomic bitwise operator, we generate
6974 // ld t1 = [bitinstr.addr]
6975 // op t2 = t1, [bitinstr.val]
6977 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6979 // fallthrough -->nextMBB
6980 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6981 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6982 MachineFunction::iterator MBBIter = MBB;
6985 /// First build the CFG
6986 MachineFunction *F = MBB->getParent();
6987 MachineBasicBlock *thisMBB = MBB;
6988 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6989 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6990 F->insert(MBBIter, newMBB);
6991 F->insert(MBBIter, nextMBB);
6993 // Move all successors to thisMBB to nextMBB
6994 nextMBB->transferSuccessors(thisMBB);
6996 // Update thisMBB to fall through to newMBB
6997 thisMBB->addSuccessor(newMBB);
6999 // newMBB jumps to itself and fall through to nextMBB
7000 newMBB->addSuccessor(nextMBB);
7001 newMBB->addSuccessor(newMBB);
7003 // Insert instructions into newMBB based on incoming instruction
7004 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
7005 DebugLoc dl = bInstr->getDebugLoc();
7006 MachineOperand& destOper = bInstr->getOperand(0);
7007 MachineOperand* argOpers[6];
7008 int numArgs = bInstr->getNumOperands() - 1;
7009 for (int i=0; i < numArgs; ++i)
7010 argOpers[i] = &bInstr->getOperand(i+1);
7012 // x86 address has 4 operands: base, index, scale, and displacement
7013 int lastAddrIndx = 3; // [0,3]
7016 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7017 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7018 for (int i=0; i <= lastAddrIndx; ++i)
7019 (*MIB).addOperand(*argOpers[i]);
7021 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7023 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7028 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7029 assert((argOpers[valArgIndx]->isReg() ||
7030 argOpers[valArgIndx]->isImm()) &&
7032 if (argOpers[valArgIndx]->isReg())
7033 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7035 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7037 (*MIB).addOperand(*argOpers[valArgIndx]);
7039 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7042 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7043 for (int i=0; i <= lastAddrIndx; ++i)
7044 (*MIB).addOperand(*argOpers[i]);
7046 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7047 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7049 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7053 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7055 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7059 // private utility function: 64 bit atomics on 32 bit host.
7061 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7062 MachineBasicBlock *MBB,
7068 // For the atomic bitwise operator, we generate
7069 // thisMBB (instructions are in pairs, except cmpxchg8b)
7070 // ld t1,t2 = [bitinstr.addr]
7072 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7073 // op t5, t6 <- out1, out2, [bitinstr.val]
7074 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7075 // mov ECX, EBX <- t5, t6
7076 // mov EAX, EDX <- t1, t2
7077 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7078 // mov t3, t4 <- EAX, EDX
7080 // result in out1, out2
7081 // fallthrough -->nextMBB
7083 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7084 const unsigned LoadOpc = X86::MOV32rm;
7085 const unsigned copyOpc = X86::MOV32rr;
7086 const unsigned NotOpc = X86::NOT32r;
7087 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7088 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7089 MachineFunction::iterator MBBIter = MBB;
7092 /// First build the CFG
7093 MachineFunction *F = MBB->getParent();
7094 MachineBasicBlock *thisMBB = MBB;
7095 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7096 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7097 F->insert(MBBIter, newMBB);
7098 F->insert(MBBIter, nextMBB);
7100 // Move all successors to thisMBB to nextMBB
7101 nextMBB->transferSuccessors(thisMBB);
7103 // Update thisMBB to fall through to newMBB
7104 thisMBB->addSuccessor(newMBB);
7106 // newMBB jumps to itself and fall through to nextMBB
7107 newMBB->addSuccessor(nextMBB);
7108 newMBB->addSuccessor(newMBB);
7110 DebugLoc dl = bInstr->getDebugLoc();
7111 // Insert instructions into newMBB based on incoming instruction
7112 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7113 assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
7114 MachineOperand& dest1Oper = bInstr->getOperand(0);
7115 MachineOperand& dest2Oper = bInstr->getOperand(1);
7116 MachineOperand* argOpers[6];
7117 for (int i=0; i < 6; ++i)
7118 argOpers[i] = &bInstr->getOperand(i+2);
7120 // x86 address has 4 operands: base, index, scale, and displacement
7121 int lastAddrIndx = 3; // [0,3]
7123 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7124 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7125 for (int i=0; i <= lastAddrIndx; ++i)
7126 (*MIB).addOperand(*argOpers[i]);
7127 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7128 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7129 // add 4 to displacement.
7130 for (int i=0; i <= lastAddrIndx-1; ++i)
7131 (*MIB).addOperand(*argOpers[i]);
7132 MachineOperand newOp3 = *(argOpers[3]);
7134 newOp3.setImm(newOp3.getImm()+4);
7136 newOp3.setOffset(newOp3.getOffset()+4);
7137 (*MIB).addOperand(newOp3);
7139 // t3/4 are defined later, at the bottom of the loop
7140 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7141 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7142 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7143 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7144 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7145 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7147 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7148 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7150 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7151 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7157 assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
7159 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7160 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7161 if (argOpers[4]->isReg())
7162 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7164 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7165 if (regOpcL != X86::MOV32rr)
7167 (*MIB).addOperand(*argOpers[4]);
7168 assert(argOpers[5]->isReg() == argOpers[4]->isReg());
7169 assert(argOpers[5]->isImm() == argOpers[4]->isImm());
7170 if (argOpers[5]->isReg())
7171 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7173 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7174 if (regOpcH != X86::MOV32rr)
7176 (*MIB).addOperand(*argOpers[5]);
7178 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7180 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7183 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7185 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7188 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7189 for (int i=0; i <= lastAddrIndx; ++i)
7190 (*MIB).addOperand(*argOpers[i]);
7192 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7193 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7195 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7196 MIB.addReg(X86::EAX);
7197 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7198 MIB.addReg(X86::EDX);
7201 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7203 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7207 // private utility function
7209 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7210 MachineBasicBlock *MBB,
7212 // For the atomic min/max operator, we generate
7215 // ld t1 = [min/max.addr]
7216 // mov t2 = [min/max.val]
7218 // cmov[cond] t2 = t1
7220 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7222 // fallthrough -->nextMBB
7224 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7225 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7226 MachineFunction::iterator MBBIter = MBB;
7229 /// First build the CFG
7230 MachineFunction *F = MBB->getParent();
7231 MachineBasicBlock *thisMBB = MBB;
7232 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7233 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7234 F->insert(MBBIter, newMBB);
7235 F->insert(MBBIter, nextMBB);
7237 // Move all successors to thisMBB to nextMBB
7238 nextMBB->transferSuccessors(thisMBB);
7240 // Update thisMBB to fall through to newMBB
7241 thisMBB->addSuccessor(newMBB);
7243 // newMBB jumps to newMBB and fall through to nextMBB
7244 newMBB->addSuccessor(nextMBB);
7245 newMBB->addSuccessor(newMBB);
7247 DebugLoc dl = mInstr->getDebugLoc();
7248 // Insert instructions into newMBB based on incoming instruction
7249 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
7250 MachineOperand& destOper = mInstr->getOperand(0);
7251 MachineOperand* argOpers[6];
7252 int numArgs = mInstr->getNumOperands() - 1;
7253 for (int i=0; i < numArgs; ++i)
7254 argOpers[i] = &mInstr->getOperand(i+1);
7256 // x86 address has 4 operands: base, index, scale, and displacement
7257 int lastAddrIndx = 3; // [0,3]
7260 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7261 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7262 for (int i=0; i <= lastAddrIndx; ++i)
7263 (*MIB).addOperand(*argOpers[i]);
7265 // We only support register and immediate values
7266 assert((argOpers[valArgIndx]->isReg() ||
7267 argOpers[valArgIndx]->isImm()) &&
7270 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7271 if (argOpers[valArgIndx]->isReg())
7272 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7274 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7275 (*MIB).addOperand(*argOpers[valArgIndx]);
7277 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7280 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7285 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7286 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7290 // Cmp and exchange if none has modified the memory location
7291 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7292 for (int i=0; i <= lastAddrIndx; ++i)
7293 (*MIB).addOperand(*argOpers[i]);
7295 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7296 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7298 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7299 MIB.addReg(X86::EAX);
7302 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7304 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7310 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7311 MachineBasicBlock *BB) {
7312 DebugLoc dl = MI->getDebugLoc();
7313 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7314 switch (MI->getOpcode()) {
7315 default: assert(false && "Unexpected instr type to insert");
7316 case X86::CMOV_V1I64:
7317 case X86::CMOV_FR32:
7318 case X86::CMOV_FR64:
7319 case X86::CMOV_V4F32:
7320 case X86::CMOV_V2F64:
7321 case X86::CMOV_V2I64: {
7322 // To "insert" a SELECT_CC instruction, we actually have to insert the
7323 // diamond control-flow pattern. The incoming instruction knows the
7324 // destination vreg to set, the condition code register to branch on, the
7325 // true/false values to select between, and a branch opcode to use.
7326 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7327 MachineFunction::iterator It = BB;
7333 // cmpTY ccX, r1, r2
7335 // fallthrough --> copy0MBB
7336 MachineBasicBlock *thisMBB = BB;
7337 MachineFunction *F = BB->getParent();
7338 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7339 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7341 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7342 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7343 F->insert(It, copy0MBB);
7344 F->insert(It, sinkMBB);
7345 // Update machine-CFG edges by transferring all successors of the current
7346 // block to the new block which will contain the Phi node for the select.
7347 sinkMBB->transferSuccessors(BB);
7349 // Add the true and fallthrough blocks as its successors.
7350 BB->addSuccessor(copy0MBB);
7351 BB->addSuccessor(sinkMBB);
7354 // %FalseValue = ...
7355 // # fallthrough to sinkMBB
7358 // Update machine-CFG edges
7359 BB->addSuccessor(sinkMBB);
7362 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7365 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7366 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7367 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7369 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7373 case X86::FP32_TO_INT16_IN_MEM:
7374 case X86::FP32_TO_INT32_IN_MEM:
7375 case X86::FP32_TO_INT64_IN_MEM:
7376 case X86::FP64_TO_INT16_IN_MEM:
7377 case X86::FP64_TO_INT32_IN_MEM:
7378 case X86::FP64_TO_INT64_IN_MEM:
7379 case X86::FP80_TO_INT16_IN_MEM:
7380 case X86::FP80_TO_INT32_IN_MEM:
7381 case X86::FP80_TO_INT64_IN_MEM: {
7382 // Change the floating point control register to use "round towards zero"
7383 // mode when truncating to an integer value.
7384 MachineFunction *F = BB->getParent();
7385 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7386 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7388 // Load the old value of the high byte of the control word...
7390 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7391 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7394 // Set the high part to be round to zero...
7395 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7398 // Reload the modified control word now...
7399 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7401 // Restore the memory image of control word to original value
7402 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7405 // Get the X86 opcode to use.
7407 switch (MI->getOpcode()) {
7408 default: assert(0 && "illegal opcode!");
7409 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7410 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7411 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7412 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7413 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7414 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7415 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7416 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7417 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7421 MachineOperand &Op = MI->getOperand(0);
7423 AM.BaseType = X86AddressMode::RegBase;
7424 AM.Base.Reg = Op.getReg();
7426 AM.BaseType = X86AddressMode::FrameIndexBase;
7427 AM.Base.FrameIndex = Op.getIndex();
7429 Op = MI->getOperand(1);
7431 AM.Scale = Op.getImm();
7432 Op = MI->getOperand(2);
7434 AM.IndexReg = Op.getImm();
7435 Op = MI->getOperand(3);
7436 if (Op.isGlobal()) {
7437 AM.GV = Op.getGlobal();
7439 AM.Disp = Op.getImm();
7441 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7442 .addReg(MI->getOperand(4).getReg());
7444 // Reload the original control word now.
7445 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7447 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7450 case X86::ATOMAND32:
7451 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7452 X86::AND32ri, X86::MOV32rm,
7453 X86::LCMPXCHG32, X86::MOV32rr,
7454 X86::NOT32r, X86::EAX,
7455 X86::GR32RegisterClass);
7457 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7458 X86::OR32ri, X86::MOV32rm,
7459 X86::LCMPXCHG32, X86::MOV32rr,
7460 X86::NOT32r, X86::EAX,
7461 X86::GR32RegisterClass);
7462 case X86::ATOMXOR32:
7463 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7464 X86::XOR32ri, X86::MOV32rm,
7465 X86::LCMPXCHG32, X86::MOV32rr,
7466 X86::NOT32r, X86::EAX,
7467 X86::GR32RegisterClass);
7468 case X86::ATOMNAND32:
7469 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7470 X86::AND32ri, X86::MOV32rm,
7471 X86::LCMPXCHG32, X86::MOV32rr,
7472 X86::NOT32r, X86::EAX,
7473 X86::GR32RegisterClass, true);
7474 case X86::ATOMMIN32:
7475 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7476 case X86::ATOMMAX32:
7477 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7478 case X86::ATOMUMIN32:
7479 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7480 case X86::ATOMUMAX32:
7481 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7483 case X86::ATOMAND16:
7484 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7485 X86::AND16ri, X86::MOV16rm,
7486 X86::LCMPXCHG16, X86::MOV16rr,
7487 X86::NOT16r, X86::AX,
7488 X86::GR16RegisterClass);
7490 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7491 X86::OR16ri, X86::MOV16rm,
7492 X86::LCMPXCHG16, X86::MOV16rr,
7493 X86::NOT16r, X86::AX,
7494 X86::GR16RegisterClass);
7495 case X86::ATOMXOR16:
7496 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7497 X86::XOR16ri, X86::MOV16rm,
7498 X86::LCMPXCHG16, X86::MOV16rr,
7499 X86::NOT16r, X86::AX,
7500 X86::GR16RegisterClass);
7501 case X86::ATOMNAND16:
7502 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7503 X86::AND16ri, X86::MOV16rm,
7504 X86::LCMPXCHG16, X86::MOV16rr,
7505 X86::NOT16r, X86::AX,
7506 X86::GR16RegisterClass, true);
7507 case X86::ATOMMIN16:
7508 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7509 case X86::ATOMMAX16:
7510 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7511 case X86::ATOMUMIN16:
7512 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7513 case X86::ATOMUMAX16:
7514 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7517 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7518 X86::AND8ri, X86::MOV8rm,
7519 X86::LCMPXCHG8, X86::MOV8rr,
7520 X86::NOT8r, X86::AL,
7521 X86::GR8RegisterClass);
7523 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7524 X86::OR8ri, X86::MOV8rm,
7525 X86::LCMPXCHG8, X86::MOV8rr,
7526 X86::NOT8r, X86::AL,
7527 X86::GR8RegisterClass);
7529 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7530 X86::XOR8ri, X86::MOV8rm,
7531 X86::LCMPXCHG8, X86::MOV8rr,
7532 X86::NOT8r, X86::AL,
7533 X86::GR8RegisterClass);
7534 case X86::ATOMNAND8:
7535 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7536 X86::AND8ri, X86::MOV8rm,
7537 X86::LCMPXCHG8, X86::MOV8rr,
7538 X86::NOT8r, X86::AL,
7539 X86::GR8RegisterClass, true);
7540 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7541 // This group is for 64-bit host.
7542 case X86::ATOMAND64:
7543 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7544 X86::AND64ri32, X86::MOV64rm,
7545 X86::LCMPXCHG64, X86::MOV64rr,
7546 X86::NOT64r, X86::RAX,
7547 X86::GR64RegisterClass);
7549 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7550 X86::OR64ri32, X86::MOV64rm,
7551 X86::LCMPXCHG64, X86::MOV64rr,
7552 X86::NOT64r, X86::RAX,
7553 X86::GR64RegisterClass);
7554 case X86::ATOMXOR64:
7555 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7556 X86::XOR64ri32, X86::MOV64rm,
7557 X86::LCMPXCHG64, X86::MOV64rr,
7558 X86::NOT64r, X86::RAX,
7559 X86::GR64RegisterClass);
7560 case X86::ATOMNAND64:
7561 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7562 X86::AND64ri32, X86::MOV64rm,
7563 X86::LCMPXCHG64, X86::MOV64rr,
7564 X86::NOT64r, X86::RAX,
7565 X86::GR64RegisterClass, true);
7566 case X86::ATOMMIN64:
7567 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7568 case X86::ATOMMAX64:
7569 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7570 case X86::ATOMUMIN64:
7571 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7572 case X86::ATOMUMAX64:
7573 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7575 // This group does 64-bit operations on a 32-bit host.
7576 case X86::ATOMAND6432:
7577 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7578 X86::AND32rr, X86::AND32rr,
7579 X86::AND32ri, X86::AND32ri,
7581 case X86::ATOMOR6432:
7582 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7583 X86::OR32rr, X86::OR32rr,
7584 X86::OR32ri, X86::OR32ri,
7586 case X86::ATOMXOR6432:
7587 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7588 X86::XOR32rr, X86::XOR32rr,
7589 X86::XOR32ri, X86::XOR32ri,
7591 case X86::ATOMNAND6432:
7592 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7593 X86::AND32rr, X86::AND32rr,
7594 X86::AND32ri, X86::AND32ri,
7596 case X86::ATOMADD6432:
7597 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7598 X86::ADD32rr, X86::ADC32rr,
7599 X86::ADD32ri, X86::ADC32ri,
7601 case X86::ATOMSUB6432:
7602 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7603 X86::SUB32rr, X86::SBB32rr,
7604 X86::SUB32ri, X86::SBB32ri,
7606 case X86::ATOMSWAP6432:
7607 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7608 X86::MOV32rr, X86::MOV32rr,
7609 X86::MOV32ri, X86::MOV32ri,
7614 //===----------------------------------------------------------------------===//
7615 // X86 Optimization Hooks
7616 //===----------------------------------------------------------------------===//
7618 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7622 const SelectionDAG &DAG,
7623 unsigned Depth) const {
7624 unsigned Opc = Op.getOpcode();
7625 assert((Opc >= ISD::BUILTIN_OP_END ||
7626 Opc == ISD::INTRINSIC_WO_CHAIN ||
7627 Opc == ISD::INTRINSIC_W_CHAIN ||
7628 Opc == ISD::INTRINSIC_VOID) &&
7629 "Should use MaskedValueIsZero if you don't know whether Op"
7630 " is a target node!");
7632 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7639 // These nodes' second result is a boolean.
7640 if (Op.getResNo() == 0)
7644 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7645 Mask.getBitWidth() - 1);
7650 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7651 /// node is a GlobalAddress + offset.
7652 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7653 GlobalValue* &GA, int64_t &Offset) const{
7654 if (N->getOpcode() == X86ISD::Wrapper) {
7655 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7656 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7657 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7661 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7664 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7665 const TargetLowering &TLI) {
7668 if (TLI.isGAPlusOffset(Base, GV, Offset))
7669 return (GV->getAlignment() >= N && (Offset % N) == 0);
7670 // DAG combine handles the stack object case.
7674 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
7675 unsigned NumElems, MVT EVT,
7677 SelectionDAG &DAG, MachineFrameInfo *MFI,
7678 const TargetLowering &TLI) {
7680 for (unsigned i = 0; i < NumElems; ++i) {
7681 SDValue Idx = PermMask.getOperand(i);
7682 if (Idx.getOpcode() == ISD::UNDEF) {
7688 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7689 if (!Elt.getNode() ||
7690 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7693 Base = Elt.getNode();
7694 if (Base->getOpcode() == ISD::UNDEF)
7698 if (Elt.getOpcode() == ISD::UNDEF)
7701 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7702 EVT.getSizeInBits()/8, i, MFI))
7708 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7709 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7710 /// if the load addresses are consecutive, non-overlapping, and in the right
7712 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7713 const TargetLowering &TLI) {
7714 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7715 DebugLoc dl = N->getDebugLoc();
7716 MVT VT = N->getValueType(0);
7717 MVT EVT = VT.getVectorElementType();
7718 SDValue PermMask = N->getOperand(2);
7719 unsigned NumElems = PermMask.getNumOperands();
7720 SDNode *Base = NULL;
7721 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
7725 LoadSDNode *LD = cast<LoadSDNode>(Base);
7726 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7727 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7728 LD->getSrcValue(), LD->getSrcValueOffset(),
7730 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7731 LD->getSrcValue(), LD->getSrcValueOffset(),
7732 LD->isVolatile(), LD->getAlignment());
7735 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7736 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7737 TargetLowering::DAGCombinerInfo &DCI,
7738 const X86Subtarget *Subtarget,
7739 const TargetLowering &TLI) {
7740 unsigned NumOps = N->getNumOperands();
7741 DebugLoc dl = N->getDebugLoc();
7743 // Ignore single operand BUILD_VECTOR.
7747 MVT VT = N->getValueType(0);
7748 MVT EVT = VT.getVectorElementType();
7749 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7750 // We are looking for load i64 and zero extend. We want to transform
7751 // it before legalizer has a chance to expand it. Also look for i64
7752 // BUILD_PAIR bit casted to f64.
7754 // This must be an insertion into a zero vector.
7755 SDValue HighElt = N->getOperand(1);
7756 if (!isZeroNode(HighElt))
7759 // Value must be a load.
7760 SDNode *Base = N->getOperand(0).getNode();
7761 if (!isa<LoadSDNode>(Base)) {
7762 if (Base->getOpcode() != ISD::BIT_CONVERT)
7764 Base = Base->getOperand(0).getNode();
7765 if (!isa<LoadSDNode>(Base))
7769 // Transform it into VZEXT_LOAD addr.
7770 LoadSDNode *LD = cast<LoadSDNode>(Base);
7772 // Load must not be an extload.
7773 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7776 // Load type should legal type so we don't have to legalize it.
7777 if (!TLI.isTypeLegal(VT))
7780 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7781 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7782 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7783 TargetLowering::TargetLoweringOpt TLO(DAG);
7784 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
7785 DCI.CommitTargetLoweringOpt(TLO);
7789 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7790 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7791 const X86Subtarget *Subtarget) {
7792 DebugLoc dl = N->getDebugLoc();
7793 SDValue Cond = N->getOperand(0);
7795 // If we have SSE[12] support, try to form min/max nodes.
7796 if (Subtarget->hasSSE2() &&
7797 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
7798 if (Cond.getOpcode() == ISD::SETCC) {
7799 // Get the LHS/RHS of the select.
7800 SDValue LHS = N->getOperand(1);
7801 SDValue RHS = N->getOperand(2);
7802 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7804 unsigned Opcode = 0;
7805 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7808 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7811 if (!UnsafeFPMath) break;
7813 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7815 Opcode = X86ISD::FMIN;
7818 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7821 if (!UnsafeFPMath) break;
7823 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7825 Opcode = X86ISD::FMAX;
7828 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7831 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7834 if (!UnsafeFPMath) break;
7836 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7838 Opcode = X86ISD::FMIN;
7841 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7844 if (!UnsafeFPMath) break;
7846 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7848 Opcode = X86ISD::FMAX;
7854 return DAG.getNode(Opcode, dl, N->getValueType(0), LHS, RHS);
7862 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
7864 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
7865 const X86Subtarget *Subtarget) {
7866 // On X86 with SSE2 support, we can transform this to a vector shift if
7867 // all elements are shifted by the same amount. We can't do this in legalize
7868 // because the a constant vector is typically transformed to a constant pool
7869 // so we have no knowledge of the shift amount.
7870 if (!Subtarget->hasSSE2())
7873 MVT VT = N->getValueType(0);
7874 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
7877 SDValue ShAmtOp = N->getOperand(1);
7878 MVT EltVT = VT.getVectorElementType();
7879 DebugLoc dl = N->getDebugLoc();
7881 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
7882 unsigned NumElts = VT.getVectorNumElements();
7884 for (; i != NumElts; ++i) {
7885 SDValue Arg = ShAmtOp.getOperand(i);
7886 if (Arg.getOpcode() == ISD::UNDEF) continue;
7890 for (; i != NumElts; ++i) {
7891 SDValue Arg = ShAmtOp.getOperand(i);
7892 if (Arg.getOpcode() == ISD::UNDEF) continue;
7893 if (Arg != BaseShAmt) {
7897 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
7898 isSplatMask(ShAmtOp.getOperand(2).getNode())) {
7899 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, ShAmtOp,
7900 DAG.getIntPtrConstant(0));
7904 if (EltVT.bitsGT(MVT::i32))
7905 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
7906 else if (EltVT.bitsLT(MVT::i32))
7907 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BaseShAmt);
7909 // The shift amount is identical so we can do a vector shift.
7910 SDValue ValOp = N->getOperand(0);
7911 switch (N->getOpcode()) {
7913 assert(0 && "Unknown shift opcode!");
7916 if (VT == MVT::v2i64)
7917 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7918 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7920 if (VT == MVT::v4i32)
7921 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7922 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
7924 if (VT == MVT::v8i16)
7925 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7926 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
7930 if (VT == MVT::v4i32)
7931 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7932 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
7934 if (VT == MVT::v8i16)
7935 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7936 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
7940 if (VT == MVT::v2i64)
7941 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7942 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7944 if (VT == MVT::v4i32)
7945 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7946 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
7948 if (VT == MVT::v8i16)
7949 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7950 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
7957 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
7958 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
7959 const X86Subtarget *Subtarget) {
7960 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
7961 // the FP state in cases where an emms may be missing.
7962 // A preferable solution to the general problem is to figure out the right
7963 // places to insert EMMS. This qualifies as a quick hack.
7964 StoreSDNode *St = cast<StoreSDNode>(N);
7965 if (St->getValue().getValueType().isVector() &&
7966 St->getValue().getValueType().getSizeInBits() == 64 &&
7967 isa<LoadSDNode>(St->getValue()) &&
7968 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
7969 St->getChain().hasOneUse() && !St->isVolatile()) {
7970 SDNode* LdVal = St->getValue().getNode();
7972 int TokenFactorIndex = -1;
7973 SmallVector<SDValue, 8> Ops;
7974 SDNode* ChainVal = St->getChain().getNode();
7975 // Must be a store of a load. We currently handle two cases: the load
7976 // is a direct child, and it's under an intervening TokenFactor. It is
7977 // possible to dig deeper under nested TokenFactors.
7978 if (ChainVal == LdVal)
7979 Ld = cast<LoadSDNode>(St->getChain());
7980 else if (St->getValue().hasOneUse() &&
7981 ChainVal->getOpcode() == ISD::TokenFactor) {
7982 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
7983 if (ChainVal->getOperand(i).getNode() == LdVal) {
7984 TokenFactorIndex = i;
7985 Ld = cast<LoadSDNode>(St->getValue());
7987 Ops.push_back(ChainVal->getOperand(i));
7991 DebugLoc dl = N->getDebugLoc();
7992 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
7993 if (Subtarget->is64Bit()) {
7994 SDValue NewLd = DAG.getLoad(MVT::i64, dl, Ld->getChain(),
7995 Ld->getBasePtr(), Ld->getSrcValue(),
7996 Ld->getSrcValueOffset(), Ld->isVolatile(),
7997 Ld->getAlignment());
7998 SDValue NewChain = NewLd.getValue(1);
7999 if (TokenFactorIndex != -1) {
8000 Ops.push_back(NewChain);
8001 NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Ops[0],
8004 return DAG.getStore(NewChain, dl, NewLd, St->getBasePtr(),
8005 St->getSrcValue(), St->getSrcValueOffset(),
8006 St->isVolatile(), St->getAlignment());
8009 // Otherwise, lower to two 32-bit copies.
8010 SDValue LoAddr = Ld->getBasePtr();
8011 SDValue HiAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, LoAddr,
8012 DAG.getConstant(4, MVT::i32));
8014 SDValue LoLd = DAG.getLoad(MVT::i32, dl, Ld->getChain(), LoAddr,
8015 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8016 Ld->isVolatile(), Ld->getAlignment());
8017 SDValue HiLd = DAG.getLoad(MVT::i32, dl, Ld->getChain(), HiAddr,
8018 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8020 MinAlign(Ld->getAlignment(), 4));
8022 SDValue NewChain = LoLd.getValue(1);
8023 if (TokenFactorIndex != -1) {
8024 Ops.push_back(LoLd);
8025 Ops.push_back(HiLd);
8026 NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Ops[0],
8030 LoAddr = St->getBasePtr();
8031 HiAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, LoAddr,
8032 DAG.getConstant(4, MVT::i32));
8034 SDValue LoSt = DAG.getStore(NewChain, dl, LoLd, LoAddr,
8035 St->getSrcValue(), St->getSrcValueOffset(),
8036 St->isVolatile(), St->getAlignment());
8037 SDValue HiSt = DAG.getStore(NewChain, dl, HiLd, HiAddr,
8039 St->getSrcValueOffset() + 4,
8041 MinAlign(St->getAlignment(), 4));
8042 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoSt, HiSt);
8048 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8049 /// X86ISD::FXOR nodes.
8050 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8051 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8052 // F[X]OR(0.0, x) -> x
8053 // F[X]OR(x, 0.0) -> x
8054 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8055 if (C->getValueAPF().isPosZero())
8056 return N->getOperand(1);
8057 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8058 if (C->getValueAPF().isPosZero())
8059 return N->getOperand(0);
8063 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8064 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8065 // FAND(0.0, x) -> 0.0
8066 // FAND(x, 0.0) -> 0.0
8067 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8068 if (C->getValueAPF().isPosZero())
8069 return N->getOperand(0);
8070 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8071 if (C->getValueAPF().isPosZero())
8072 return N->getOperand(1);
8076 static SDValue PerformBTCombine(SDNode *N,
8078 TargetLowering::DAGCombinerInfo &DCI) {
8079 // BT ignores high bits in the bit index operand.
8080 SDValue Op1 = N->getOperand(1);
8081 if (Op1.hasOneUse()) {
8082 unsigned BitWidth = Op1.getValueSizeInBits();
8083 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8084 APInt KnownZero, KnownOne;
8085 TargetLowering::TargetLoweringOpt TLO(DAG);
8086 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8087 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8088 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8089 DCI.CommitTargetLoweringOpt(TLO);
8094 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8095 DAGCombinerInfo &DCI) const {
8096 SelectionDAG &DAG = DCI.DAG;
8097 switch (N->getOpcode()) {
8099 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8100 case ISD::BUILD_VECTOR:
8101 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8102 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8105 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8106 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8108 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8109 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8110 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8116 //===----------------------------------------------------------------------===//
8117 // X86 Inline Assembly Support
8118 //===----------------------------------------------------------------------===//
8120 /// getConstraintType - Given a constraint letter, return the type of
8121 /// constraint it is for this target.
8122 X86TargetLowering::ConstraintType
8123 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8124 if (Constraint.size() == 1) {
8125 switch (Constraint[0]) {
8137 return C_RegisterClass;
8142 return TargetLowering::getConstraintType(Constraint);
8145 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8146 /// with another that has more specific requirements based on the type of the
8147 /// corresponding operand.
8148 const char *X86TargetLowering::
8149 LowerXConstraint(MVT ConstraintVT) const {
8150 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8151 // 'f' like normal targets.
8152 if (ConstraintVT.isFloatingPoint()) {
8153 if (Subtarget->hasSSE2())
8155 if (Subtarget->hasSSE1())
8159 return TargetLowering::LowerXConstraint(ConstraintVT);
8162 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8163 /// vector. If it is invalid, don't add anything to Ops.
8164 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8167 std::vector<SDValue>&Ops,
8168 SelectionDAG &DAG) const {
8169 SDValue Result(0, 0);
8171 switch (Constraint) {
8174 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8175 if (C->getZExtValue() <= 31) {
8176 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8182 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8183 if (C->getZExtValue() <= 63) {
8184 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8190 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8191 if (C->getZExtValue() <= 255) {
8192 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8198 // Literal immediates are always ok.
8199 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8200 Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
8204 // If we are in non-pic codegen mode, we allow the address of a global (with
8205 // an optional displacement) to be used with 'i'.
8206 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
8209 // Match either (GA) or (GA+C)
8211 Offset = GA->getOffset();
8212 } else if (Op.getOpcode() == ISD::ADD) {
8213 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8214 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8216 Offset = GA->getOffset()+C->getZExtValue();
8218 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8219 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8221 Offset = GA->getOffset()+C->getZExtValue();
8229 Op = LowerGlobalAddress(GA->getGlobal(), Offset, DAG);
8231 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8237 // Otherwise, not valid for this mode.
8242 if (Result.getNode()) {
8243 Ops.push_back(Result);
8246 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8250 std::vector<unsigned> X86TargetLowering::
8251 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8253 if (Constraint.size() == 1) {
8254 // FIXME: not handling fp-stack yet!
8255 switch (Constraint[0]) { // GCC X86 Constraint Letters
8256 default: break; // Unknown constraint letter
8257 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8260 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8261 else if (VT == MVT::i16)
8262 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8263 else if (VT == MVT::i8)
8264 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8265 else if (VT == MVT::i64)
8266 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8271 return std::vector<unsigned>();
8274 std::pair<unsigned, const TargetRegisterClass*>
8275 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8277 // First, see if this is a constraint that directly corresponds to an LLVM
8279 if (Constraint.size() == 1) {
8280 // GCC Constraint Letters
8281 switch (Constraint[0]) {
8283 case 'r': // GENERAL_REGS
8284 case 'R': // LEGACY_REGS
8285 case 'l': // INDEX_REGS
8287 return std::make_pair(0U, X86::GR8RegisterClass);
8289 return std::make_pair(0U, X86::GR16RegisterClass);
8290 if (VT == MVT::i32 || !Subtarget->is64Bit())
8291 return std::make_pair(0U, X86::GR32RegisterClass);
8292 return std::make_pair(0U, X86::GR64RegisterClass);
8293 case 'f': // FP Stack registers.
8294 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8295 // value to the correct fpstack register class.
8296 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8297 return std::make_pair(0U, X86::RFP32RegisterClass);
8298 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8299 return std::make_pair(0U, X86::RFP64RegisterClass);
8300 return std::make_pair(0U, X86::RFP80RegisterClass);
8301 case 'y': // MMX_REGS if MMX allowed.
8302 if (!Subtarget->hasMMX()) break;
8303 return std::make_pair(0U, X86::VR64RegisterClass);
8304 case 'Y': // SSE_REGS if SSE2 allowed
8305 if (!Subtarget->hasSSE2()) break;
8307 case 'x': // SSE_REGS if SSE1 allowed
8308 if (!Subtarget->hasSSE1()) break;
8310 switch (VT.getSimpleVT()) {
8312 // Scalar SSE types.
8315 return std::make_pair(0U, X86::FR32RegisterClass);
8318 return std::make_pair(0U, X86::FR64RegisterClass);
8326 return std::make_pair(0U, X86::VR128RegisterClass);
8332 // Use the default implementation in TargetLowering to convert the register
8333 // constraint into a member of a register class.
8334 std::pair<unsigned, const TargetRegisterClass*> Res;
8335 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8337 // Not found as a standard register?
8338 if (Res.second == 0) {
8339 // GCC calls "st(0)" just plain "st".
8340 if (StringsEqualNoCase("{st}", Constraint)) {
8341 Res.first = X86::ST0;
8342 Res.second = X86::RFP80RegisterClass;
8344 // 'A' means EAX + EDX.
8345 if (Constraint == "A") {
8346 Res.first = X86::EAX;
8347 Res.second = X86::GRADRegisterClass;
8352 // Otherwise, check to see if this is a register class of the wrong value
8353 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8354 // turn into {ax},{dx}.
8355 if (Res.second->hasType(VT))
8356 return Res; // Correct type already, nothing to do.
8358 // All of the single-register GCC register classes map their values onto
8359 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8360 // really want an 8-bit or 32-bit register, map to the appropriate register
8361 // class and return the appropriate register.
8362 if (Res.second == X86::GR16RegisterClass) {
8363 if (VT == MVT::i8) {
8364 unsigned DestReg = 0;
8365 switch (Res.first) {
8367 case X86::AX: DestReg = X86::AL; break;
8368 case X86::DX: DestReg = X86::DL; break;
8369 case X86::CX: DestReg = X86::CL; break;
8370 case X86::BX: DestReg = X86::BL; break;
8373 Res.first = DestReg;
8374 Res.second = Res.second = X86::GR8RegisterClass;
8376 } else if (VT == MVT::i32) {
8377 unsigned DestReg = 0;
8378 switch (Res.first) {
8380 case X86::AX: DestReg = X86::EAX; break;
8381 case X86::DX: DestReg = X86::EDX; break;
8382 case X86::CX: DestReg = X86::ECX; break;
8383 case X86::BX: DestReg = X86::EBX; break;
8384 case X86::SI: DestReg = X86::ESI; break;
8385 case X86::DI: DestReg = X86::EDI; break;
8386 case X86::BP: DestReg = X86::EBP; break;
8387 case X86::SP: DestReg = X86::ESP; break;
8390 Res.first = DestReg;
8391 Res.second = Res.second = X86::GR32RegisterClass;
8393 } else if (VT == MVT::i64) {
8394 unsigned DestReg = 0;
8395 switch (Res.first) {
8397 case X86::AX: DestReg = X86::RAX; break;
8398 case X86::DX: DestReg = X86::RDX; break;
8399 case X86::CX: DestReg = X86::RCX; break;
8400 case X86::BX: DestReg = X86::RBX; break;
8401 case X86::SI: DestReg = X86::RSI; break;
8402 case X86::DI: DestReg = X86::RDI; break;
8403 case X86::BP: DestReg = X86::RBP; break;
8404 case X86::SP: DestReg = X86::RSP; break;
8407 Res.first = DestReg;
8408 Res.second = Res.second = X86::GR64RegisterClass;
8411 } else if (Res.second == X86::FR32RegisterClass ||
8412 Res.second == X86::FR64RegisterClass ||
8413 Res.second == X86::VR128RegisterClass) {
8414 // Handle references to XMM physical registers that got mapped into the
8415 // wrong class. This can happen with constraints like {xmm0} where the
8416 // target independent register mapper will just pick the first match it can
8417 // find, ignoring the required type.
8419 Res.second = X86::FR32RegisterClass;
8420 else if (VT == MVT::f64)
8421 Res.second = X86::FR64RegisterClass;
8422 else if (X86::VR128RegisterClass->hasType(VT))
8423 Res.second = X86::VR128RegisterClass;
8429 //===----------------------------------------------------------------------===//
8430 // X86 Widen vector type
8431 //===----------------------------------------------------------------------===//
8433 /// getWidenVectorType: given a vector type, returns the type to widen
8434 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8435 /// If there is no vector type that we want to widen to, returns MVT::Other
8436 /// When and where to widen is target dependent based on the cost of
8437 /// scalarizing vs using the wider vector type.
8439 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8440 assert(VT.isVector());
8441 if (isTypeLegal(VT))
8444 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8445 // type based on element type. This would speed up our search (though
8446 // it may not be worth it since the size of the list is relatively
8448 MVT EltVT = VT.getVectorElementType();
8449 unsigned NElts = VT.getVectorNumElements();
8451 // On X86, it make sense to widen any vector wider than 1
8455 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8456 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8457 MVT SVT = (MVT::SimpleValueType)nVT;
8459 if (isTypeLegal(SVT) &&
8460 SVT.getVectorElementType() == EltVT &&
8461 SVT.getVectorNumElements() > NElts)