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 "X86TargetMachine.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Function.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/VectorExtras.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/PseudoSourceValue.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/CommandLine.h"
42 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
44 // Forward declarations.
45 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
48 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
49 : TargetLowering(TM) {
50 Subtarget = &TM.getSubtarget<X86Subtarget>();
51 X86ScalarSSEf64 = Subtarget->hasSSE2();
52 X86ScalarSSEf32 = Subtarget->hasSSE1();
53 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
55 RegInfo = TM.getRegisterInfo();
58 // Set up the TargetLowering object.
60 // X86 is weird, it always uses i8 for shift amounts and setcc results.
61 setShiftAmountType(MVT::i8);
62 setBooleanContents(ZeroOrOneBooleanContent);
63 setSchedulingPreference(SchedulingForRegPressure);
64 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
65 setStackPointerRegisterToSaveRestore(X86StackPtr);
67 if (Subtarget->isTargetDarwin()) {
68 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
69 setUseUnderscoreSetJmp(false);
70 setUseUnderscoreLongJmp(false);
71 } else if (Subtarget->isTargetMingw()) {
72 // MS runtime is weird: it exports _setjmp, but longjmp!
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(false);
76 setUseUnderscoreSetJmp(true);
77 setUseUnderscoreLongJmp(true);
80 // Set up the register classes.
81 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
82 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
83 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
84 if (Subtarget->is64Bit())
85 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
87 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
89 // We don't accept any truncstore of integer registers.
90 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
91 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
92 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
93 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
94 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
95 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
97 // SETOEQ and SETUNE require checking two conditions.
98 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
99 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
100 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
101 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
102 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
103 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
105 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
107 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
108 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
109 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
111 if (Subtarget->is64Bit()) {
112 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
114 } else if (!UseSoftFloat) {
115 if (X86ScalarSSEf64) {
116 // We have an impenetrably clever algorithm for ui64->double only.
117 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
119 // We have an algorithm for SSE2, and we turn this into a 64-bit
120 // FILD for other targets.
121 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
124 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
126 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
127 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
130 // SSE has no i16 to fp conversion, only i32
131 if (X86ScalarSSEf32) {
132 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
133 // f32 and f64 cases are Legal, f80 case is not
134 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
136 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
137 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
140 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
141 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
144 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
145 // are Legal, f80 is custom lowered.
146 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
147 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
149 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
151 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
152 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
154 if (X86ScalarSSEf32) {
155 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
156 // f32 and f64 cases are Legal, f80 case is not
157 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
159 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
160 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
163 // Handle FP_TO_UINT by promoting the destination to a larger signed
165 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
166 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
167 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
169 if (Subtarget->is64Bit()) {
170 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
171 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
172 } else if (!UseSoftFloat) {
173 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
174 // Expand FP_TO_UINT into a select.
175 // FIXME: We would like to use a Custom expander here eventually to do
176 // the optimal thing for SSE vs. the default expansion in the legalizer.
177 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
179 // With SSE3 we can use fisttpll to convert to a signed i64; without
180 // SSE, we're stuck with a fistpll.
181 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
184 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
185 if (!X86ScalarSSEf64) {
186 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
187 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
190 // Scalar integer divide and remainder are lowered to use operations that
191 // produce two results, to match the available instructions. This exposes
192 // the two-result form to trivial CSE, which is able to combine x/y and x%y
193 // into a single instruction.
195 // Scalar integer multiply-high is also lowered to use two-result
196 // operations, to match the available instructions. However, plain multiply
197 // (low) operations are left as Legal, as there are single-result
198 // instructions for this in x86. Using the two-result multiply instructions
199 // when both high and low results are needed must be arranged by dagcombine.
200 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
201 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
202 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
203 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
204 setOperationAction(ISD::SREM , MVT::i8 , Expand);
205 setOperationAction(ISD::UREM , MVT::i8 , Expand);
206 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
207 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
208 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
209 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
210 setOperationAction(ISD::SREM , MVT::i16 , Expand);
211 setOperationAction(ISD::UREM , MVT::i16 , Expand);
212 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
213 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
214 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
215 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
216 setOperationAction(ISD::SREM , MVT::i32 , Expand);
217 setOperationAction(ISD::UREM , MVT::i32 , Expand);
218 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
219 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
220 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
221 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
222 setOperationAction(ISD::SREM , MVT::i64 , Expand);
223 setOperationAction(ISD::UREM , MVT::i64 , Expand);
225 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
226 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
227 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
228 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
229 if (Subtarget->is64Bit())
230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
234 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
235 setOperationAction(ISD::FREM , MVT::f32 , Expand);
236 setOperationAction(ISD::FREM , MVT::f64 , Expand);
237 setOperationAction(ISD::FREM , MVT::f80 , Expand);
238 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
240 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
241 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
242 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
243 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
244 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
245 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
246 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
247 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
248 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
249 if (Subtarget->is64Bit()) {
250 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
251 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
252 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
255 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
256 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
258 // These should be promoted to a larger select which is supported.
259 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
260 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
261 // X86 wants to expand cmov itself.
262 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
263 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
264 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
265 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
266 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
267 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
268 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
269 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
270 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
271 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
272 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
273 if (Subtarget->is64Bit()) {
274 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
275 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
277 // X86 ret instruction may pop stack.
278 setOperationAction(ISD::RET , MVT::Other, Custom);
279 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
282 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
283 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
284 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
285 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
286 if (Subtarget->is64Bit())
287 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
288 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
289 if (Subtarget->is64Bit()) {
290 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
291 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
292 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
293 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
295 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
296 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
297 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
298 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
299 if (Subtarget->is64Bit()) {
300 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
301 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
302 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
305 if (Subtarget->hasSSE1())
306 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
308 if (!Subtarget->hasSSE2())
309 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
311 // Expand certain atomics
312 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
313 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
314 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
315 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
317 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
318 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
319 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
320 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
322 if (!Subtarget->is64Bit()) {
323 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
324 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
325 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
326 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
327 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
328 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
329 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
332 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
333 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
334 // FIXME - use subtarget debug flags
335 if (!Subtarget->isTargetDarwin() &&
336 !Subtarget->isTargetELF() &&
337 !Subtarget->isTargetCygMing()) {
338 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
339 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
342 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
343 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
344 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
345 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
346 if (Subtarget->is64Bit()) {
347 setExceptionPointerRegister(X86::RAX);
348 setExceptionSelectorRegister(X86::RDX);
350 setExceptionPointerRegister(X86::EAX);
351 setExceptionSelectorRegister(X86::EDX);
353 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
354 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
356 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
358 setOperationAction(ISD::TRAP, MVT::Other, Legal);
360 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
361 setOperationAction(ISD::VASTART , MVT::Other, Custom);
362 setOperationAction(ISD::VAEND , MVT::Other, Expand);
363 if (Subtarget->is64Bit()) {
364 setOperationAction(ISD::VAARG , MVT::Other, Custom);
365 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
367 setOperationAction(ISD::VAARG , MVT::Other, Expand);
368 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
371 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
372 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
373 if (Subtarget->is64Bit())
374 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
375 if (Subtarget->isTargetCygMing())
376 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
378 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
380 if (!UseSoftFloat && X86ScalarSSEf64) {
381 // f32 and f64 use SSE.
382 // Set up the FP register classes.
383 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
384 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
386 // Use ANDPD to simulate FABS.
387 setOperationAction(ISD::FABS , MVT::f64, Custom);
388 setOperationAction(ISD::FABS , MVT::f32, Custom);
390 // Use XORP to simulate FNEG.
391 setOperationAction(ISD::FNEG , MVT::f64, Custom);
392 setOperationAction(ISD::FNEG , MVT::f32, Custom);
394 // Use ANDPD and ORPD to simulate FCOPYSIGN.
395 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
396 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
398 // We don't support sin/cos/fmod
399 setOperationAction(ISD::FSIN , MVT::f64, Expand);
400 setOperationAction(ISD::FCOS , MVT::f64, Expand);
401 setOperationAction(ISD::FSIN , MVT::f32, Expand);
402 setOperationAction(ISD::FCOS , MVT::f32, Expand);
404 // Expand FP immediates into loads from the stack, except for the special
406 addLegalFPImmediate(APFloat(+0.0)); // xorpd
407 addLegalFPImmediate(APFloat(+0.0f)); // xorps
408 } else if (!UseSoftFloat && X86ScalarSSEf32) {
409 // Use SSE for f32, x87 for f64.
410 // Set up the FP register classes.
411 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
412 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
414 // Use ANDPS to simulate FABS.
415 setOperationAction(ISD::FABS , MVT::f32, Custom);
417 // Use XORP to simulate FNEG.
418 setOperationAction(ISD::FNEG , MVT::f32, Custom);
420 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
422 // Use ANDPS and ORPS to simulate FCOPYSIGN.
423 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
424 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
426 // We don't support sin/cos/fmod
427 setOperationAction(ISD::FSIN , MVT::f32, Expand);
428 setOperationAction(ISD::FCOS , MVT::f32, Expand);
430 // Special cases we handle for FP constants.
431 addLegalFPImmediate(APFloat(+0.0f)); // xorps
432 addLegalFPImmediate(APFloat(+0.0)); // FLD0
433 addLegalFPImmediate(APFloat(+1.0)); // FLD1
434 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
435 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
438 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
439 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
441 } else if (!UseSoftFloat) {
442 // f32 and f64 in x87.
443 // Set up the FP register classes.
444 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
445 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
447 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
448 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
449 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
450 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
453 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
454 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
456 addLegalFPImmediate(APFloat(+0.0)); // FLD0
457 addLegalFPImmediate(APFloat(+1.0)); // FLD1
458 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
459 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
460 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
461 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
462 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
463 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
466 // Long double always uses X87.
468 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
469 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
470 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
473 APFloat TmpFlt(+0.0);
474 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
476 addLegalFPImmediate(TmpFlt); // FLD0
478 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
479 APFloat TmpFlt2(+1.0);
480 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
482 addLegalFPImmediate(TmpFlt2); // FLD1
483 TmpFlt2.changeSign();
484 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
488 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
489 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
493 // Always use a library call for pow.
494 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
495 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
496 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
498 setOperationAction(ISD::FLOG, MVT::f80, Expand);
499 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
500 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
501 setOperationAction(ISD::FEXP, MVT::f80, Expand);
502 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
504 // First set operation action for all vector types to either promote
505 // (for widening) or expand (for scalarization). Then we will selectively
506 // turn on ones that can be effectively codegen'd.
507 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
508 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
509 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
510 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
511 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
512 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
513 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
514 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
515 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
516 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
517 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
518 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
519 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
520 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
521 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
522 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
523 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
524 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
525 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
526 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
527 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
528 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
529 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
530 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
531 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
532 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
533 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
534 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
535 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
536 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
555 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
556 // with -msoft-float, disable use of MMX as well.
557 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
558 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
559 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
560 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
561 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
562 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
564 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
565 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
566 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
567 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
569 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
570 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
571 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
572 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
574 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
575 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
577 setOperationAction(ISD::AND, MVT::v8i8, Promote);
578 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
579 setOperationAction(ISD::AND, MVT::v4i16, Promote);
580 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
581 setOperationAction(ISD::AND, MVT::v2i32, Promote);
582 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
583 setOperationAction(ISD::AND, MVT::v1i64, Legal);
585 setOperationAction(ISD::OR, MVT::v8i8, Promote);
586 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
587 setOperationAction(ISD::OR, MVT::v4i16, Promote);
588 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
589 setOperationAction(ISD::OR, MVT::v2i32, Promote);
590 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
591 setOperationAction(ISD::OR, MVT::v1i64, Legal);
593 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
594 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
595 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
596 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
597 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
598 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
599 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
601 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
602 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
603 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
604 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
605 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
606 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
607 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
608 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
609 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
611 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
612 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
613 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
614 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
615 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
617 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
618 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
619 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
620 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
622 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
623 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
624 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
625 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
627 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
629 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
630 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
631 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
632 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
633 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
634 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
637 if (!UseSoftFloat && Subtarget->hasSSE1()) {
638 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
640 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
641 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
642 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
643 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
644 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
645 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
646 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
647 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
648 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
649 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
650 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
651 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
654 if (!UseSoftFloat && Subtarget->hasSSE2()) {
655 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
657 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
658 // registers cannot be used even for integer operations.
659 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
660 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
661 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
662 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
664 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
665 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
666 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
667 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
668 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
669 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
670 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
671 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
672 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
673 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
674 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
675 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
676 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
677 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
678 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
679 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
681 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
682 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
683 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
684 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
686 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
687 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
688 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
689 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
690 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
692 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
693 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
694 MVT VT = (MVT::SimpleValueType)i;
695 // Do not attempt to custom lower non-power-of-2 vectors
696 if (!isPowerOf2_32(VT.getVectorNumElements()))
698 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
699 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
700 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
703 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
704 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
705 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
706 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
707 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
708 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
710 if (Subtarget->is64Bit()) {
711 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
715 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
716 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
717 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
718 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
719 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
720 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
721 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
722 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
723 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
724 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
725 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
726 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
729 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
731 // Custom lower v2i64 and v2f64 selects.
732 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
733 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
734 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
735 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
739 if (Subtarget->hasSSE41()) {
740 // FIXME: Do we need to handle scalar-to-vector here?
741 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
743 // i8 and i16 vectors are custom , because the source register and source
744 // source memory operand types are not the same width. f32 vectors are
745 // custom since the immediate controlling the insert encodes additional
747 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
748 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
749 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
750 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
752 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
753 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
754 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
755 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
757 if (Subtarget->is64Bit()) {
758 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
759 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
763 if (Subtarget->hasSSE42()) {
764 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
767 // We want to custom lower some of our intrinsics.
768 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
770 // Add/Sub/Mul with overflow operations are custom lowered.
771 setOperationAction(ISD::SADDO, MVT::i32, Custom);
772 setOperationAction(ISD::SADDO, MVT::i64, Custom);
773 setOperationAction(ISD::UADDO, MVT::i32, Custom);
774 setOperationAction(ISD::UADDO, MVT::i64, Custom);
775 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
776 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
777 setOperationAction(ISD::USUBO, MVT::i32, Custom);
778 setOperationAction(ISD::USUBO, MVT::i64, Custom);
779 setOperationAction(ISD::SMULO, MVT::i32, Custom);
780 setOperationAction(ISD::SMULO, MVT::i64, Custom);
781 setOperationAction(ISD::UMULO, MVT::i32, Custom);
782 setOperationAction(ISD::UMULO, MVT::i64, Custom);
784 if (!Subtarget->is64Bit()) {
785 // These libcalls are not available in 32-bit.
786 setLibcallName(RTLIB::SHL_I128, 0);
787 setLibcallName(RTLIB::SRL_I128, 0);
788 setLibcallName(RTLIB::SRA_I128, 0);
791 // We have target-specific dag combine patterns for the following nodes:
792 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
793 setTargetDAGCombine(ISD::BUILD_VECTOR);
794 setTargetDAGCombine(ISD::SELECT);
795 setTargetDAGCombine(ISD::SHL);
796 setTargetDAGCombine(ISD::SRA);
797 setTargetDAGCombine(ISD::SRL);
798 setTargetDAGCombine(ISD::STORE);
799 if (Subtarget->is64Bit())
800 setTargetDAGCombine(ISD::MUL);
802 computeRegisterProperties();
804 // FIXME: These should be based on subtarget info. Plus, the values should
805 // be smaller when we are in optimizing for size mode.
806 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
807 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
808 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
809 allowUnalignedMemoryAccesses = true; // x86 supports it!
810 setPrefLoopAlignment(16);
811 benefitFromCodePlacementOpt = true;
815 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
820 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
821 /// the desired ByVal argument alignment.
822 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
825 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
826 if (VTy->getBitWidth() == 128)
828 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
829 unsigned EltAlign = 0;
830 getMaxByValAlign(ATy->getElementType(), EltAlign);
831 if (EltAlign > MaxAlign)
833 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
834 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
835 unsigned EltAlign = 0;
836 getMaxByValAlign(STy->getElementType(i), EltAlign);
837 if (EltAlign > MaxAlign)
846 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
847 /// function arguments in the caller parameter area. For X86, aggregates
848 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
849 /// are at 4-byte boundaries.
850 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
851 if (Subtarget->is64Bit()) {
852 // Max of 8 and alignment of type.
853 unsigned TyAlign = TD->getABITypeAlignment(Ty);
860 if (Subtarget->hasSSE1())
861 getMaxByValAlign(Ty, Align);
865 /// getOptimalMemOpType - Returns the target specific optimal type for load
866 /// and store operations as a result of memset, memcpy, and memmove
867 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
870 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
871 bool isSrcConst, bool isSrcStr,
872 SelectionDAG &DAG) const {
873 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
874 // linux. This is because the stack realignment code can't handle certain
875 // cases like PR2962. This should be removed when PR2962 is fixed.
876 const Function *F = DAG.getMachineFunction().getFunction();
877 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
878 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
879 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
881 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
884 if (Subtarget->is64Bit() && Size >= 8)
889 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
891 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
892 SelectionDAG &DAG) const {
893 if (usesGlobalOffsetTable())
894 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
895 if (!Subtarget->isPICStyleRIPRel())
896 // This doesn't have DebugLoc associated with it, but is not really the
897 // same as a Register.
898 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
903 //===----------------------------------------------------------------------===//
904 // Return Value Calling Convention Implementation
905 //===----------------------------------------------------------------------===//
907 #include "X86GenCallingConv.inc"
909 /// LowerRET - Lower an ISD::RET node.
910 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
911 DebugLoc dl = Op.getDebugLoc();
912 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
914 SmallVector<CCValAssign, 16> RVLocs;
915 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
916 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
917 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
918 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
920 // If this is the first return lowered for this function, add the regs to the
921 // liveout set for the function.
922 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
923 for (unsigned i = 0; i != RVLocs.size(); ++i)
924 if (RVLocs[i].isRegLoc())
925 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
927 SDValue Chain = Op.getOperand(0);
929 // Handle tail call return.
930 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
931 if (Chain.getOpcode() == X86ISD::TAILCALL) {
932 SDValue TailCall = Chain;
933 SDValue TargetAddress = TailCall.getOperand(1);
934 SDValue StackAdjustment = TailCall.getOperand(2);
935 assert(((TargetAddress.getOpcode() == ISD::Register &&
936 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
937 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
938 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
939 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
940 "Expecting an global address, external symbol, or register");
941 assert(StackAdjustment.getOpcode() == ISD::Constant &&
942 "Expecting a const value");
944 SmallVector<SDValue,8> Operands;
945 Operands.push_back(Chain.getOperand(0));
946 Operands.push_back(TargetAddress);
947 Operands.push_back(StackAdjustment);
948 // Copy registers used by the call. Last operand is a flag so it is not
950 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
951 Operands.push_back(Chain.getOperand(i));
953 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
960 SmallVector<SDValue, 6> RetOps;
961 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
962 // Operand #1 = Bytes To Pop
963 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
965 // Copy the result values into the output registers.
966 for (unsigned i = 0; i != RVLocs.size(); ++i) {
967 CCValAssign &VA = RVLocs[i];
968 assert(VA.isRegLoc() && "Can only return in registers!");
969 SDValue ValToCopy = Op.getOperand(i*2+1);
971 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
972 // the RET instruction and handled by the FP Stackifier.
973 if (VA.getLocReg() == X86::ST0 ||
974 VA.getLocReg() == X86::ST1) {
975 // If this is a copy from an xmm register to ST(0), use an FPExtend to
976 // change the value to the FP stack register class.
977 if (isScalarFPTypeInSSEReg(VA.getValVT()))
978 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
979 RetOps.push_back(ValToCopy);
980 // Don't emit a copytoreg.
984 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
985 // which is returned in RAX / RDX.
986 if (Subtarget->is64Bit()) {
987 MVT ValVT = ValToCopy.getValueType();
988 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
989 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
990 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
991 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
995 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
996 Flag = Chain.getValue(1);
999 // The x86-64 ABI for returning structs by value requires that we copy
1000 // the sret argument into %rax for the return. We saved the argument into
1001 // a virtual register in the entry block, so now we copy the value out
1003 if (Subtarget->is64Bit() &&
1004 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1005 MachineFunction &MF = DAG.getMachineFunction();
1006 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1007 unsigned Reg = FuncInfo->getSRetReturnReg();
1009 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1010 FuncInfo->setSRetReturnReg(Reg);
1012 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1014 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1015 Flag = Chain.getValue(1);
1018 RetOps[0] = Chain; // Update chain.
1020 // Add the flag if we have it.
1022 RetOps.push_back(Flag);
1024 return DAG.getNode(X86ISD::RET_FLAG, dl,
1025 MVT::Other, &RetOps[0], RetOps.size());
1029 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1030 /// appropriate copies out of appropriate physical registers. This assumes that
1031 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1032 /// being lowered. The returns a SDNode with the same number of values as the
1034 SDNode *X86TargetLowering::
1035 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1036 unsigned CallingConv, SelectionDAG &DAG) {
1038 DebugLoc dl = TheCall->getDebugLoc();
1039 // Assign locations to each value returned by this call.
1040 SmallVector<CCValAssign, 16> RVLocs;
1041 bool isVarArg = TheCall->isVarArg();
1042 bool Is64Bit = Subtarget->is64Bit();
1043 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1044 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1046 SmallVector<SDValue, 8> ResultVals;
1048 // Copy all of the result registers out of their specified physreg.
1049 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1050 CCValAssign &VA = RVLocs[i];
1051 MVT CopyVT = VA.getValVT();
1053 // If this is x86-64, and we disabled SSE, we can't return FP values
1054 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1055 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1056 cerr << "SSE register return with SSE disabled\n";
1060 // If this is a call to a function that returns an fp value on the floating
1061 // point stack, but where we prefer to use the value in xmm registers, copy
1062 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1063 if ((VA.getLocReg() == X86::ST0 ||
1064 VA.getLocReg() == X86::ST1) &&
1065 isScalarFPTypeInSSEReg(VA.getValVT())) {
1070 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1071 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1072 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1073 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1074 MVT::v2i64, InFlag).getValue(1);
1075 Val = Chain.getValue(0);
1076 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1077 Val, DAG.getConstant(0, MVT::i64));
1079 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1080 MVT::i64, InFlag).getValue(1);
1081 Val = Chain.getValue(0);
1083 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1085 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1086 CopyVT, InFlag).getValue(1);
1087 Val = Chain.getValue(0);
1089 InFlag = Chain.getValue(2);
1091 if (CopyVT != VA.getValVT()) {
1092 // Round the F80 the right size, which also moves to the appropriate xmm
1094 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1095 // This truncation won't change the value.
1096 DAG.getIntPtrConstant(1));
1099 ResultVals.push_back(Val);
1102 // Merge everything together with a MERGE_VALUES node.
1103 ResultVals.push_back(Chain);
1104 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1105 &ResultVals[0], ResultVals.size()).getNode();
1109 //===----------------------------------------------------------------------===//
1110 // C & StdCall & Fast Calling Convention implementation
1111 //===----------------------------------------------------------------------===//
1112 // StdCall calling convention seems to be standard for many Windows' API
1113 // routines and around. It differs from C calling convention just a little:
1114 // callee should clean up the stack, not caller. Symbols should be also
1115 // decorated in some fancy way :) It doesn't support any vector arguments.
1116 // For info on fast calling convention see Fast Calling Convention (tail call)
1117 // implementation LowerX86_32FastCCCallTo.
1119 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1121 static bool CallIsStructReturn(CallSDNode *TheCall) {
1122 unsigned NumOps = TheCall->getNumArgs();
1126 return TheCall->getArgFlags(0).isSRet();
1129 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1130 /// return semantics.
1131 static bool ArgsAreStructReturn(SDValue Op) {
1132 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1136 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1139 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1140 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1142 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1146 switch (CallingConv) {
1149 case CallingConv::X86_StdCall:
1150 return !Subtarget->is64Bit();
1151 case CallingConv::X86_FastCall:
1152 return !Subtarget->is64Bit();
1153 case CallingConv::Fast:
1154 return PerformTailCallOpt;
1158 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1159 /// given CallingConvention value.
1160 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1161 if (Subtarget->is64Bit()) {
1162 if (Subtarget->isTargetWin64())
1163 return CC_X86_Win64_C;
1164 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1165 return CC_X86_64_TailCall;
1170 if (CC == CallingConv::X86_FastCall)
1171 return CC_X86_32_FastCall;
1172 else if (CC == CallingConv::Fast)
1173 return CC_X86_32_FastCC;
1178 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1179 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1181 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1182 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1183 if (CC == CallingConv::X86_FastCall)
1185 else if (CC == CallingConv::X86_StdCall)
1191 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1192 /// in a register before calling.
1193 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1194 return !IsTailCall && !Is64Bit &&
1195 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1196 Subtarget->isPICStyleGOT();
1199 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1200 /// address to be loaded in a register.
1202 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1203 return !Is64Bit && IsTailCall &&
1204 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1205 Subtarget->isPICStyleGOT();
1208 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1209 /// by "Src" to address "Dst" with size and alignment information specified by
1210 /// the specific parameter attribute. The copy will be passed as a byval
1211 /// function parameter.
1213 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1214 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1216 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1217 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1218 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1221 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1222 const CCValAssign &VA,
1223 MachineFrameInfo *MFI,
1225 SDValue Root, unsigned i) {
1226 // Create the nodes corresponding to a load from this parameter slot.
1227 ISD::ArgFlagsTy Flags =
1228 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1229 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1230 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1232 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1233 // changed with more analysis.
1234 // In case of tail call optimization mark all arguments mutable. Since they
1235 // could be overwritten by lowering of arguments in case of a tail call.
1236 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1237 VA.getLocMemOffset(), isImmutable);
1238 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1239 if (Flags.isByVal())
1241 return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1242 PseudoSourceValue::getFixedStack(FI), 0);
1246 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1247 MachineFunction &MF = DAG.getMachineFunction();
1248 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1249 DebugLoc dl = Op.getDebugLoc();
1251 const Function* Fn = MF.getFunction();
1252 if (Fn->hasExternalLinkage() &&
1253 Subtarget->isTargetCygMing() &&
1254 Fn->getName() == "main")
1255 FuncInfo->setForceFramePointer(true);
1257 // Decorate the function name.
1258 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1260 MachineFrameInfo *MFI = MF.getFrameInfo();
1261 SDValue Root = Op.getOperand(0);
1262 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1263 unsigned CC = MF.getFunction()->getCallingConv();
1264 bool Is64Bit = Subtarget->is64Bit();
1265 bool IsWin64 = Subtarget->isTargetWin64();
1267 assert(!(isVarArg && CC == CallingConv::Fast) &&
1268 "Var args not supported with calling convention fastcc");
1270 // Assign locations to all of the incoming arguments.
1271 SmallVector<CCValAssign, 16> ArgLocs;
1272 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1273 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1275 SmallVector<SDValue, 8> ArgValues;
1276 unsigned LastVal = ~0U;
1277 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1278 CCValAssign &VA = ArgLocs[i];
1279 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1281 assert(VA.getValNo() != LastVal &&
1282 "Don't support value assigned to multiple locs yet");
1283 LastVal = VA.getValNo();
1285 if (VA.isRegLoc()) {
1286 MVT RegVT = VA.getLocVT();
1287 TargetRegisterClass *RC = NULL;
1288 if (RegVT == MVT::i32)
1289 RC = X86::GR32RegisterClass;
1290 else if (Is64Bit && RegVT == MVT::i64)
1291 RC = X86::GR64RegisterClass;
1292 else if (RegVT == MVT::f32)
1293 RC = X86::FR32RegisterClass;
1294 else if (RegVT == MVT::f64)
1295 RC = X86::FR64RegisterClass;
1296 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1297 RC = X86::VR128RegisterClass;
1298 else if (RegVT.isVector()) {
1299 assert(RegVT.getSizeInBits() == 64);
1301 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1303 // Darwin calling convention passes MMX values in either GPRs or
1304 // XMMs in x86-64. Other targets pass them in memory.
1305 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1306 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1309 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1314 assert(0 && "Unknown argument type!");
1317 unsigned Reg = DAG.getMachineFunction().addLiveIn(VA.getLocReg(), RC);
1318 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1320 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1321 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1323 if (VA.getLocInfo() == CCValAssign::SExt)
1324 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1325 DAG.getValueType(VA.getValVT()));
1326 else if (VA.getLocInfo() == CCValAssign::ZExt)
1327 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1328 DAG.getValueType(VA.getValVT()));
1330 if (VA.getLocInfo() != CCValAssign::Full)
1331 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1333 // Handle MMX values passed in GPRs.
1334 if (Is64Bit && RegVT != VA.getLocVT()) {
1335 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1336 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1337 else if (RC == X86::VR128RegisterClass) {
1338 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1339 ArgValue, DAG.getConstant(0, MVT::i64));
1340 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1344 ArgValues.push_back(ArgValue);
1346 assert(VA.isMemLoc());
1347 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1351 // The x86-64 ABI for returning structs by value requires that we copy
1352 // the sret argument into %rax for the return. Save the argument into
1353 // a virtual register so that we can access it from the return points.
1354 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1355 MachineFunction &MF = DAG.getMachineFunction();
1356 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1357 unsigned Reg = FuncInfo->getSRetReturnReg();
1359 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1360 FuncInfo->setSRetReturnReg(Reg);
1362 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1363 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1366 unsigned StackSize = CCInfo.getNextStackOffset();
1367 // align stack specially for tail calls
1368 if (PerformTailCallOpt && CC == CallingConv::Fast)
1369 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1371 // If the function takes variable number of arguments, make a frame index for
1372 // the start of the first vararg value... for expansion of llvm.va_start.
1374 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1375 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1378 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1380 // FIXME: We should really autogenerate these arrays
1381 static const unsigned GPR64ArgRegsWin64[] = {
1382 X86::RCX, X86::RDX, X86::R8, X86::R9
1384 static const unsigned XMMArgRegsWin64[] = {
1385 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1387 static const unsigned GPR64ArgRegs64Bit[] = {
1388 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1390 static const unsigned XMMArgRegs64Bit[] = {
1391 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1392 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1394 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1397 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1398 GPR64ArgRegs = GPR64ArgRegsWin64;
1399 XMMArgRegs = XMMArgRegsWin64;
1401 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1402 GPR64ArgRegs = GPR64ArgRegs64Bit;
1403 XMMArgRegs = XMMArgRegs64Bit;
1405 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1407 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1410 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1411 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1412 "SSE register cannot be used when SSE is disabled!");
1413 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1414 "SSE register cannot be used when SSE is disabled!");
1415 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1416 // Kernel mode asks for SSE to be disabled, so don't push them
1418 TotalNumXMMRegs = 0;
1420 // For X86-64, if there are vararg parameters that are passed via
1421 // registers, then we must store them to their spots on the stack so they
1422 // may be loaded by deferencing the result of va_next.
1423 VarArgsGPOffset = NumIntRegs * 8;
1424 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1425 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1426 TotalNumXMMRegs * 16, 16);
1428 // Store the integer parameter registers.
1429 SmallVector<SDValue, 8> MemOps;
1430 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1431 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1432 DAG.getIntPtrConstant(VarArgsGPOffset));
1433 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1434 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1435 X86::GR64RegisterClass);
1436 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
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(8));
1445 // Now store the XMM (fp + vector) parameter registers.
1446 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1447 DAG.getIntPtrConstant(VarArgsFPOffset));
1448 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1449 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1450 X86::VR128RegisterClass);
1451 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1453 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1454 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1455 MemOps.push_back(Store);
1456 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1457 DAG.getIntPtrConstant(16));
1459 if (!MemOps.empty())
1460 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1461 &MemOps[0], MemOps.size());
1465 ArgValues.push_back(Root);
1467 // Some CCs need callee pop.
1468 if (IsCalleePop(isVarArg, CC)) {
1469 BytesToPopOnReturn = StackSize; // Callee pops everything.
1470 BytesCallerReserves = 0;
1472 BytesToPopOnReturn = 0; // Callee pops nothing.
1473 // If this is an sret function, the return should pop the hidden pointer.
1474 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1475 BytesToPopOnReturn = 4;
1476 BytesCallerReserves = StackSize;
1480 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1481 if (CC == CallingConv::X86_FastCall)
1482 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1485 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1487 // Return the new list of results.
1488 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1489 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1493 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1494 const SDValue &StackPtr,
1495 const CCValAssign &VA,
1497 SDValue Arg, ISD::ArgFlagsTy Flags) {
1498 DebugLoc dl = TheCall->getDebugLoc();
1499 unsigned LocMemOffset = VA.getLocMemOffset();
1500 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1501 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1502 if (Flags.isByVal()) {
1503 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1505 return DAG.getStore(Chain, dl, Arg, PtrOff,
1506 PseudoSourceValue::getStack(), LocMemOffset);
1509 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1510 /// optimization is performed and it is required.
1512 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1513 SDValue &OutRetAddr,
1519 if (!IsTailCall || FPDiff==0) return Chain;
1521 // Adjust the Return address stack slot.
1522 MVT VT = getPointerTy();
1523 OutRetAddr = getReturnAddressFrameIndex(DAG);
1525 // Load the "old" Return address.
1526 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1527 return SDValue(OutRetAddr.getNode(), 1);
1530 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1531 /// optimization is performed and it is required (FPDiff!=0).
1533 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1534 SDValue Chain, SDValue RetAddrFrIdx,
1535 bool Is64Bit, int FPDiff, DebugLoc dl) {
1536 // Store the return address to the appropriate stack slot.
1537 if (!FPDiff) return Chain;
1538 // Calculate the new stack slot for the return address.
1539 int SlotSize = Is64Bit ? 8 : 4;
1540 int NewReturnAddrFI =
1541 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1542 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1543 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1544 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1545 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1549 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1550 MachineFunction &MF = DAG.getMachineFunction();
1551 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1552 SDValue Chain = TheCall->getChain();
1553 unsigned CC = TheCall->getCallingConv();
1554 bool isVarArg = TheCall->isVarArg();
1555 bool IsTailCall = TheCall->isTailCall() &&
1556 CC == CallingConv::Fast && PerformTailCallOpt;
1557 SDValue Callee = TheCall->getCallee();
1558 bool Is64Bit = Subtarget->is64Bit();
1559 bool IsStructRet = CallIsStructReturn(TheCall);
1560 DebugLoc dl = TheCall->getDebugLoc();
1562 assert(!(isVarArg && CC == CallingConv::Fast) &&
1563 "Var args not supported with calling convention fastcc");
1565 // Analyze operands of the call, assigning locations to each operand.
1566 SmallVector<CCValAssign, 16> ArgLocs;
1567 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1568 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1570 // Get a count of how many bytes are to be pushed on the stack.
1571 unsigned NumBytes = CCInfo.getNextStackOffset();
1572 if (PerformTailCallOpt && CC == CallingConv::Fast)
1573 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1577 // Lower arguments at fp - stackoffset + fpdiff.
1578 unsigned NumBytesCallerPushed =
1579 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1580 FPDiff = NumBytesCallerPushed - NumBytes;
1582 // Set the delta of movement of the returnaddr stackslot.
1583 // But only set if delta is greater than previous delta.
1584 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1585 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1588 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1590 SDValue RetAddrFrIdx;
1591 // Load return adress for tail calls.
1592 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1595 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1596 SmallVector<SDValue, 8> MemOpChains;
1599 // Walk the register/memloc assignments, inserting copies/loads. In the case
1600 // of tail call optimization arguments are handle later.
1601 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1602 CCValAssign &VA = ArgLocs[i];
1603 SDValue Arg = TheCall->getArg(i);
1604 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1605 bool isByVal = Flags.isByVal();
1607 // Promote the value if needed.
1608 switch (VA.getLocInfo()) {
1609 default: assert(0 && "Unknown loc info!");
1610 case CCValAssign::Full: break;
1611 case CCValAssign::SExt:
1612 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1614 case CCValAssign::ZExt:
1615 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1617 case CCValAssign::AExt:
1618 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1622 if (VA.isRegLoc()) {
1624 MVT RegVT = VA.getLocVT();
1625 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1626 switch (VA.getLocReg()) {
1629 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1631 // Special case: passing MMX values in GPR registers.
1632 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1635 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1636 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1637 // Special case: passing MMX values in XMM registers.
1638 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1639 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1640 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1645 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1647 if (!IsTailCall || (IsTailCall && isByVal)) {
1648 assert(VA.isMemLoc());
1649 if (StackPtr.getNode() == 0)
1650 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1652 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1653 Chain, Arg, Flags));
1658 if (!MemOpChains.empty())
1659 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1660 &MemOpChains[0], MemOpChains.size());
1662 // Build a sequence of copy-to-reg nodes chained together with token chain
1663 // and flag operands which copy the outgoing args into registers.
1665 // Tail call byval lowering might overwrite argument registers so in case of
1666 // tail call optimization the copies to registers are lowered later.
1668 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1669 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1670 RegsToPass[i].second, InFlag);
1671 InFlag = Chain.getValue(1);
1674 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1676 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1677 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1678 DAG.getNode(X86ISD::GlobalBaseReg,
1679 DebugLoc::getUnknownLoc(),
1682 InFlag = Chain.getValue(1);
1684 // If we are tail calling and generating PIC/GOT style code load the address
1685 // of the callee into ecx. The value in ecx is used as target of the tail
1686 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1687 // calls on PIC/GOT architectures. Normally we would just put the address of
1688 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1689 // restored (since ebx is callee saved) before jumping to the target@PLT.
1690 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1691 // Note: The actual moving to ecx is done further down.
1692 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1693 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1694 !G->getGlobal()->hasProtectedVisibility())
1695 Callee = LowerGlobalAddress(Callee, DAG);
1696 else if (isa<ExternalSymbolSDNode>(Callee))
1697 Callee = LowerExternalSymbol(Callee,DAG);
1700 if (Is64Bit && isVarArg) {
1701 // From AMD64 ABI document:
1702 // For calls that may call functions that use varargs or stdargs
1703 // (prototype-less calls or calls to functions containing ellipsis (...) in
1704 // the declaration) %al is used as hidden argument to specify the number
1705 // of SSE registers used. The contents of %al do not need to match exactly
1706 // the number of registers, but must be an ubound on the number of SSE
1707 // registers used and is in the range 0 - 8 inclusive.
1709 // FIXME: Verify this on Win64
1710 // Count the number of XMM registers allocated.
1711 static const unsigned XMMArgRegs[] = {
1712 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1713 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1715 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1716 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1717 && "SSE registers cannot be used when SSE is disabled");
1719 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1720 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1721 InFlag = Chain.getValue(1);
1725 // For tail calls lower the arguments to the 'real' stack slot.
1727 SmallVector<SDValue, 8> MemOpChains2;
1730 // Do not flag preceeding copytoreg stuff together with the following stuff.
1732 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1733 CCValAssign &VA = ArgLocs[i];
1734 if (!VA.isRegLoc()) {
1735 assert(VA.isMemLoc());
1736 SDValue Arg = TheCall->getArg(i);
1737 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1738 // Create frame index.
1739 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1740 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1741 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1742 FIN = DAG.getFrameIndex(FI, getPointerTy());
1744 if (Flags.isByVal()) {
1745 // Copy relative to framepointer.
1746 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1747 if (StackPtr.getNode() == 0)
1748 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1750 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1752 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1755 // Store relative to framepointer.
1756 MemOpChains2.push_back(
1757 DAG.getStore(Chain, dl, Arg, FIN,
1758 PseudoSourceValue::getFixedStack(FI), 0));
1763 if (!MemOpChains2.empty())
1764 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1765 &MemOpChains2[0], MemOpChains2.size());
1767 // Copy arguments to their registers.
1768 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1769 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1770 RegsToPass[i].second, InFlag);
1771 InFlag = Chain.getValue(1);
1775 // Store the return address to the appropriate stack slot.
1776 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1780 // If the callee is a GlobalAddress node (quite common, every direct call is)
1781 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1782 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1783 // We should use extra load for direct calls to dllimported functions in
1785 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1786 getTargetMachine(), true))
1787 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1789 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1790 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1791 } else if (IsTailCall) {
1792 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1794 Chain = DAG.getCopyToReg(Chain, dl,
1795 DAG.getRegister(Opc, getPointerTy()),
1797 Callee = DAG.getRegister(Opc, getPointerTy());
1798 // Add register as live out.
1799 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1802 // Returns a chain & a flag for retval copy to use.
1803 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1804 SmallVector<SDValue, 8> Ops;
1807 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1808 DAG.getIntPtrConstant(0, true), InFlag);
1809 InFlag = Chain.getValue(1);
1811 // Returns a chain & a flag for retval copy to use.
1812 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1816 Ops.push_back(Chain);
1817 Ops.push_back(Callee);
1820 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1822 // Add argument registers to the end of the list so that they are known live
1824 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1825 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1826 RegsToPass[i].second.getValueType()));
1828 // Add an implicit use GOT pointer in EBX.
1829 if (!IsTailCall && !Is64Bit &&
1830 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1831 Subtarget->isPICStyleGOT())
1832 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1834 // Add an implicit use of AL for x86 vararg functions.
1835 if (Is64Bit && isVarArg)
1836 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1838 if (InFlag.getNode())
1839 Ops.push_back(InFlag);
1842 assert(InFlag.getNode() &&
1843 "Flag must be set. Depend on flag being set in LowerRET");
1844 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1845 TheCall->getVTList(), &Ops[0], Ops.size());
1847 return SDValue(Chain.getNode(), Op.getResNo());
1850 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1851 InFlag = Chain.getValue(1);
1853 // Create the CALLSEQ_END node.
1854 unsigned NumBytesForCalleeToPush;
1855 if (IsCalleePop(isVarArg, CC))
1856 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1857 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1858 // If this is is a call to a struct-return function, the callee
1859 // pops the hidden struct pointer, so we have to push it back.
1860 // This is common for Darwin/X86, Linux & Mingw32 targets.
1861 NumBytesForCalleeToPush = 4;
1863 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1865 // Returns a flag for retval copy to use.
1866 Chain = DAG.getCALLSEQ_END(Chain,
1867 DAG.getIntPtrConstant(NumBytes, true),
1868 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1871 InFlag = Chain.getValue(1);
1873 // Handle result values, copying them out of physregs into vregs that we
1875 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1880 //===----------------------------------------------------------------------===//
1881 // Fast Calling Convention (tail call) implementation
1882 //===----------------------------------------------------------------------===//
1884 // Like std call, callee cleans arguments, convention except that ECX is
1885 // reserved for storing the tail called function address. Only 2 registers are
1886 // free for argument passing (inreg). Tail call optimization is performed
1888 // * tailcallopt is enabled
1889 // * caller/callee are fastcc
1890 // On X86_64 architecture with GOT-style position independent code only local
1891 // (within module) calls are supported at the moment.
1892 // To keep the stack aligned according to platform abi the function
1893 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1894 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1895 // If a tail called function callee has more arguments than the caller the
1896 // caller needs to make sure that there is room to move the RETADDR to. This is
1897 // achieved by reserving an area the size of the argument delta right after the
1898 // original REtADDR, but before the saved framepointer or the spilled registers
1899 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1911 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1912 /// for a 16 byte align requirement.
1913 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1914 SelectionDAG& DAG) {
1915 MachineFunction &MF = DAG.getMachineFunction();
1916 const TargetMachine &TM = MF.getTarget();
1917 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1918 unsigned StackAlignment = TFI.getStackAlignment();
1919 uint64_t AlignMask = StackAlignment - 1;
1920 int64_t Offset = StackSize;
1921 uint64_t SlotSize = TD->getPointerSize();
1922 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1923 // Number smaller than 12 so just add the difference.
1924 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1926 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1927 Offset = ((~AlignMask) & Offset) + StackAlignment +
1928 (StackAlignment-SlotSize);
1933 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1934 /// following the call is a return. A function is eligible if caller/callee
1935 /// calling conventions match, currently only fastcc supports tail calls, and
1936 /// the function CALL is immediatly followed by a RET.
1937 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1939 SelectionDAG& DAG) const {
1940 if (!PerformTailCallOpt)
1943 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1944 MachineFunction &MF = DAG.getMachineFunction();
1945 unsigned CallerCC = MF.getFunction()->getCallingConv();
1946 unsigned CalleeCC= TheCall->getCallingConv();
1947 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1948 SDValue Callee = TheCall->getCallee();
1949 // On x86/32Bit PIC/GOT tail calls are supported.
1950 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1951 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1954 // Can only do local tail calls (in same module, hidden or protected) on
1955 // x86_64 PIC/GOT at the moment.
1956 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1957 return G->getGlobal()->hasHiddenVisibility()
1958 || G->getGlobal()->hasProtectedVisibility();
1966 X86TargetLowering::createFastISel(MachineFunction &mf,
1967 MachineModuleInfo *mmo,
1969 DenseMap<const Value *, unsigned> &vm,
1970 DenseMap<const BasicBlock *,
1971 MachineBasicBlock *> &bm,
1972 DenseMap<const AllocaInst *, int> &am
1974 , SmallSet<Instruction*, 8> &cil
1977 return X86::createFastISel(mf, mmo, dw, vm, bm, am
1985 //===----------------------------------------------------------------------===//
1986 // Other Lowering Hooks
1987 //===----------------------------------------------------------------------===//
1990 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1991 MachineFunction &MF = DAG.getMachineFunction();
1992 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1993 int ReturnAddrIndex = FuncInfo->getRAIndex();
1995 if (ReturnAddrIndex == 0) {
1996 // Set up a frame object for the return address.
1997 uint64_t SlotSize = TD->getPointerSize();
1998 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1999 FuncInfo->setRAIndex(ReturnAddrIndex);
2002 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2006 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2007 /// specific condition code, returning the condition code and the LHS/RHS of the
2008 /// comparison to make.
2009 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2010 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2012 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2013 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2014 // X > -1 -> X == 0, jump !sign.
2015 RHS = DAG.getConstant(0, RHS.getValueType());
2016 return X86::COND_NS;
2017 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2018 // X < 0 -> X == 0, jump on sign.
2020 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2022 RHS = DAG.getConstant(0, RHS.getValueType());
2023 return X86::COND_LE;
2027 switch (SetCCOpcode) {
2028 default: assert(0 && "Invalid integer condition!");
2029 case ISD::SETEQ: return X86::COND_E;
2030 case ISD::SETGT: return X86::COND_G;
2031 case ISD::SETGE: return X86::COND_GE;
2032 case ISD::SETLT: return X86::COND_L;
2033 case ISD::SETLE: return X86::COND_LE;
2034 case ISD::SETNE: return X86::COND_NE;
2035 case ISD::SETULT: return X86::COND_B;
2036 case ISD::SETUGT: return X86::COND_A;
2037 case ISD::SETULE: return X86::COND_BE;
2038 case ISD::SETUGE: return X86::COND_AE;
2042 // First determine if it is required or is profitable to flip the operands.
2044 // If LHS is a foldable load, but RHS is not, flip the condition.
2045 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2046 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2047 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2048 std::swap(LHS, RHS);
2051 switch (SetCCOpcode) {
2057 std::swap(LHS, RHS);
2061 // On a floating point condition, the flags are set as follows:
2063 // 0 | 0 | 0 | X > Y
2064 // 0 | 0 | 1 | X < Y
2065 // 1 | 0 | 0 | X == Y
2066 // 1 | 1 | 1 | unordered
2067 switch (SetCCOpcode) {
2068 default: assert(0 && "Condcode should be pre-legalized away");
2070 case ISD::SETEQ: return X86::COND_E;
2071 case ISD::SETOLT: // flipped
2073 case ISD::SETGT: return X86::COND_A;
2074 case ISD::SETOLE: // flipped
2076 case ISD::SETGE: return X86::COND_AE;
2077 case ISD::SETUGT: // flipped
2079 case ISD::SETLT: return X86::COND_B;
2080 case ISD::SETUGE: // flipped
2082 case ISD::SETLE: return X86::COND_BE;
2084 case ISD::SETNE: return X86::COND_NE;
2085 case ISD::SETUO: return X86::COND_P;
2086 case ISD::SETO: return X86::COND_NP;
2090 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2091 /// code. Current x86 isa includes the following FP cmov instructions:
2092 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2093 static bool hasFPCMov(unsigned X86CC) {
2109 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2110 /// the specified range (L, H].
2111 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2112 return (Val < 0) || (Val >= Low && Val < Hi);
2115 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2116 /// specified value.
2117 static bool isUndefOrEqual(int Val, int CmpVal) {
2118 if (Val < 0 || Val == CmpVal)
2123 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2124 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2125 /// the second operand.
2126 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2127 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2128 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2129 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2130 return (Mask[0] < 2 && Mask[1] < 2);
2134 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2135 SmallVector<int, 8> M;
2137 return ::isPSHUFDMask(M, N->getValueType(0));
2140 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2141 /// is suitable for input to PSHUFHW.
2142 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2143 if (VT != MVT::v8i16)
2146 // Lower quadword copied in order or undef.
2147 for (int i = 0; i != 4; ++i)
2148 if (Mask[i] >= 0 && Mask[i] != i)
2151 // Upper quadword shuffled.
2152 for (int i = 4; i != 8; ++i)
2153 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2159 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2160 SmallVector<int, 8> M;
2162 return ::isPSHUFHWMask(M, N->getValueType(0));
2165 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2166 /// is suitable for input to PSHUFLW.
2167 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2168 if (VT != MVT::v8i16)
2171 // Upper quadword copied in order.
2172 for (int i = 4; i != 8; ++i)
2173 if (Mask[i] >= 0 && Mask[i] != i)
2176 // Lower quadword shuffled.
2177 for (int i = 0; i != 4; ++i)
2184 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2185 SmallVector<int, 8> M;
2187 return ::isPSHUFLWMask(M, N->getValueType(0));
2190 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2191 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2192 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2193 int NumElems = VT.getVectorNumElements();
2194 if (NumElems != 2 && NumElems != 4)
2197 int Half = NumElems / 2;
2198 for (int i = 0; i < Half; ++i)
2199 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2201 for (int i = Half; i < NumElems; ++i)
2202 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2208 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2209 SmallVector<int, 8> M;
2211 return ::isSHUFPMask(M, N->getValueType(0));
2214 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2215 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2216 /// half elements to come from vector 1 (which would equal the dest.) and
2217 /// the upper half to come from vector 2.
2218 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2219 int NumElems = VT.getVectorNumElements();
2221 if (NumElems != 2 && NumElems != 4)
2224 int Half = NumElems / 2;
2225 for (int i = 0; i < Half; ++i)
2226 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2228 for (int i = Half; i < NumElems; ++i)
2229 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2234 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2235 SmallVector<int, 8> M;
2237 return isCommutedSHUFPMask(M, N->getValueType(0));
2240 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2241 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2242 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2243 if (N->getValueType(0).getVectorNumElements() != 4)
2246 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2247 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2248 isUndefOrEqual(N->getMaskElt(1), 7) &&
2249 isUndefOrEqual(N->getMaskElt(2), 2) &&
2250 isUndefOrEqual(N->getMaskElt(3), 3);
2253 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2254 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2255 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2256 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2258 if (NumElems != 2 && NumElems != 4)
2261 for (unsigned i = 0; i < NumElems/2; ++i)
2262 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2265 for (unsigned i = NumElems/2; i < NumElems; ++i)
2266 if (!isUndefOrEqual(N->getMaskElt(i), i))
2272 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2273 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2275 bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2276 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2278 if (NumElems != 2 && NumElems != 4)
2281 for (unsigned i = 0; i < NumElems/2; ++i)
2282 if (!isUndefOrEqual(N->getMaskElt(i), i))
2285 for (unsigned i = 0; i < NumElems/2; ++i)
2286 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2292 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2293 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2295 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2296 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2301 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2302 isUndefOrEqual(N->getMaskElt(1), 3) &&
2303 isUndefOrEqual(N->getMaskElt(2), 2) &&
2304 isUndefOrEqual(N->getMaskElt(3), 3);
2307 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2308 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2309 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2310 bool V2IsSplat = false) {
2311 int NumElts = VT.getVectorNumElements();
2312 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2315 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2317 int BitI1 = Mask[i+1];
2318 if (!isUndefOrEqual(BitI, j))
2321 if (!isUndefOrEqual(BitI1, NumElts))
2324 if (!isUndefOrEqual(BitI1, j + NumElts))
2331 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2332 SmallVector<int, 8> M;
2334 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2337 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2338 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2339 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, MVT VT,
2340 bool V2IsSplat = false) {
2341 int NumElts = VT.getVectorNumElements();
2342 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2345 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2347 int BitI1 = Mask[i+1];
2348 if (!isUndefOrEqual(BitI, j + NumElts/2))
2351 if (isUndefOrEqual(BitI1, NumElts))
2354 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2361 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2362 SmallVector<int, 8> M;
2364 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2367 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2368 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2370 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2371 int NumElems = VT.getVectorNumElements();
2372 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2375 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2377 int BitI1 = Mask[i+1];
2378 if (!isUndefOrEqual(BitI, j))
2380 if (!isUndefOrEqual(BitI1, j))
2386 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2387 SmallVector<int, 8> M;
2389 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2392 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2393 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2395 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2396 int NumElems = VT.getVectorNumElements();
2397 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2400 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2402 int BitI1 = Mask[i+1];
2403 if (!isUndefOrEqual(BitI, j))
2405 if (!isUndefOrEqual(BitI1, j))
2411 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2412 SmallVector<int, 8> M;
2414 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2417 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2418 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2419 /// MOVSD, and MOVD, i.e. setting the lowest element.
2420 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2421 int NumElts = VT.getVectorNumElements();
2422 if (NumElts != 2 && NumElts != 4)
2425 if (!isUndefOrEqual(Mask[0], NumElts))
2428 for (int i = 1; i < NumElts; ++i)
2429 if (!isUndefOrEqual(Mask[i], i))
2435 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2436 SmallVector<int, 8> M;
2438 return ::isMOVLMask(M, N->getValueType(0));
2441 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2442 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2443 /// element of vector 2 and the other elements to come from vector 1 in order.
2444 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2445 bool V2IsSplat = false, bool V2IsUndef = false) {
2446 int NumOps = VT.getVectorNumElements();
2447 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2450 if (!isUndefOrEqual(Mask[0], 0))
2453 for (int i = 1; i < NumOps; ++i)
2454 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2455 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2456 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2462 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2463 bool V2IsUndef = false) {
2464 SmallVector<int, 8> M;
2466 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2469 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2470 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2471 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2472 if (N->getValueType(0).getVectorNumElements() != 4)
2475 // Expect 1, 1, 3, 3
2476 for (unsigned i = 0; i < 2; ++i) {
2477 int Elt = N->getMaskElt(i);
2478 if (Elt >= 0 && Elt != 1)
2483 for (unsigned i = 2; i < 4; ++i) {
2484 int Elt = N->getMaskElt(i);
2485 if (Elt >= 0 && Elt != 3)
2490 // Don't use movshdup if it can be done with a shufps.
2491 // FIXME: verify that matching u, u, 3, 3 is what we want.
2495 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2496 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2497 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2498 if (N->getValueType(0).getVectorNumElements() != 4)
2501 // Expect 0, 0, 2, 2
2502 for (unsigned i = 0; i < 2; ++i)
2503 if (N->getMaskElt(i) > 0)
2507 for (unsigned i = 2; i < 4; ++i) {
2508 int Elt = N->getMaskElt(i);
2509 if (Elt >= 0 && Elt != 2)
2514 // Don't use movsldup if it can be done with a shufps.
2518 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2519 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2520 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2521 int e = N->getValueType(0).getVectorNumElements() / 2;
2523 for (int i = 0; i < e; ++i)
2524 if (!isUndefOrEqual(N->getMaskElt(i), i))
2526 for (int i = 0; i < e; ++i)
2527 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2532 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2533 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2535 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2536 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2537 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2539 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2541 for (int i = 0; i < NumOperands; ++i) {
2542 int Val = SVOp->getMaskElt(NumOperands-i-1);
2543 if (Val < 0) Val = 0;
2544 if (Val >= NumOperands) Val -= NumOperands;
2546 if (i != NumOperands - 1)
2552 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2553 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2555 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2556 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2558 // 8 nodes, but we only care about the last 4.
2559 for (unsigned i = 7; i >= 4; --i) {
2560 int Val = SVOp->getMaskElt(i);
2569 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2570 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2572 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2573 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2575 // 8 nodes, but we only care about the first 4.
2576 for (int i = 3; i >= 0; --i) {
2577 int Val = SVOp->getMaskElt(i);
2586 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2587 /// their permute mask.
2588 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2589 SelectionDAG &DAG) {
2590 MVT VT = SVOp->getValueType(0);
2591 unsigned NumElems = VT.getVectorNumElements();
2592 SmallVector<int, 8> MaskVec;
2594 for (unsigned i = 0; i != NumElems; ++i) {
2595 int idx = SVOp->getMaskElt(i);
2597 MaskVec.push_back(idx);
2598 else if (idx < (int)NumElems)
2599 MaskVec.push_back(idx + NumElems);
2601 MaskVec.push_back(idx - NumElems);
2603 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2604 SVOp->getOperand(0), &MaskVec[0]);
2607 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2608 /// the two vector operands have swapped position.
2609 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, MVT VT) {
2610 unsigned NumElems = VT.getVectorNumElements();
2611 for (unsigned i = 0; i != NumElems; ++i) {
2615 else if (idx < (int)NumElems)
2616 Mask[i] = idx + NumElems;
2618 Mask[i] = idx - NumElems;
2622 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2623 /// match movhlps. The lower half elements should come from upper half of
2624 /// V1 (and in order), and the upper half elements should come from the upper
2625 /// half of V2 (and in order).
2626 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2627 if (Op->getValueType(0).getVectorNumElements() != 4)
2629 for (unsigned i = 0, e = 2; i != e; ++i)
2630 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2632 for (unsigned i = 2; i != 4; ++i)
2633 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2638 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2639 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2641 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2642 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2644 N = N->getOperand(0).getNode();
2645 if (!ISD::isNON_EXTLoad(N))
2648 *LD = cast<LoadSDNode>(N);
2652 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2653 /// match movlp{s|d}. The lower half elements should come from lower half of
2654 /// V1 (and in order), and the upper half elements should come from the upper
2655 /// half of V2 (and in order). And since V1 will become the source of the
2656 /// MOVLP, it must be either a vector load or a scalar load to vector.
2657 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2658 ShuffleVectorSDNode *Op) {
2659 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2661 // Is V2 is a vector load, don't do this transformation. We will try to use
2662 // load folding shufps op.
2663 if (ISD::isNON_EXTLoad(V2))
2666 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2668 if (NumElems != 2 && NumElems != 4)
2670 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2671 if (!isUndefOrEqual(Op->getMaskElt(i), i))
2673 for (unsigned i = NumElems/2; i != NumElems; ++i)
2674 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2679 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2681 static bool isSplatVector(SDNode *N) {
2682 if (N->getOpcode() != ISD::BUILD_VECTOR)
2685 SDValue SplatValue = N->getOperand(0);
2686 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2687 if (N->getOperand(i) != SplatValue)
2692 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2694 static inline bool isZeroNode(SDValue Elt) {
2695 return ((isa<ConstantSDNode>(Elt) &&
2696 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2697 (isa<ConstantFPSDNode>(Elt) &&
2698 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2701 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2702 /// to an zero vector.
2703 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2704 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2705 SDValue V1 = N->getOperand(0);
2706 SDValue V2 = N->getOperand(1);
2707 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2708 for (unsigned i = 0; i != NumElems; ++i) {
2709 int Idx = N->getMaskElt(i);
2710 if (Idx >= (int)NumElems) {
2711 unsigned Opc = V2.getOpcode();
2712 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2714 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V2.getOperand(Idx-NumElems)))
2716 } else if (Idx >= 0) {
2717 unsigned Opc = V1.getOpcode();
2718 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2720 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V1.getOperand(Idx)))
2727 /// getZeroVector - Returns a vector of specified type with all zero elements.
2729 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2731 assert(VT.isVector() && "Expected a vector type");
2733 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2734 // type. This ensures they get CSE'd.
2736 if (VT.getSizeInBits() == 64) { // MMX
2737 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2738 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2739 } else if (HasSSE2) { // SSE2
2740 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2741 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2743 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2744 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2746 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2749 /// getOnesVector - Returns a vector of specified type with all bits set.
2751 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2752 assert(VT.isVector() && "Expected a vector type");
2754 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2755 // type. This ensures they get CSE'd.
2756 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2758 if (VT.getSizeInBits() == 64) // MMX
2759 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2761 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2762 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2766 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2767 /// that point to V2 points to its first element.
2768 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2769 MVT VT = SVOp->getValueType(0);
2770 unsigned NumElems = VT.getVectorNumElements();
2772 bool Changed = false;
2773 SmallVector<int, 8> MaskVec;
2774 SVOp->getMask(MaskVec);
2776 for (unsigned i = 0; i != NumElems; ++i) {
2777 if (MaskVec[i] > (int)NumElems) {
2778 MaskVec[i] = NumElems;
2783 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
2784 SVOp->getOperand(1), &MaskVec[0]);
2785 return SDValue(SVOp, 0);
2788 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2789 /// operation of specified width.
2790 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2792 unsigned NumElems = VT.getVectorNumElements();
2793 SmallVector<int, 8> Mask;
2794 Mask.push_back(NumElems);
2795 for (unsigned i = 1; i != NumElems; ++i)
2797 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2800 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
2801 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2803 unsigned NumElems = VT.getVectorNumElements();
2804 SmallVector<int, 8> Mask;
2805 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2807 Mask.push_back(i + NumElems);
2809 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2812 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
2813 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2815 unsigned NumElems = VT.getVectorNumElements();
2816 unsigned Half = NumElems/2;
2817 SmallVector<int, 8> Mask;
2818 for (unsigned i = 0; i != Half; ++i) {
2819 Mask.push_back(i + Half);
2820 Mask.push_back(i + NumElems + Half);
2822 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2825 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2826 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
2828 if (SV->getValueType(0).getVectorNumElements() <= 4)
2829 return SDValue(SV, 0);
2831 MVT PVT = MVT::v4f32;
2832 MVT VT = SV->getValueType(0);
2833 DebugLoc dl = SV->getDebugLoc();
2834 SDValue V1 = SV->getOperand(0);
2835 int NumElems = VT.getVectorNumElements();
2836 int EltNo = SV->getSplatIndex();
2838 // unpack elements to the correct location
2839 while (NumElems > 4) {
2840 if (EltNo < NumElems/2) {
2841 V1 = getUnpackl(DAG, dl, VT, V1, V1);
2843 V1 = getUnpackh(DAG, dl, VT, V1, V1);
2844 EltNo -= NumElems/2;
2849 // Perform the splat.
2850 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
2851 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
2852 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
2853 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
2856 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2857 /// vector of zero or undef vector. This produces a shuffle where the low
2858 /// element of V2 is swizzled into the zero/undef vector, landing at element
2859 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2860 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2861 bool isZero, bool HasSSE2,
2862 SelectionDAG &DAG) {
2863 MVT VT = V2.getValueType();
2865 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
2866 unsigned NumElems = VT.getVectorNumElements();
2867 SmallVector<int, 16> MaskVec;
2868 for (unsigned i = 0; i != NumElems; ++i)
2869 // If this is the insertion idx, put the low elt of V2 here.
2870 MaskVec.push_back(i == Idx ? NumElems : i);
2871 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
2874 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2875 /// a shuffle that is zero.
2877 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
2878 bool Low, SelectionDAG &DAG) {
2879 unsigned NumZeros = 0;
2880 for (int i = 0; i < NumElems; ++i) {
2881 unsigned Index = Low ? i : NumElems-i-1;
2882 int Idx = SVOp->getMaskElt(Index);
2887 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
2888 if (Elt.getNode() && isZeroNode(Elt))
2896 /// isVectorShift - Returns true if the shuffle can be implemented as a
2897 /// logical left or right shift of a vector.
2898 /// FIXME: split into pslldqi, psrldqi, palignr variants.
2899 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
2900 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
2901 int NumElems = SVOp->getValueType(0).getVectorNumElements();
2904 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
2907 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
2911 bool SeenV1 = false;
2912 bool SeenV2 = false;
2913 for (int i = NumZeros; i < NumElems; ++i) {
2914 int Val = isLeft ? (i - NumZeros) : i;
2915 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
2927 if (SeenV1 && SeenV2)
2930 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
2936 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2938 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
2939 unsigned NumNonZero, unsigned NumZero,
2940 SelectionDAG &DAG, TargetLowering &TLI) {
2944 DebugLoc dl = Op.getDebugLoc();
2947 for (unsigned i = 0; i < 16; ++i) {
2948 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2949 if (ThisIsNonZero && First) {
2951 V = getZeroVector(MVT::v8i16, true, DAG, dl);
2953 V = DAG.getUNDEF(MVT::v8i16);
2958 SDValue ThisElt(0, 0), LastElt(0, 0);
2959 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2960 if (LastIsNonZero) {
2961 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
2962 MVT::i16, Op.getOperand(i-1));
2964 if (ThisIsNonZero) {
2965 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
2966 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
2967 ThisElt, DAG.getConstant(8, MVT::i8));
2969 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
2973 if (ThisElt.getNode())
2974 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
2975 DAG.getIntPtrConstant(i/2));
2979 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
2982 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2984 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
2985 unsigned NumNonZero, unsigned NumZero,
2986 SelectionDAG &DAG, TargetLowering &TLI) {
2990 DebugLoc dl = Op.getDebugLoc();
2993 for (unsigned i = 0; i < 8; ++i) {
2994 bool isNonZero = (NonZeros & (1 << i)) != 0;
2998 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3000 V = DAG.getUNDEF(MVT::v8i16);
3003 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3004 MVT::v8i16, V, Op.getOperand(i),
3005 DAG.getIntPtrConstant(i));
3012 /// getVShift - Return a vector logical shift node.
3014 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3015 unsigned NumBits, SelectionDAG &DAG,
3016 const TargetLowering &TLI, DebugLoc dl) {
3017 bool isMMX = VT.getSizeInBits() == 64;
3018 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3019 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3020 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3021 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3022 DAG.getNode(Opc, dl, ShVT, SrcOp,
3023 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3027 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3028 DebugLoc dl = Op.getDebugLoc();
3029 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3030 if (ISD::isBuildVectorAllZeros(Op.getNode())
3031 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3032 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3033 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3034 // eliminated on x86-32 hosts.
3035 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3038 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3039 return getOnesVector(Op.getValueType(), DAG, dl);
3040 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3043 MVT VT = Op.getValueType();
3044 MVT EVT = VT.getVectorElementType();
3045 unsigned EVTBits = EVT.getSizeInBits();
3047 unsigned NumElems = Op.getNumOperands();
3048 unsigned NumZero = 0;
3049 unsigned NumNonZero = 0;
3050 unsigned NonZeros = 0;
3051 bool IsAllConstants = true;
3052 SmallSet<SDValue, 8> Values;
3053 for (unsigned i = 0; i < NumElems; ++i) {
3054 SDValue Elt = Op.getOperand(i);
3055 if (Elt.getOpcode() == ISD::UNDEF)
3058 if (Elt.getOpcode() != ISD::Constant &&
3059 Elt.getOpcode() != ISD::ConstantFP)
3060 IsAllConstants = false;
3061 if (isZeroNode(Elt))
3064 NonZeros |= (1 << i);
3069 if (NumNonZero == 0) {
3070 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3071 return DAG.getUNDEF(VT);
3074 // Special case for single non-zero, non-undef, element.
3075 if (NumNonZero == 1 && NumElems <= 4) {
3076 unsigned Idx = CountTrailingZeros_32(NonZeros);
3077 SDValue Item = Op.getOperand(Idx);
3079 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3080 // the value are obviously zero, truncate the value to i32 and do the
3081 // insertion that way. Only do this if the value is non-constant or if the
3082 // value is a constant being inserted into element 0. It is cheaper to do
3083 // a constant pool load than it is to do a movd + shuffle.
3084 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3085 (!IsAllConstants || Idx == 0)) {
3086 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3087 // Handle MMX and SSE both.
3088 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3089 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3091 // Truncate the value (which may itself be a constant) to i32, and
3092 // convert it to a vector with movd (S2V+shuffle to zero extend).
3093 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3094 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3095 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3096 Subtarget->hasSSE2(), DAG);
3098 // Now we have our 32-bit value zero extended in the low element of
3099 // a vector. If Idx != 0, swizzle it into place.
3101 SmallVector<int, 4> Mask;
3102 Mask.push_back(Idx);
3103 for (unsigned i = 1; i != VecElts; ++i)
3105 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3106 DAG.getUNDEF(Item.getValueType()),
3109 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3113 // If we have a constant or non-constant insertion into the low element of
3114 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3115 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3116 // depending on what the source datatype is. Because we can only get here
3117 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3119 // Don't do this for i64 values on x86-32.
3120 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3121 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3122 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3123 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3124 Subtarget->hasSSE2(), DAG);
3127 // Is it a vector logical left shift?
3128 if (NumElems == 2 && Idx == 1 &&
3129 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3130 unsigned NumBits = VT.getSizeInBits();
3131 return getVShift(true, VT,
3132 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3133 VT, Op.getOperand(1)),
3134 NumBits/2, DAG, *this, dl);
3137 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3140 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3141 // is a non-constant being inserted into an element other than the low one,
3142 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3143 // movd/movss) to move this into the low element, then shuffle it into
3145 if (EVTBits == 32) {
3146 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3148 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3149 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3150 Subtarget->hasSSE2(), DAG);
3151 SmallVector<int, 8> MaskVec;
3152 for (unsigned i = 0; i < NumElems; i++)
3153 MaskVec.push_back(i == Idx ? 0 : 1);
3154 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3158 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3159 if (Values.size() == 1)
3162 // A vector full of immediates; various special cases are already
3163 // handled, so this is best done with a single constant-pool load.
3167 // Let legalizer expand 2-wide build_vectors.
3168 if (EVTBits == 64) {
3169 if (NumNonZero == 1) {
3170 // One half is zero or undef.
3171 unsigned Idx = CountTrailingZeros_32(NonZeros);
3172 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3173 Op.getOperand(Idx));
3174 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3175 Subtarget->hasSSE2(), DAG);
3180 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3181 if (EVTBits == 8 && NumElems == 16) {
3182 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3184 if (V.getNode()) return V;
3187 if (EVTBits == 16 && NumElems == 8) {
3188 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3190 if (V.getNode()) return V;
3193 // If element VT is == 32 bits, turn it into a number of shuffles.
3194 SmallVector<SDValue, 8> V;
3196 if (NumElems == 4 && NumZero > 0) {
3197 for (unsigned i = 0; i < 4; ++i) {
3198 bool isZero = !(NonZeros & (1 << i));
3200 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3202 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3205 for (unsigned i = 0; i < 2; ++i) {
3206 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3209 V[i] = V[i*2]; // Must be a zero vector.
3212 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3215 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3218 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3223 SmallVector<int, 8> MaskVec;
3224 bool Reverse = (NonZeros & 0x3) == 2;
3225 for (unsigned i = 0; i < 2; ++i)
3226 MaskVec.push_back(Reverse ? 1-i : i);
3227 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3228 for (unsigned i = 0; i < 2; ++i)
3229 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3230 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3233 if (Values.size() > 2) {
3234 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3235 // values to be inserted is equal to the number of elements, in which case
3236 // use the unpack code below in the hopes of matching the consecutive elts
3237 // load merge pattern for shuffles.
3238 // FIXME: We could probably just check that here directly.
3239 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3240 getSubtarget()->hasSSE41()) {
3241 V[0] = DAG.getUNDEF(VT);
3242 for (unsigned i = 0; i < NumElems; ++i)
3243 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3244 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3245 Op.getOperand(i), DAG.getIntPtrConstant(i));
3248 // Expand into a number of unpckl*.
3250 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3251 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3252 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3253 for (unsigned i = 0; i < NumElems; ++i)
3254 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3256 while (NumElems != 0) {
3257 for (unsigned i = 0; i < NumElems; ++i)
3258 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3267 // v8i16 shuffles - Prefer shuffles in the following order:
3268 // 1. [all] pshuflw, pshufhw, optional move
3269 // 2. [ssse3] 1 x pshufb
3270 // 3. [ssse3] 2 x pshufb + 1 x por
3271 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3273 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3274 SelectionDAG &DAG, X86TargetLowering &TLI) {
3275 SDValue V1 = SVOp->getOperand(0);
3276 SDValue V2 = SVOp->getOperand(1);
3277 DebugLoc dl = SVOp->getDebugLoc();
3278 SmallVector<int, 8> MaskVals;
3280 // Determine if more than 1 of the words in each of the low and high quadwords
3281 // of the result come from the same quadword of one of the two inputs. Undef
3282 // mask values count as coming from any quadword, for better codegen.
3283 SmallVector<unsigned, 4> LoQuad(4);
3284 SmallVector<unsigned, 4> HiQuad(4);
3285 BitVector InputQuads(4);
3286 for (unsigned i = 0; i < 8; ++i) {
3287 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3288 int EltIdx = SVOp->getMaskElt(i);
3289 MaskVals.push_back(EltIdx);
3298 InputQuads.set(EltIdx / 4);
3301 int BestLoQuad = -1;
3302 unsigned MaxQuad = 1;
3303 for (unsigned i = 0; i < 4; ++i) {
3304 if (LoQuad[i] > MaxQuad) {
3306 MaxQuad = LoQuad[i];
3310 int BestHiQuad = -1;
3312 for (unsigned i = 0; i < 4; ++i) {
3313 if (HiQuad[i] > MaxQuad) {
3315 MaxQuad = HiQuad[i];
3319 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3320 // of the two input vectors, shuffle them into one input vector so only a
3321 // single pshufb instruction is necessary. If There are more than 2 input
3322 // quads, disable the next transformation since it does not help SSSE3.
3323 bool V1Used = InputQuads[0] || InputQuads[1];
3324 bool V2Used = InputQuads[2] || InputQuads[3];
3325 if (TLI.getSubtarget()->hasSSSE3()) {
3326 if (InputQuads.count() == 2 && V1Used && V2Used) {
3327 BestLoQuad = InputQuads.find_first();
3328 BestHiQuad = InputQuads.find_next(BestLoQuad);
3330 if (InputQuads.count() > 2) {
3336 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3337 // the shuffle mask. If a quad is scored as -1, that means that it contains
3338 // words from all 4 input quadwords.
3340 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3341 SmallVector<int, 8> MaskV;
3342 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3343 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3344 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3345 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3346 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3347 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3349 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3350 // source words for the shuffle, to aid later transformations.
3351 bool AllWordsInNewV = true;
3352 bool InOrder[2] = { true, true };
3353 for (unsigned i = 0; i != 8; ++i) {
3354 int idx = MaskVals[i];
3356 InOrder[i/4] = false;
3357 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3359 AllWordsInNewV = false;
3363 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3364 if (AllWordsInNewV) {
3365 for (int i = 0; i != 8; ++i) {
3366 int idx = MaskVals[i];
3369 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3370 if ((idx != i) && idx < 4)
3372 if ((idx != i) && idx > 3)
3381 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3382 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3383 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3384 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3385 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3389 // If we have SSSE3, and all words of the result are from 1 input vector,
3390 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3391 // is present, fall back to case 4.
3392 if (TLI.getSubtarget()->hasSSSE3()) {
3393 SmallVector<SDValue,16> pshufbMask;
3395 // If we have elements from both input vectors, set the high bit of the
3396 // shuffle mask element to zero out elements that come from V2 in the V1
3397 // mask, and elements that come from V1 in the V2 mask, so that the two
3398 // results can be OR'd together.
3399 bool TwoInputs = V1Used && V2Used;
3400 for (unsigned i = 0; i != 8; ++i) {
3401 int EltIdx = MaskVals[i] * 2;
3402 if (TwoInputs && (EltIdx >= 16)) {
3403 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3404 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3407 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3408 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3410 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3411 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3412 DAG.getNode(ISD::BUILD_VECTOR, dl,
3413 MVT::v16i8, &pshufbMask[0], 16));
3415 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3417 // Calculate the shuffle mask for the second input, shuffle it, and
3418 // OR it with the first shuffled input.
3420 for (unsigned i = 0; i != 8; ++i) {
3421 int EltIdx = MaskVals[i] * 2;
3423 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3424 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3427 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3428 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3430 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3431 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3432 DAG.getNode(ISD::BUILD_VECTOR, dl,
3433 MVT::v16i8, &pshufbMask[0], 16));
3434 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3435 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3438 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3439 // and update MaskVals with new element order.
3440 BitVector InOrder(8);
3441 if (BestLoQuad >= 0) {
3442 SmallVector<int, 8> MaskV;
3443 for (int i = 0; i != 4; ++i) {
3444 int idx = MaskVals[i];
3446 MaskV.push_back(-1);
3448 } else if ((idx / 4) == BestLoQuad) {
3449 MaskV.push_back(idx & 3);
3452 MaskV.push_back(-1);
3455 for (unsigned i = 4; i != 8; ++i)
3457 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3461 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3462 // and update MaskVals with the new element order.
3463 if (BestHiQuad >= 0) {
3464 SmallVector<int, 8> MaskV;
3465 for (unsigned i = 0; i != 4; ++i)
3467 for (unsigned i = 4; i != 8; ++i) {
3468 int idx = MaskVals[i];
3470 MaskV.push_back(-1);
3472 } else if ((idx / 4) == BestHiQuad) {
3473 MaskV.push_back((idx & 3) + 4);
3476 MaskV.push_back(-1);
3479 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3483 // In case BestHi & BestLo were both -1, which means each quadword has a word
3484 // from each of the four input quadwords, calculate the InOrder bitvector now
3485 // before falling through to the insert/extract cleanup.
3486 if (BestLoQuad == -1 && BestHiQuad == -1) {
3488 for (int i = 0; i != 8; ++i)
3489 if (MaskVals[i] < 0 || MaskVals[i] == i)
3493 // The other elements are put in the right place using pextrw and pinsrw.
3494 for (unsigned i = 0; i != 8; ++i) {
3497 int EltIdx = MaskVals[i];
3500 SDValue ExtOp = (EltIdx < 8)
3501 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3502 DAG.getIntPtrConstant(EltIdx))
3503 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3504 DAG.getIntPtrConstant(EltIdx - 8));
3505 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3506 DAG.getIntPtrConstant(i));
3511 // v16i8 shuffles - Prefer shuffles in the following order:
3512 // 1. [ssse3] 1 x pshufb
3513 // 2. [ssse3] 2 x pshufb + 1 x por
3514 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3516 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3517 SelectionDAG &DAG, X86TargetLowering &TLI) {
3518 SDValue V1 = SVOp->getOperand(0);
3519 SDValue V2 = SVOp->getOperand(1);
3520 DebugLoc dl = SVOp->getDebugLoc();
3521 SmallVector<int, 16> MaskVals;
3522 SVOp->getMask(MaskVals);
3524 // If we have SSSE3, case 1 is generated when all result bytes come from
3525 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3526 // present, fall back to case 3.
3527 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3530 for (unsigned i = 0; i < 16; ++i) {
3531 int EltIdx = MaskVals[i];
3540 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3541 if (TLI.getSubtarget()->hasSSSE3()) {
3542 SmallVector<SDValue,16> pshufbMask;
3544 // If all result elements are from one input vector, then only translate
3545 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3547 // Otherwise, we have elements from both input vectors, and must zero out
3548 // elements that come from V2 in the first mask, and V1 in the second mask
3549 // so that we can OR them together.
3550 bool TwoInputs = !(V1Only || V2Only);
3551 for (unsigned i = 0; i != 16; ++i) {
3552 int EltIdx = MaskVals[i];
3553 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3554 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3557 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3559 // If all the elements are from V2, assign it to V1 and return after
3560 // building the first pshufb.
3563 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3564 DAG.getNode(ISD::BUILD_VECTOR, dl,
3565 MVT::v16i8, &pshufbMask[0], 16));
3569 // Calculate the shuffle mask for the second input, shuffle it, and
3570 // OR it with the first shuffled input.
3572 for (unsigned i = 0; i != 16; ++i) {
3573 int EltIdx = MaskVals[i];
3575 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3578 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3580 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3581 DAG.getNode(ISD::BUILD_VECTOR, dl,
3582 MVT::v16i8, &pshufbMask[0], 16));
3583 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3586 // No SSSE3 - Calculate in place words and then fix all out of place words
3587 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3588 // the 16 different words that comprise the two doublequadword input vectors.
3589 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3590 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3591 SDValue NewV = V2Only ? V2 : V1;
3592 for (int i = 0; i != 8; ++i) {
3593 int Elt0 = MaskVals[i*2];
3594 int Elt1 = MaskVals[i*2+1];
3596 // This word of the result is all undef, skip it.
3597 if (Elt0 < 0 && Elt1 < 0)
3600 // This word of the result is already in the correct place, skip it.
3601 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3603 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3606 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3607 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3610 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3611 // using a single extract together, load it and store it.
3612 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3613 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3614 DAG.getIntPtrConstant(Elt1 / 2));
3615 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3616 DAG.getIntPtrConstant(i));
3620 // If Elt1 is defined, extract it from the appropriate source. If the
3621 // source byte is not also odd, shift the extracted word left 8 bits
3622 // otherwise clear the bottom 8 bits if we need to do an or.
3624 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3625 DAG.getIntPtrConstant(Elt1 / 2));
3626 if ((Elt1 & 1) == 0)
3627 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3628 DAG.getConstant(8, TLI.getShiftAmountTy()));
3630 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3631 DAG.getConstant(0xFF00, MVT::i16));
3633 // If Elt0 is defined, extract it from the appropriate source. If the
3634 // source byte is not also even, shift the extracted word right 8 bits. If
3635 // Elt1 was also defined, OR the extracted values together before
3636 // inserting them in the result.
3638 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3639 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3640 if ((Elt0 & 1) != 0)
3641 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3642 DAG.getConstant(8, TLI.getShiftAmountTy()));
3644 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3645 DAG.getConstant(0x00FF, MVT::i16));
3646 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3649 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3650 DAG.getIntPtrConstant(i));
3652 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3655 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3656 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3657 /// done when every pair / quad of shuffle mask elements point to elements in
3658 /// the right sequence. e.g.
3659 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3661 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3663 TargetLowering &TLI, DebugLoc dl) {
3664 MVT VT = SVOp->getValueType(0);
3665 SDValue V1 = SVOp->getOperand(0);
3666 SDValue V2 = SVOp->getOperand(1);
3667 unsigned NumElems = VT.getVectorNumElements();
3668 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3669 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3670 MVT MaskEltVT = MaskVT.getVectorElementType();
3672 switch (VT.getSimpleVT()) {
3673 default: assert(false && "Unexpected!");
3674 case MVT::v4f32: NewVT = MVT::v2f64; break;
3675 case MVT::v4i32: NewVT = MVT::v2i64; break;
3676 case MVT::v8i16: NewVT = MVT::v4i32; break;
3677 case MVT::v16i8: NewVT = MVT::v4i32; break;
3680 if (NewWidth == 2) {
3686 int Scale = NumElems / NewWidth;
3687 SmallVector<int, 8> MaskVec;
3688 for (unsigned i = 0; i < NumElems; i += Scale) {
3690 for (int j = 0; j < Scale; ++j) {
3691 int EltIdx = SVOp->getMaskElt(i+j);
3695 StartIdx = EltIdx - (EltIdx % Scale);
3696 if (EltIdx != StartIdx + j)
3700 MaskVec.push_back(-1);
3702 MaskVec.push_back(StartIdx / Scale);
3705 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3706 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3707 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3710 /// getVZextMovL - Return a zero-extending vector move low node.
3712 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3713 SDValue SrcOp, SelectionDAG &DAG,
3714 const X86Subtarget *Subtarget, DebugLoc dl) {
3715 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3716 LoadSDNode *LD = NULL;
3717 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3718 LD = dyn_cast<LoadSDNode>(SrcOp);
3720 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3722 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3723 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3724 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3725 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3726 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3728 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3729 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3730 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3731 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3739 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3740 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3741 DAG.getNode(ISD::BIT_CONVERT, dl,
3745 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3748 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3749 SDValue V1 = SVOp->getOperand(0);
3750 SDValue V2 = SVOp->getOperand(1);
3751 DebugLoc dl = SVOp->getDebugLoc();
3752 MVT VT = SVOp->getValueType(0);
3754 SmallVector<std::pair<int, int>, 8> Locs;
3756 SmallVector<int, 8> Mask1(4U, -1);
3757 SmallVector<int, 8> PermMask;
3758 SVOp->getMask(PermMask);
3762 for (unsigned i = 0; i != 4; ++i) {
3763 int Idx = PermMask[i];
3765 Locs[i] = std::make_pair(-1, -1);
3767 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3769 Locs[i] = std::make_pair(0, NumLo);
3773 Locs[i] = std::make_pair(1, NumHi);
3775 Mask1[2+NumHi] = Idx;
3781 if (NumLo <= 2 && NumHi <= 2) {
3782 // If no more than two elements come from either vector. This can be
3783 // implemented with two shuffles. First shuffle gather the elements.
3784 // The second shuffle, which takes the first shuffle as both of its
3785 // vector operands, put the elements into the right order.
3786 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3788 SmallVector<int, 8> Mask2(4U, -1);
3790 for (unsigned i = 0; i != 4; ++i) {
3791 if (Locs[i].first == -1)
3794 unsigned Idx = (i < 2) ? 0 : 4;
3795 Idx += Locs[i].first * 2 + Locs[i].second;
3800 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
3801 } else if (NumLo == 3 || NumHi == 3) {
3802 // Otherwise, we must have three elements from one vector, call it X, and
3803 // one element from the other, call it Y. First, use a shufps to build an
3804 // intermediate vector with the one element from Y and the element from X
3805 // that will be in the same half in the final destination (the indexes don't
3806 // matter). Then, use a shufps to build the final vector, taking the half
3807 // containing the element from Y from the intermediate, and the other half
3810 // Normalize it so the 3 elements come from V1.
3811 CommuteVectorShuffleMask(PermMask, VT);
3815 // Find the element from V2.
3817 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3818 int Val = PermMask[HiIndex];
3825 Mask1[0] = PermMask[HiIndex];
3827 Mask1[2] = PermMask[HiIndex^1];
3829 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3832 Mask1[0] = PermMask[0];
3833 Mask1[1] = PermMask[1];
3834 Mask1[2] = HiIndex & 1 ? 6 : 4;
3835 Mask1[3] = HiIndex & 1 ? 4 : 6;
3836 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3838 Mask1[0] = HiIndex & 1 ? 2 : 0;
3839 Mask1[1] = HiIndex & 1 ? 0 : 2;
3840 Mask1[2] = PermMask[2];
3841 Mask1[3] = PermMask[3];
3846 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
3850 // Break it into (shuffle shuffle_hi, shuffle_lo).
3852 SmallVector<int,8> LoMask(4U, -1);
3853 SmallVector<int,8> HiMask(4U, -1);
3855 SmallVector<int,8> *MaskPtr = &LoMask;
3856 unsigned MaskIdx = 0;
3859 for (unsigned i = 0; i != 4; ++i) {
3866 int Idx = PermMask[i];
3868 Locs[i] = std::make_pair(-1, -1);
3869 } else if (Idx < 4) {
3870 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3871 (*MaskPtr)[LoIdx] = Idx;
3874 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3875 (*MaskPtr)[HiIdx] = Idx;
3880 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
3881 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
3882 SmallVector<int, 8> MaskOps;
3883 for (unsigned i = 0; i != 4; ++i) {
3884 if (Locs[i].first == -1) {
3885 MaskOps.push_back(-1);
3887 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3888 MaskOps.push_back(Idx);
3891 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
3895 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3896 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
3897 SDValue V1 = Op.getOperand(0);
3898 SDValue V2 = Op.getOperand(1);
3899 MVT VT = Op.getValueType();
3900 DebugLoc dl = Op.getDebugLoc();
3901 unsigned NumElems = VT.getVectorNumElements();
3902 bool isMMX = VT.getSizeInBits() == 64;
3903 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3904 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3905 bool V1IsSplat = false;
3906 bool V2IsSplat = false;
3908 if (isZeroShuffle(SVOp))
3909 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3911 // Promote splats to v4f32.
3912 if (SVOp->isSplat()) {
3913 if (isMMX || NumElems < 4)
3915 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
3918 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3920 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3921 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3922 if (NewOp.getNode())
3923 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3924 LowerVECTOR_SHUFFLE(NewOp, DAG));
3925 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3926 // FIXME: Figure out a cleaner way to do this.
3927 // Try to make use of movq to zero out the top part.
3928 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
3929 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3930 if (NewOp.getNode()) {
3931 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
3932 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
3933 DAG, Subtarget, dl);
3935 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
3936 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3937 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
3938 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3939 DAG, Subtarget, dl);
3943 if (X86::isPSHUFDMask(SVOp))
3946 // Check if this can be converted into a logical shift.
3947 bool isLeft = false;
3950 bool isShift = getSubtarget()->hasSSE2() &&
3951 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
3952 if (isShift && ShVal.hasOneUse()) {
3953 // If the shifted value has multiple uses, it may be cheaper to use
3954 // v_set0 + movlhps or movhlps, etc.
3955 MVT EVT = VT.getVectorElementType();
3956 ShAmt *= EVT.getSizeInBits();
3957 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
3960 if (X86::isMOVLMask(SVOp)) {
3963 if (ISD::isBuildVectorAllZeros(V1.getNode()))
3964 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
3969 // FIXME: fold these into legal mask.
3970 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
3971 X86::isMOVSLDUPMask(SVOp) ||
3972 X86::isMOVHLPSMask(SVOp) ||
3973 X86::isMOVHPMask(SVOp) ||
3974 X86::isMOVLPMask(SVOp)))
3977 if (ShouldXformToMOVHLPS(SVOp) ||
3978 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
3979 return CommuteVectorShuffle(SVOp, DAG);
3982 // No better options. Use a vshl / vsrl.
3983 MVT EVT = VT.getVectorElementType();
3984 ShAmt *= EVT.getSizeInBits();
3985 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
3988 bool Commuted = false;
3989 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3990 // 1,1,1,1 -> v8i16 though.
3991 V1IsSplat = isSplatVector(V1.getNode());
3992 V2IsSplat = isSplatVector(V2.getNode());
3994 // Canonicalize the splat or undef, if present, to be on the RHS.
3995 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3996 Op = CommuteVectorShuffle(SVOp, DAG);
3997 SVOp = cast<ShuffleVectorSDNode>(Op);
3998 V1 = SVOp->getOperand(0);
3999 V2 = SVOp->getOperand(1);
4000 std::swap(V1IsSplat, V2IsSplat);
4001 std::swap(V1IsUndef, V2IsUndef);
4005 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4006 // Shuffling low element of v1 into undef, just return v1.
4009 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4010 // the instruction selector will not match, so get a canonical MOVL with
4011 // swapped operands to undo the commute.
4012 return getMOVL(DAG, dl, VT, V2, V1);
4015 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4016 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4017 X86::isUNPCKLMask(SVOp) ||
4018 X86::isUNPCKHMask(SVOp))
4022 // Normalize mask so all entries that point to V2 points to its first
4023 // element then try to match unpck{h|l} again. If match, return a
4024 // new vector_shuffle with the corrected mask.
4025 SDValue NewMask = NormalizeMask(SVOp, DAG);
4026 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4027 if (NSVOp != SVOp) {
4028 if (X86::isUNPCKLMask(NSVOp, true)) {
4030 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4037 // Commute is back and try unpck* again.
4038 // FIXME: this seems wrong.
4039 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4040 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4041 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4042 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4043 X86::isUNPCKLMask(NewSVOp) ||
4044 X86::isUNPCKHMask(NewSVOp))
4048 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4050 // Normalize the node to match x86 shuffle ops if needed
4051 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4052 return CommuteVectorShuffle(SVOp, DAG);
4054 // Check for legal shuffle and return?
4055 SmallVector<int, 16> PermMask;
4056 SVOp->getMask(PermMask);
4057 if (isShuffleMaskLegal(PermMask, VT))
4060 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4061 if (VT == MVT::v8i16) {
4062 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4063 if (NewOp.getNode())
4067 if (VT == MVT::v16i8) {
4068 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4069 if (NewOp.getNode())
4073 // Handle all 4 wide cases with a number of shuffles except for MMX.
4074 if (NumElems == 4 && !isMMX)
4075 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4081 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4082 SelectionDAG &DAG) {
4083 MVT VT = Op.getValueType();
4084 DebugLoc dl = Op.getDebugLoc();
4085 if (VT.getSizeInBits() == 8) {
4086 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4087 Op.getOperand(0), Op.getOperand(1));
4088 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4089 DAG.getValueType(VT));
4090 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4091 } else if (VT.getSizeInBits() == 16) {
4092 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4093 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4095 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4096 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4097 DAG.getNode(ISD::BIT_CONVERT, dl,
4101 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4102 Op.getOperand(0), Op.getOperand(1));
4103 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4104 DAG.getValueType(VT));
4105 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4106 } else if (VT == MVT::f32) {
4107 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4108 // the result back to FR32 register. It's only worth matching if the
4109 // result has a single use which is a store or a bitcast to i32. And in
4110 // the case of a store, it's not worth it if the index is a constant 0,
4111 // because a MOVSSmr can be used instead, which is smaller and faster.
4112 if (!Op.hasOneUse())
4114 SDNode *User = *Op.getNode()->use_begin();
4115 if ((User->getOpcode() != ISD::STORE ||
4116 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4117 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4118 (User->getOpcode() != ISD::BIT_CONVERT ||
4119 User->getValueType(0) != MVT::i32))
4121 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4122 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4125 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4126 } else if (VT == MVT::i32) {
4127 // ExtractPS works with constant index.
4128 if (isa<ConstantSDNode>(Op.getOperand(1)))
4136 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4137 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4140 if (Subtarget->hasSSE41()) {
4141 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4146 MVT VT = Op.getValueType();
4147 DebugLoc dl = Op.getDebugLoc();
4148 // TODO: handle v16i8.
4149 if (VT.getSizeInBits() == 16) {
4150 SDValue Vec = Op.getOperand(0);
4151 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4153 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4154 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4155 DAG.getNode(ISD::BIT_CONVERT, dl,
4158 // Transform it so it match pextrw which produces a 32-bit result.
4159 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4160 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4161 Op.getOperand(0), Op.getOperand(1));
4162 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4163 DAG.getValueType(VT));
4164 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4165 } else if (VT.getSizeInBits() == 32) {
4166 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4170 // SHUFPS the element to the lowest double word, then movss.
4171 int Mask[4] = { Idx, -1, -1, -1 };
4172 MVT VVT = Op.getOperand(0).getValueType();
4173 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4174 DAG.getUNDEF(VVT), Mask);
4175 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4176 DAG.getIntPtrConstant(0));
4177 } else if (VT.getSizeInBits() == 64) {
4178 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4179 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4180 // to match extract_elt for f64.
4181 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4185 // UNPCKHPD the element to the lowest double word, then movsd.
4186 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4187 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4188 int Mask[2] = { 1, -1 };
4189 MVT VVT = Op.getOperand(0).getValueType();
4190 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4191 DAG.getUNDEF(VVT), Mask);
4192 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4193 DAG.getIntPtrConstant(0));
4200 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4201 MVT VT = Op.getValueType();
4202 MVT EVT = VT.getVectorElementType();
4203 DebugLoc dl = Op.getDebugLoc();
4205 SDValue N0 = Op.getOperand(0);
4206 SDValue N1 = Op.getOperand(1);
4207 SDValue N2 = Op.getOperand(2);
4209 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4210 isa<ConstantSDNode>(N2)) {
4211 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4213 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4215 if (N1.getValueType() != MVT::i32)
4216 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4217 if (N2.getValueType() != MVT::i32)
4218 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4219 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4220 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4221 // Bits [7:6] of the constant are the source select. This will always be
4222 // zero here. The DAG Combiner may combine an extract_elt index into these
4223 // bits. For example (insert (extract, 3), 2) could be matched by putting
4224 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4225 // Bits [5:4] of the constant are the destination select. This is the
4226 // value of the incoming immediate.
4227 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4228 // combine either bitwise AND or insert of float 0.0 to set these bits.
4229 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4230 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4231 } else if (EVT == MVT::i32) {
4232 // InsertPS works with constant index.
4233 if (isa<ConstantSDNode>(N2))
4240 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4241 MVT VT = Op.getValueType();
4242 MVT EVT = VT.getVectorElementType();
4244 if (Subtarget->hasSSE41())
4245 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4250 DebugLoc dl = Op.getDebugLoc();
4251 SDValue N0 = Op.getOperand(0);
4252 SDValue N1 = Op.getOperand(1);
4253 SDValue N2 = Op.getOperand(2);
4255 if (EVT.getSizeInBits() == 16) {
4256 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4257 // as its second argument.
4258 if (N1.getValueType() != MVT::i32)
4259 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4260 if (N2.getValueType() != MVT::i32)
4261 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4262 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4268 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4269 DebugLoc dl = Op.getDebugLoc();
4270 if (Op.getValueType() == MVT::v2f32)
4271 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4272 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4273 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4274 Op.getOperand(0))));
4276 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4277 MVT VT = MVT::v2i32;
4278 switch (Op.getValueType().getSimpleVT()) {
4285 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4286 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4289 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4290 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4291 // one of the above mentioned nodes. It has to be wrapped because otherwise
4292 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4293 // be used to form addressing mode. These wrapped nodes will be selected
4296 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4297 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4298 // FIXME there isn't really any debug info here, should come from the parent
4299 DebugLoc dl = CP->getDebugLoc();
4300 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4301 CP->getAlignment());
4302 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4303 // With PIC, the address is actually $g + Offset.
4304 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4305 !Subtarget->isPICStyleRIPRel()) {
4306 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4307 DAG.getNode(X86ISD::GlobalBaseReg,
4308 DebugLoc::getUnknownLoc(),
4317 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4319 SelectionDAG &DAG) const {
4320 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4321 bool ExtraLoadRequired =
4322 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4324 // Create the TargetGlobalAddress node, folding in the constant
4325 // offset if it is legal.
4327 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4328 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4331 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4332 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4334 // With PIC, the address is actually $g + Offset.
4335 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4336 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4337 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4341 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4342 // load the value at address GV, not the value of GV itself. This means that
4343 // the GlobalAddress must be in the base or index register of the address, not
4344 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4345 // The same applies for external symbols during PIC codegen
4346 if (ExtraLoadRequired)
4347 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4348 PseudoSourceValue::getGOT(), 0);
4350 // If there was a non-zero offset that we didn't fold, create an explicit
4353 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4354 DAG.getConstant(Offset, getPointerTy()));
4360 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4361 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4362 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4363 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4367 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4368 SDValue *InFlag, const MVT PtrVT, unsigned ReturnReg) {
4369 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4370 DebugLoc dl = GA->getDebugLoc();
4371 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4372 GA->getValueType(0),
4375 SDValue Ops[] = { Chain, TGA, *InFlag };
4376 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4378 SDValue Ops[] = { Chain, TGA };
4379 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4381 SDValue Flag = Chain.getValue(1);
4382 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4385 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4387 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4390 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4391 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4392 DAG.getNode(X86ISD::GlobalBaseReg,
4393 DebugLoc::getUnknownLoc(),
4395 InFlag = Chain.getValue(1);
4397 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX);
4400 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4402 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4404 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX);
4407 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4408 // "local exec" model.
4409 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4410 const MVT PtrVT, TLSModel::Model model,
4412 DebugLoc dl = GA->getDebugLoc();
4413 // Get the Thread Pointer
4414 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4415 DebugLoc::getUnknownLoc(), PtrVT,
4416 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4419 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4422 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4424 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4425 GA->getValueType(0),
4427 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
4429 if (model == TLSModel::InitialExec)
4430 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4431 PseudoSourceValue::getGOT(), 0);
4433 // The address of the thread local variable is the add of the thread
4434 // pointer with the offset of the variable.
4435 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4439 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4440 // TODO: implement the "local dynamic" model
4441 // TODO: implement the "initial exec"model for pic executables
4442 assert(Subtarget->isTargetELF() &&
4443 "TLS not implemented for non-ELF targets");
4444 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4445 GlobalValue *GV = GA->getGlobal();
4446 TLSModel::Model model =
4447 getTLSModel (GV, getTargetMachine().getRelocationModel());
4448 if (Subtarget->is64Bit()) {
4450 case TLSModel::GeneralDynamic:
4451 case TLSModel::LocalDynamic: // not implemented
4452 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4454 case TLSModel::InitialExec:
4455 case TLSModel::LocalExec:
4456 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, true);
4460 case TLSModel::GeneralDynamic:
4461 case TLSModel::LocalDynamic: // not implemented
4462 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4464 case TLSModel::InitialExec:
4465 case TLSModel::LocalExec:
4466 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, false);
4469 assert(0 && "Unreachable");
4474 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4475 // FIXME there isn't really any debug info here
4476 DebugLoc dl = Op.getDebugLoc();
4477 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4478 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4479 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4480 // With PIC, the address is actually $g + Offset.
4481 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4482 !Subtarget->isPICStyleRIPRel()) {
4483 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4484 DAG.getNode(X86ISD::GlobalBaseReg,
4485 DebugLoc::getUnknownLoc(),
4493 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4494 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4495 // FIXME there isn't really any debug into here
4496 DebugLoc dl = JT->getDebugLoc();
4497 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4498 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4499 // With PIC, the address is actually $g + Offset.
4500 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4501 !Subtarget->isPICStyleRIPRel()) {
4502 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4503 DAG.getNode(X86ISD::GlobalBaseReg,
4504 DebugLoc::getUnknownLoc(),
4512 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4513 /// take a 2 x i32 value to shift plus a shift amount.
4514 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4515 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4516 MVT VT = Op.getValueType();
4517 unsigned VTBits = VT.getSizeInBits();
4518 DebugLoc dl = Op.getDebugLoc();
4519 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4520 SDValue ShOpLo = Op.getOperand(0);
4521 SDValue ShOpHi = Op.getOperand(1);
4522 SDValue ShAmt = Op.getOperand(2);
4523 SDValue Tmp1 = isSRA ?
4524 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4525 DAG.getConstant(VTBits - 1, MVT::i8)) :
4526 DAG.getConstant(0, VT);
4529 if (Op.getOpcode() == ISD::SHL_PARTS) {
4530 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4531 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4533 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4534 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4537 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4538 DAG.getConstant(VTBits, MVT::i8));
4539 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4540 AndNode, DAG.getConstant(0, MVT::i8));
4543 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4544 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4545 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4547 if (Op.getOpcode() == ISD::SHL_PARTS) {
4548 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4549 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4551 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4552 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4555 SDValue Ops[2] = { Lo, Hi };
4556 return DAG.getMergeValues(Ops, 2, dl);
4559 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4560 MVT SrcVT = Op.getOperand(0).getValueType();
4561 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4562 "Unknown SINT_TO_FP to lower!");
4564 // These are really Legal; return the operand so the caller accepts it as
4566 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4568 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4569 Subtarget->is64Bit()) {
4573 DebugLoc dl = Op.getDebugLoc();
4574 unsigned Size = SrcVT.getSizeInBits()/8;
4575 MachineFunction &MF = DAG.getMachineFunction();
4576 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4577 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4578 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4580 PseudoSourceValue::getFixedStack(SSFI), 0);
4581 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4584 SDValue X86TargetLowering::BuildFILD(SDValue Op, MVT SrcVT, SDValue Chain,
4586 SelectionDAG &DAG) {
4588 DebugLoc dl = Op.getDebugLoc();
4590 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4592 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4594 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4595 SmallVector<SDValue, 8> Ops;
4596 Ops.push_back(Chain);
4597 Ops.push_back(StackSlot);
4598 Ops.push_back(DAG.getValueType(SrcVT));
4599 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4600 Tys, &Ops[0], Ops.size());
4603 Chain = Result.getValue(1);
4604 SDValue InFlag = Result.getValue(2);
4606 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4607 // shouldn't be necessary except that RFP cannot be live across
4608 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4609 MachineFunction &MF = DAG.getMachineFunction();
4610 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4611 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4612 Tys = DAG.getVTList(MVT::Other);
4613 SmallVector<SDValue, 8> Ops;
4614 Ops.push_back(Chain);
4615 Ops.push_back(Result);
4616 Ops.push_back(StackSlot);
4617 Ops.push_back(DAG.getValueType(Op.getValueType()));
4618 Ops.push_back(InFlag);
4619 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4620 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4621 PseudoSourceValue::getFixedStack(SSFI), 0);
4627 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4628 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4629 // This algorithm is not obvious. Here it is in C code, more or less:
4631 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4632 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4633 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4635 // Copy ints to xmm registers.
4636 __m128i xh = _mm_cvtsi32_si128( hi );
4637 __m128i xl = _mm_cvtsi32_si128( lo );
4639 // Combine into low half of a single xmm register.
4640 __m128i x = _mm_unpacklo_epi32( xh, xl );
4644 // Merge in appropriate exponents to give the integer bits the right
4646 x = _mm_unpacklo_epi32( x, exp );
4648 // Subtract away the biases to deal with the IEEE-754 double precision
4650 d = _mm_sub_pd( (__m128d) x, bias );
4652 // All conversions up to here are exact. The correctly rounded result is
4653 // calculated using the current rounding mode using the following
4655 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4656 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4657 // store doesn't really need to be here (except
4658 // maybe to zero the other double)
4663 DebugLoc dl = Op.getDebugLoc();
4665 // Build some magic constants.
4666 std::vector<Constant*> CV0;
4667 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4668 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4669 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4670 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4671 Constant *C0 = ConstantVector::get(CV0);
4672 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4674 std::vector<Constant*> CV1;
4675 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4676 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4677 Constant *C1 = ConstantVector::get(CV1);
4678 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4680 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4681 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4683 DAG.getIntPtrConstant(1)));
4684 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4685 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4687 DAG.getIntPtrConstant(0)));
4688 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4689 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4690 PseudoSourceValue::getConstantPool(), 0,
4692 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
4693 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4694 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4695 PseudoSourceValue::getConstantPool(), 0,
4697 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4699 // Add the halves; easiest way is to swap them into another reg first.
4700 int ShufMask[2] = { 1, -1 };
4701 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
4702 DAG.getUNDEF(MVT::v2f64), ShufMask);
4703 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4704 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4705 DAG.getIntPtrConstant(0));
4708 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4709 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4710 DebugLoc dl = Op.getDebugLoc();
4711 // FP constant to bias correct the final result.
4712 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4715 // Load the 32-bit value into an XMM register.
4716 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4717 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4719 DAG.getIntPtrConstant(0)));
4721 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4722 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4723 DAG.getIntPtrConstant(0));
4725 // Or the load with the bias.
4726 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4727 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4728 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4730 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4731 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4732 MVT::v2f64, Bias)));
4733 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4734 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4735 DAG.getIntPtrConstant(0));
4737 // Subtract the bias.
4738 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4740 // Handle final rounding.
4741 MVT DestVT = Op.getValueType();
4743 if (DestVT.bitsLT(MVT::f64)) {
4744 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4745 DAG.getIntPtrConstant(0));
4746 } else if (DestVT.bitsGT(MVT::f64)) {
4747 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4750 // Handle final rounding.
4754 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4755 SDValue N0 = Op.getOperand(0);
4756 DebugLoc dl = Op.getDebugLoc();
4758 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4759 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4760 // the optimization here.
4761 if (DAG.SignBitIsZero(N0))
4762 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4764 MVT SrcVT = N0.getValueType();
4765 if (SrcVT == MVT::i64) {
4766 // We only handle SSE2 f64 target here; caller can expand the rest.
4767 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4770 return LowerUINT_TO_FP_i64(Op, DAG);
4771 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
4772 return LowerUINT_TO_FP_i32(Op, DAG);
4775 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
4777 // Make a 64-bit buffer, and use it to build an FILD.
4778 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
4779 SDValue WordOff = DAG.getConstant(4, getPointerTy());
4780 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
4781 getPointerTy(), StackSlot, WordOff);
4782 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4783 StackSlot, NULL, 0);
4784 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
4785 OffsetSlot, NULL, 0);
4786 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
4789 std::pair<SDValue,SDValue> X86TargetLowering::
4790 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
4791 DebugLoc dl = Op.getDebugLoc();
4793 MVT DstTy = Op.getValueType();
4796 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
4800 assert(DstTy.getSimpleVT() <= MVT::i64 &&
4801 DstTy.getSimpleVT() >= MVT::i16 &&
4802 "Unknown FP_TO_SINT to lower!");
4804 // These are really Legal.
4805 if (DstTy == MVT::i32 &&
4806 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4807 return std::make_pair(SDValue(), SDValue());
4808 if (Subtarget->is64Bit() &&
4809 DstTy == MVT::i64 &&
4810 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4811 return std::make_pair(SDValue(), SDValue());
4813 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4815 MachineFunction &MF = DAG.getMachineFunction();
4816 unsigned MemSize = DstTy.getSizeInBits()/8;
4817 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4818 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4821 switch (DstTy.getSimpleVT()) {
4822 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4823 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4824 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4825 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4828 SDValue Chain = DAG.getEntryNode();
4829 SDValue Value = Op.getOperand(0);
4830 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4831 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4832 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
4833 PseudoSourceValue::getFixedStack(SSFI), 0);
4834 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4836 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4838 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
4839 Chain = Value.getValue(1);
4840 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4841 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4844 // Build the FP_TO_INT*_IN_MEM
4845 SDValue Ops[] = { Chain, Value, StackSlot };
4846 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
4848 return std::make_pair(FIST, StackSlot);
4851 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4852 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
4853 SDValue FIST = Vals.first, StackSlot = Vals.second;
4854 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
4855 if (FIST.getNode() == 0) return Op;
4858 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4859 FIST, StackSlot, NULL, 0);
4862 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
4863 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
4864 SDValue FIST = Vals.first, StackSlot = Vals.second;
4865 assert(FIST.getNode() && "Unexpected failure");
4868 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4869 FIST, StackSlot, NULL, 0);
4872 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4873 DebugLoc dl = Op.getDebugLoc();
4874 MVT VT = Op.getValueType();
4877 EltVT = VT.getVectorElementType();
4878 std::vector<Constant*> CV;
4879 if (EltVT == MVT::f64) {
4880 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4884 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4890 Constant *C = ConstantVector::get(CV);
4891 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4892 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4893 PseudoSourceValue::getConstantPool(), 0,
4895 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
4898 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4899 DebugLoc dl = Op.getDebugLoc();
4900 MVT VT = Op.getValueType();
4902 unsigned EltNum = 1;
4903 if (VT.isVector()) {
4904 EltVT = VT.getVectorElementType();
4905 EltNum = VT.getVectorNumElements();
4907 std::vector<Constant*> CV;
4908 if (EltVT == MVT::f64) {
4909 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4913 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4919 Constant *C = ConstantVector::get(CV);
4920 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4921 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4922 PseudoSourceValue::getConstantPool(), 0,
4924 if (VT.isVector()) {
4925 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4926 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
4927 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4929 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
4931 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
4935 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4936 SDValue Op0 = Op.getOperand(0);
4937 SDValue Op1 = Op.getOperand(1);
4938 DebugLoc dl = Op.getDebugLoc();
4939 MVT VT = Op.getValueType();
4940 MVT SrcVT = Op1.getValueType();
4942 // If second operand is smaller, extend it first.
4943 if (SrcVT.bitsLT(VT)) {
4944 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
4947 // And if it is bigger, shrink it first.
4948 if (SrcVT.bitsGT(VT)) {
4949 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
4953 // At this point the operands and the result should have the same
4954 // type, and that won't be f80 since that is not custom lowered.
4956 // First get the sign bit of second operand.
4957 std::vector<Constant*> CV;
4958 if (SrcVT == MVT::f64) {
4959 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4960 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4962 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4963 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4964 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4965 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4967 Constant *C = ConstantVector::get(CV);
4968 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4969 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
4970 PseudoSourceValue::getConstantPool(), 0,
4972 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
4974 // Shift sign bit right or left if the two operands have different types.
4975 if (SrcVT.bitsGT(VT)) {
4976 // Op0 is MVT::f32, Op1 is MVT::f64.
4977 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
4978 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
4979 DAG.getConstant(32, MVT::i32));
4980 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
4981 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
4982 DAG.getIntPtrConstant(0));
4985 // Clear first operand sign bit.
4987 if (VT == MVT::f64) {
4988 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4989 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4991 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4992 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4993 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4994 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4996 C = ConstantVector::get(CV);
4997 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4998 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4999 PseudoSourceValue::getConstantPool(), 0,
5001 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5003 // Or the value with the sign bit.
5004 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5007 /// Emit nodes that will be selected as "test Op0,Op0", or something
5009 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5010 SelectionDAG &DAG) {
5011 DebugLoc dl = Op.getDebugLoc();
5013 // CF and OF aren't always set the way we want. Determine which
5014 // of these we need.
5015 bool NeedCF = false;
5016 bool NeedOF = false;
5018 case X86::COND_A: case X86::COND_AE:
5019 case X86::COND_B: case X86::COND_BE:
5022 case X86::COND_G: case X86::COND_GE:
5023 case X86::COND_L: case X86::COND_LE:
5024 case X86::COND_O: case X86::COND_NO:
5030 // See if we can use the EFLAGS value from the operand instead of
5031 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5032 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5033 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5034 unsigned Opcode = 0;
5035 unsigned NumOperands = 0;
5036 switch (Op.getNode()->getOpcode()) {
5038 // Due to an isel shortcoming, be conservative if this add is likely to
5039 // be selected as part of a load-modify-store instruction. When the root
5040 // node in a match is a store, isel doesn't know how to remap non-chain
5041 // non-flag uses of other nodes in the match, such as the ADD in this
5042 // case. This leads to the ADD being left around and reselected, with
5043 // the result being two adds in the output.
5044 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5045 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5046 if (UI->getOpcode() == ISD::STORE)
5048 if (ConstantSDNode *C =
5049 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5050 // An add of one will be selected as an INC.
5051 if (C->getAPIntValue() == 1) {
5052 Opcode = X86ISD::INC;
5056 // An add of negative one (subtract of one) will be selected as a DEC.
5057 if (C->getAPIntValue().isAllOnesValue()) {
5058 Opcode = X86ISD::DEC;
5063 // Otherwise use a regular EFLAGS-setting add.
5064 Opcode = X86ISD::ADD;
5068 // Due to the ISEL shortcoming noted above, be conservative if this sub is
5069 // likely to be selected as part of a load-modify-store instruction.
5070 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5071 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5072 if (UI->getOpcode() == ISD::STORE)
5074 // Otherwise use a regular EFLAGS-setting sub.
5075 Opcode = X86ISD::SUB;
5082 return SDValue(Op.getNode(), 1);
5088 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5089 SmallVector<SDValue, 4> Ops;
5090 for (unsigned i = 0; i != NumOperands; ++i)
5091 Ops.push_back(Op.getOperand(i));
5092 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5093 DAG.ReplaceAllUsesWith(Op, New);
5094 return SDValue(New.getNode(), 1);
5098 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5099 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5100 DAG.getConstant(0, Op.getValueType()));
5103 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5105 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5106 SelectionDAG &DAG) {
5107 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5108 if (C->getAPIntValue() == 0)
5109 return EmitTest(Op0, X86CC, DAG);
5111 DebugLoc dl = Op0.getDebugLoc();
5112 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5115 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5116 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5117 SDValue Op0 = Op.getOperand(0);
5118 SDValue Op1 = Op.getOperand(1);
5119 DebugLoc dl = Op.getDebugLoc();
5120 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5122 // Lower (X & (1 << N)) == 0 to BT(X, N).
5123 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5124 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5125 if (Op0.getOpcode() == ISD::AND &&
5127 Op1.getOpcode() == ISD::Constant &&
5128 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5129 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5131 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5132 if (ConstantSDNode *Op010C =
5133 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5134 if (Op010C->getZExtValue() == 1) {
5135 LHS = Op0.getOperand(0);
5136 RHS = Op0.getOperand(1).getOperand(1);
5138 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5139 if (ConstantSDNode *Op000C =
5140 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5141 if (Op000C->getZExtValue() == 1) {
5142 LHS = Op0.getOperand(1);
5143 RHS = Op0.getOperand(0).getOperand(1);
5145 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5146 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5147 SDValue AndLHS = Op0.getOperand(0);
5148 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5149 LHS = AndLHS.getOperand(0);
5150 RHS = AndLHS.getOperand(1);
5154 if (LHS.getNode()) {
5155 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5156 // instruction. Since the shift amount is in-range-or-undefined, we know
5157 // that doing a bittest on the i16 value is ok. We extend to i32 because
5158 // the encoding for the i16 version is larger than the i32 version.
5159 if (LHS.getValueType() == MVT::i8)
5160 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5162 // If the operand types disagree, extend the shift amount to match. Since
5163 // BT ignores high bits (like shifts) we can use anyextend.
5164 if (LHS.getValueType() != RHS.getValueType())
5165 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5167 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5168 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5169 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5170 DAG.getConstant(Cond, MVT::i8), BT);
5174 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5175 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5177 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5178 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5179 DAG.getConstant(X86CC, MVT::i8), Cond);
5182 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5184 SDValue Op0 = Op.getOperand(0);
5185 SDValue Op1 = Op.getOperand(1);
5186 SDValue CC = Op.getOperand(2);
5187 MVT VT = Op.getValueType();
5188 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5189 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5190 DebugLoc dl = Op.getDebugLoc();
5194 MVT VT0 = Op0.getValueType();
5195 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5196 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5199 switch (SetCCOpcode) {
5202 case ISD::SETEQ: SSECC = 0; break;
5204 case ISD::SETGT: Swap = true; // Fallthrough
5206 case ISD::SETOLT: SSECC = 1; break;
5208 case ISD::SETGE: Swap = true; // Fallthrough
5210 case ISD::SETOLE: SSECC = 2; break;
5211 case ISD::SETUO: SSECC = 3; break;
5213 case ISD::SETNE: SSECC = 4; break;
5214 case ISD::SETULE: Swap = true;
5215 case ISD::SETUGE: SSECC = 5; break;
5216 case ISD::SETULT: Swap = true;
5217 case ISD::SETUGT: SSECC = 6; break;
5218 case ISD::SETO: SSECC = 7; break;
5221 std::swap(Op0, Op1);
5223 // In the two special cases we can't handle, emit two comparisons.
5225 if (SetCCOpcode == ISD::SETUEQ) {
5227 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5228 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5229 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5231 else if (SetCCOpcode == ISD::SETONE) {
5233 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5234 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5235 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5237 assert(0 && "Illegal FP comparison");
5239 // Handle all other FP comparisons here.
5240 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5243 // We are handling one of the integer comparisons here. Since SSE only has
5244 // GT and EQ comparisons for integer, swapping operands and multiple
5245 // operations may be required for some comparisons.
5246 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5247 bool Swap = false, Invert = false, FlipSigns = false;
5249 switch (VT.getSimpleVT()) {
5251 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5252 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5253 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5254 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5257 switch (SetCCOpcode) {
5259 case ISD::SETNE: Invert = true;
5260 case ISD::SETEQ: Opc = EQOpc; break;
5261 case ISD::SETLT: Swap = true;
5262 case ISD::SETGT: Opc = GTOpc; break;
5263 case ISD::SETGE: Swap = true;
5264 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5265 case ISD::SETULT: Swap = true;
5266 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5267 case ISD::SETUGE: Swap = true;
5268 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5271 std::swap(Op0, Op1);
5273 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5274 // bits of the inputs before performing those operations.
5276 MVT EltVT = VT.getVectorElementType();
5277 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5279 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5280 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5282 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5283 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5286 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5288 // If the logical-not of the result is required, perform that now.
5290 Result = DAG.getNOT(dl, Result, VT);
5295 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5296 static bool isX86LogicalCmp(SDValue Op) {
5297 unsigned Opc = Op.getNode()->getOpcode();
5298 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5300 if (Op.getResNo() == 1 &&
5301 (Opc == X86ISD::ADD ||
5302 Opc == X86ISD::SUB ||
5303 Opc == X86ISD::SMUL ||
5304 Opc == X86ISD::UMUL ||
5305 Opc == X86ISD::INC ||
5306 Opc == X86ISD::DEC))
5312 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5313 bool addTest = true;
5314 SDValue Cond = Op.getOperand(0);
5315 DebugLoc dl = Op.getDebugLoc();
5318 if (Cond.getOpcode() == ISD::SETCC)
5319 Cond = LowerSETCC(Cond, DAG);
5321 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5322 // setting operand in place of the X86ISD::SETCC.
5323 if (Cond.getOpcode() == X86ISD::SETCC) {
5324 CC = Cond.getOperand(0);
5326 SDValue Cmp = Cond.getOperand(1);
5327 unsigned Opc = Cmp.getOpcode();
5328 MVT VT = Op.getValueType();
5330 bool IllegalFPCMov = false;
5331 if (VT.isFloatingPoint() && !VT.isVector() &&
5332 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5333 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5335 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5336 Opc == X86ISD::BT) { // FIXME
5343 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5344 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5347 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5348 SmallVector<SDValue, 4> Ops;
5349 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5350 // condition is true.
5351 Ops.push_back(Op.getOperand(2));
5352 Ops.push_back(Op.getOperand(1));
5354 Ops.push_back(Cond);
5355 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5358 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5359 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5360 // from the AND / OR.
5361 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5362 Opc = Op.getOpcode();
5363 if (Opc != ISD::OR && Opc != ISD::AND)
5365 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5366 Op.getOperand(0).hasOneUse() &&
5367 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5368 Op.getOperand(1).hasOneUse());
5371 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5372 // 1 and that the SETCC node has a single use.
5373 static bool isXor1OfSetCC(SDValue Op) {
5374 if (Op.getOpcode() != ISD::XOR)
5376 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5377 if (N1C && N1C->getAPIntValue() == 1) {
5378 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5379 Op.getOperand(0).hasOneUse();
5384 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5385 bool addTest = true;
5386 SDValue Chain = Op.getOperand(0);
5387 SDValue Cond = Op.getOperand(1);
5388 SDValue Dest = Op.getOperand(2);
5389 DebugLoc dl = Op.getDebugLoc();
5392 if (Cond.getOpcode() == ISD::SETCC)
5393 Cond = LowerSETCC(Cond, DAG);
5395 // FIXME: LowerXALUO doesn't handle these!!
5396 else if (Cond.getOpcode() == X86ISD::ADD ||
5397 Cond.getOpcode() == X86ISD::SUB ||
5398 Cond.getOpcode() == X86ISD::SMUL ||
5399 Cond.getOpcode() == X86ISD::UMUL)
5400 Cond = LowerXALUO(Cond, DAG);
5403 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5404 // setting operand in place of the X86ISD::SETCC.
5405 if (Cond.getOpcode() == X86ISD::SETCC) {
5406 CC = Cond.getOperand(0);
5408 SDValue Cmp = Cond.getOperand(1);
5409 unsigned Opc = Cmp.getOpcode();
5410 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5411 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5415 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5419 // These can only come from an arithmetic instruction with overflow,
5420 // e.g. SADDO, UADDO.
5421 Cond = Cond.getNode()->getOperand(1);
5428 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5429 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5430 if (CondOpc == ISD::OR) {
5431 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5432 // two branches instead of an explicit OR instruction with a
5434 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5435 isX86LogicalCmp(Cmp)) {
5436 CC = Cond.getOperand(0).getOperand(0);
5437 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5438 Chain, Dest, CC, Cmp);
5439 CC = Cond.getOperand(1).getOperand(0);
5443 } else { // ISD::AND
5444 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5445 // two branches instead of an explicit AND instruction with a
5446 // separate test. However, we only do this if this block doesn't
5447 // have a fall-through edge, because this requires an explicit
5448 // jmp when the condition is false.
5449 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5450 isX86LogicalCmp(Cmp) &&
5451 Op.getNode()->hasOneUse()) {
5452 X86::CondCode CCode =
5453 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5454 CCode = X86::GetOppositeBranchCondition(CCode);
5455 CC = DAG.getConstant(CCode, MVT::i8);
5456 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5457 // Look for an unconditional branch following this conditional branch.
5458 // We need this because we need to reverse the successors in order
5459 // to implement FCMP_OEQ.
5460 if (User.getOpcode() == ISD::BR) {
5461 SDValue FalseBB = User.getOperand(1);
5463 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5464 assert(NewBR == User);
5467 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5468 Chain, Dest, CC, Cmp);
5469 X86::CondCode CCode =
5470 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5471 CCode = X86::GetOppositeBranchCondition(CCode);
5472 CC = DAG.getConstant(CCode, MVT::i8);
5478 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5479 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5480 // It should be transformed during dag combiner except when the condition
5481 // is set by a arithmetics with overflow node.
5482 X86::CondCode CCode =
5483 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5484 CCode = X86::GetOppositeBranchCondition(CCode);
5485 CC = DAG.getConstant(CCode, MVT::i8);
5486 Cond = Cond.getOperand(0).getOperand(1);
5492 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5493 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5495 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5496 Chain, Dest, CC, Cond);
5500 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5501 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5502 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5503 // that the guard pages used by the OS virtual memory manager are allocated in
5504 // correct sequence.
5506 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5507 SelectionDAG &DAG) {
5508 assert(Subtarget->isTargetCygMing() &&
5509 "This should be used only on Cygwin/Mingw targets");
5510 DebugLoc dl = Op.getDebugLoc();
5513 SDValue Chain = Op.getOperand(0);
5514 SDValue Size = Op.getOperand(1);
5515 // FIXME: Ensure alignment here
5519 MVT IntPtr = getPointerTy();
5520 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5522 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5524 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5525 Flag = Chain.getValue(1);
5527 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5528 SDValue Ops[] = { Chain,
5529 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5530 DAG.getRegister(X86::EAX, IntPtr),
5531 DAG.getRegister(X86StackPtr, SPTy),
5533 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5534 Flag = Chain.getValue(1);
5536 Chain = DAG.getCALLSEQ_END(Chain,
5537 DAG.getIntPtrConstant(0, true),
5538 DAG.getIntPtrConstant(0, true),
5541 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5543 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5544 return DAG.getMergeValues(Ops1, 2, dl);
5548 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5550 SDValue Dst, SDValue Src,
5551 SDValue Size, unsigned Align,
5553 uint64_t DstSVOff) {
5554 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5556 // If not DWORD aligned or size is more than the threshold, call the library.
5557 // The libc version is likely to be faster for these cases. It can use the
5558 // address value and run time information about the CPU.
5559 if ((Align & 3) != 0 ||
5561 ConstantSize->getZExtValue() >
5562 getSubtarget()->getMaxInlineSizeThreshold()) {
5563 SDValue InFlag(0, 0);
5565 // Check to see if there is a specialized entry-point for memory zeroing.
5566 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5568 if (const char *bzeroEntry = V &&
5569 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5570 MVT IntPtr = getPointerTy();
5571 const Type *IntPtrTy = TD->getIntPtrType();
5572 TargetLowering::ArgListTy Args;
5573 TargetLowering::ArgListEntry Entry;
5575 Entry.Ty = IntPtrTy;
5576 Args.push_back(Entry);
5578 Args.push_back(Entry);
5579 std::pair<SDValue,SDValue> CallResult =
5580 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5581 CallingConv::C, false,
5582 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5583 return CallResult.second;
5586 // Otherwise have the target-independent code call memset.
5590 uint64_t SizeVal = ConstantSize->getZExtValue();
5591 SDValue InFlag(0, 0);
5594 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5595 unsigned BytesLeft = 0;
5596 bool TwoRepStos = false;
5599 uint64_t Val = ValC->getZExtValue() & 255;
5601 // If the value is a constant, then we can potentially use larger sets.
5602 switch (Align & 3) {
5603 case 2: // WORD aligned
5606 Val = (Val << 8) | Val;
5608 case 0: // DWORD aligned
5611 Val = (Val << 8) | Val;
5612 Val = (Val << 16) | Val;
5613 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5616 Val = (Val << 32) | Val;
5619 default: // Byte aligned
5622 Count = DAG.getIntPtrConstant(SizeVal);
5626 if (AVT.bitsGT(MVT::i8)) {
5627 unsigned UBytes = AVT.getSizeInBits() / 8;
5628 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5629 BytesLeft = SizeVal % UBytes;
5632 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5634 InFlag = Chain.getValue(1);
5637 Count = DAG.getIntPtrConstant(SizeVal);
5638 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5639 InFlag = Chain.getValue(1);
5642 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5645 InFlag = Chain.getValue(1);
5646 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5649 InFlag = Chain.getValue(1);
5651 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5652 SmallVector<SDValue, 8> Ops;
5653 Ops.push_back(Chain);
5654 Ops.push_back(DAG.getValueType(AVT));
5655 Ops.push_back(InFlag);
5656 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5659 InFlag = Chain.getValue(1);
5661 MVT CVT = Count.getValueType();
5662 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5663 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5664 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5667 InFlag = Chain.getValue(1);
5668 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5670 Ops.push_back(Chain);
5671 Ops.push_back(DAG.getValueType(MVT::i8));
5672 Ops.push_back(InFlag);
5673 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5674 } else if (BytesLeft) {
5675 // Handle the last 1 - 7 bytes.
5676 unsigned Offset = SizeVal - BytesLeft;
5677 MVT AddrVT = Dst.getValueType();
5678 MVT SizeVT = Size.getValueType();
5680 Chain = DAG.getMemset(Chain, dl,
5681 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5682 DAG.getConstant(Offset, AddrVT)),
5684 DAG.getConstant(BytesLeft, SizeVT),
5685 Align, DstSV, DstSVOff + Offset);
5688 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5693 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5694 SDValue Chain, SDValue Dst, SDValue Src,
5695 SDValue Size, unsigned Align,
5697 const Value *DstSV, uint64_t DstSVOff,
5698 const Value *SrcSV, uint64_t SrcSVOff) {
5699 // This requires the copy size to be a constant, preferrably
5700 // within a subtarget-specific limit.
5701 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5704 uint64_t SizeVal = ConstantSize->getZExtValue();
5705 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5708 /// If not DWORD aligned, call the library.
5709 if ((Align & 3) != 0)
5714 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5717 unsigned UBytes = AVT.getSizeInBits() / 8;
5718 unsigned CountVal = SizeVal / UBytes;
5719 SDValue Count = DAG.getIntPtrConstant(CountVal);
5720 unsigned BytesLeft = SizeVal % UBytes;
5722 SDValue InFlag(0, 0);
5723 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5726 InFlag = Chain.getValue(1);
5727 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5730 InFlag = Chain.getValue(1);
5731 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5734 InFlag = Chain.getValue(1);
5736 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5737 SmallVector<SDValue, 8> Ops;
5738 Ops.push_back(Chain);
5739 Ops.push_back(DAG.getValueType(AVT));
5740 Ops.push_back(InFlag);
5741 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5743 SmallVector<SDValue, 4> Results;
5744 Results.push_back(RepMovs);
5746 // Handle the last 1 - 7 bytes.
5747 unsigned Offset = SizeVal - BytesLeft;
5748 MVT DstVT = Dst.getValueType();
5749 MVT SrcVT = Src.getValueType();
5750 MVT SizeVT = Size.getValueType();
5751 Results.push_back(DAG.getMemcpy(Chain, dl,
5752 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5753 DAG.getConstant(Offset, DstVT)),
5754 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5755 DAG.getConstant(Offset, SrcVT)),
5756 DAG.getConstant(BytesLeft, SizeVT),
5757 Align, AlwaysInline,
5758 DstSV, DstSVOff + Offset,
5759 SrcSV, SrcSVOff + Offset));
5762 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5763 &Results[0], Results.size());
5766 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5767 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5768 DebugLoc dl = Op.getDebugLoc();
5770 if (!Subtarget->is64Bit()) {
5771 // vastart just stores the address of the VarArgsFrameIndex slot into the
5772 // memory location argument.
5773 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5774 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
5778 // gp_offset (0 - 6 * 8)
5779 // fp_offset (48 - 48 + 8 * 16)
5780 // overflow_arg_area (point to parameters coming in memory).
5782 SmallVector<SDValue, 8> MemOps;
5783 SDValue FIN = Op.getOperand(1);
5785 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
5786 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5788 MemOps.push_back(Store);
5791 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5792 FIN, DAG.getIntPtrConstant(4));
5793 Store = DAG.getStore(Op.getOperand(0), dl,
5794 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5796 MemOps.push_back(Store);
5798 // Store ptr to overflow_arg_area
5799 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5800 FIN, DAG.getIntPtrConstant(4));
5801 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5802 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
5803 MemOps.push_back(Store);
5805 // Store ptr to reg_save_area.
5806 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5807 FIN, DAG.getIntPtrConstant(8));
5808 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5809 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
5810 MemOps.push_back(Store);
5811 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5812 &MemOps[0], MemOps.size());
5815 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5816 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5817 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5818 SDValue Chain = Op.getOperand(0);
5819 SDValue SrcPtr = Op.getOperand(1);
5820 SDValue SrcSV = Op.getOperand(2);
5822 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5827 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5828 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5829 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5830 SDValue Chain = Op.getOperand(0);
5831 SDValue DstPtr = Op.getOperand(1);
5832 SDValue SrcPtr = Op.getOperand(2);
5833 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5834 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5835 DebugLoc dl = Op.getDebugLoc();
5837 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
5838 DAG.getIntPtrConstant(24), 8, false,
5839 DstSV, 0, SrcSV, 0);
5843 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5844 DebugLoc dl = Op.getDebugLoc();
5845 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5847 default: return SDValue(); // Don't custom lower most intrinsics.
5848 // Comparison intrinsics.
5849 case Intrinsic::x86_sse_comieq_ss:
5850 case Intrinsic::x86_sse_comilt_ss:
5851 case Intrinsic::x86_sse_comile_ss:
5852 case Intrinsic::x86_sse_comigt_ss:
5853 case Intrinsic::x86_sse_comige_ss:
5854 case Intrinsic::x86_sse_comineq_ss:
5855 case Intrinsic::x86_sse_ucomieq_ss:
5856 case Intrinsic::x86_sse_ucomilt_ss:
5857 case Intrinsic::x86_sse_ucomile_ss:
5858 case Intrinsic::x86_sse_ucomigt_ss:
5859 case Intrinsic::x86_sse_ucomige_ss:
5860 case Intrinsic::x86_sse_ucomineq_ss:
5861 case Intrinsic::x86_sse2_comieq_sd:
5862 case Intrinsic::x86_sse2_comilt_sd:
5863 case Intrinsic::x86_sse2_comile_sd:
5864 case Intrinsic::x86_sse2_comigt_sd:
5865 case Intrinsic::x86_sse2_comige_sd:
5866 case Intrinsic::x86_sse2_comineq_sd:
5867 case Intrinsic::x86_sse2_ucomieq_sd:
5868 case Intrinsic::x86_sse2_ucomilt_sd:
5869 case Intrinsic::x86_sse2_ucomile_sd:
5870 case Intrinsic::x86_sse2_ucomigt_sd:
5871 case Intrinsic::x86_sse2_ucomige_sd:
5872 case Intrinsic::x86_sse2_ucomineq_sd: {
5874 ISD::CondCode CC = ISD::SETCC_INVALID;
5877 case Intrinsic::x86_sse_comieq_ss:
5878 case Intrinsic::x86_sse2_comieq_sd:
5882 case Intrinsic::x86_sse_comilt_ss:
5883 case Intrinsic::x86_sse2_comilt_sd:
5887 case Intrinsic::x86_sse_comile_ss:
5888 case Intrinsic::x86_sse2_comile_sd:
5892 case Intrinsic::x86_sse_comigt_ss:
5893 case Intrinsic::x86_sse2_comigt_sd:
5897 case Intrinsic::x86_sse_comige_ss:
5898 case Intrinsic::x86_sse2_comige_sd:
5902 case Intrinsic::x86_sse_comineq_ss:
5903 case Intrinsic::x86_sse2_comineq_sd:
5907 case Intrinsic::x86_sse_ucomieq_ss:
5908 case Intrinsic::x86_sse2_ucomieq_sd:
5909 Opc = X86ISD::UCOMI;
5912 case Intrinsic::x86_sse_ucomilt_ss:
5913 case Intrinsic::x86_sse2_ucomilt_sd:
5914 Opc = X86ISD::UCOMI;
5917 case Intrinsic::x86_sse_ucomile_ss:
5918 case Intrinsic::x86_sse2_ucomile_sd:
5919 Opc = X86ISD::UCOMI;
5922 case Intrinsic::x86_sse_ucomigt_ss:
5923 case Intrinsic::x86_sse2_ucomigt_sd:
5924 Opc = X86ISD::UCOMI;
5927 case Intrinsic::x86_sse_ucomige_ss:
5928 case Intrinsic::x86_sse2_ucomige_sd:
5929 Opc = X86ISD::UCOMI;
5932 case Intrinsic::x86_sse_ucomineq_ss:
5933 case Intrinsic::x86_sse2_ucomineq_sd:
5934 Opc = X86ISD::UCOMI;
5939 SDValue LHS = Op.getOperand(1);
5940 SDValue RHS = Op.getOperand(2);
5941 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
5942 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
5943 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5944 DAG.getConstant(X86CC, MVT::i8), Cond);
5945 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
5948 // Fix vector shift instructions where the last operand is a non-immediate
5950 case Intrinsic::x86_sse2_pslli_w:
5951 case Intrinsic::x86_sse2_pslli_d:
5952 case Intrinsic::x86_sse2_pslli_q:
5953 case Intrinsic::x86_sse2_psrli_w:
5954 case Intrinsic::x86_sse2_psrli_d:
5955 case Intrinsic::x86_sse2_psrli_q:
5956 case Intrinsic::x86_sse2_psrai_w:
5957 case Intrinsic::x86_sse2_psrai_d:
5958 case Intrinsic::x86_mmx_pslli_w:
5959 case Intrinsic::x86_mmx_pslli_d:
5960 case Intrinsic::x86_mmx_pslli_q:
5961 case Intrinsic::x86_mmx_psrli_w:
5962 case Intrinsic::x86_mmx_psrli_d:
5963 case Intrinsic::x86_mmx_psrli_q:
5964 case Intrinsic::x86_mmx_psrai_w:
5965 case Intrinsic::x86_mmx_psrai_d: {
5966 SDValue ShAmt = Op.getOperand(2);
5967 if (isa<ConstantSDNode>(ShAmt))
5970 unsigned NewIntNo = 0;
5971 MVT ShAmtVT = MVT::v4i32;
5973 case Intrinsic::x86_sse2_pslli_w:
5974 NewIntNo = Intrinsic::x86_sse2_psll_w;
5976 case Intrinsic::x86_sse2_pslli_d:
5977 NewIntNo = Intrinsic::x86_sse2_psll_d;
5979 case Intrinsic::x86_sse2_pslli_q:
5980 NewIntNo = Intrinsic::x86_sse2_psll_q;
5982 case Intrinsic::x86_sse2_psrli_w:
5983 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5985 case Intrinsic::x86_sse2_psrli_d:
5986 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5988 case Intrinsic::x86_sse2_psrli_q:
5989 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5991 case Intrinsic::x86_sse2_psrai_w:
5992 NewIntNo = Intrinsic::x86_sse2_psra_w;
5994 case Intrinsic::x86_sse2_psrai_d:
5995 NewIntNo = Intrinsic::x86_sse2_psra_d;
5998 ShAmtVT = MVT::v2i32;
6000 case Intrinsic::x86_mmx_pslli_w:
6001 NewIntNo = Intrinsic::x86_mmx_psll_w;
6003 case Intrinsic::x86_mmx_pslli_d:
6004 NewIntNo = Intrinsic::x86_mmx_psll_d;
6006 case Intrinsic::x86_mmx_pslli_q:
6007 NewIntNo = Intrinsic::x86_mmx_psll_q;
6009 case Intrinsic::x86_mmx_psrli_w:
6010 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6012 case Intrinsic::x86_mmx_psrli_d:
6013 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6015 case Intrinsic::x86_mmx_psrli_q:
6016 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6018 case Intrinsic::x86_mmx_psrai_w:
6019 NewIntNo = Intrinsic::x86_mmx_psra_w;
6021 case Intrinsic::x86_mmx_psrai_d:
6022 NewIntNo = Intrinsic::x86_mmx_psra_d;
6024 default: abort(); // Can't reach here.
6029 MVT VT = Op.getValueType();
6030 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6031 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6032 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6033 DAG.getConstant(NewIntNo, MVT::i32),
6034 Op.getOperand(1), ShAmt);
6039 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6040 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6041 DebugLoc dl = Op.getDebugLoc();
6044 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6046 DAG.getConstant(TD->getPointerSize(),
6047 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6048 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6049 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6054 // Just load the return address.
6055 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6056 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6057 RetAddrFI, NULL, 0);
6060 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6061 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6062 MFI->setFrameAddressIsTaken(true);
6063 MVT VT = Op.getValueType();
6064 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6065 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6066 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6067 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6069 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6073 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6074 SelectionDAG &DAG) {
6075 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6078 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6080 MachineFunction &MF = DAG.getMachineFunction();
6081 SDValue Chain = Op.getOperand(0);
6082 SDValue Offset = Op.getOperand(1);
6083 SDValue Handler = Op.getOperand(2);
6084 DebugLoc dl = Op.getDebugLoc();
6086 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6088 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6090 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6091 DAG.getIntPtrConstant(-TD->getPointerSize()));
6092 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6093 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6094 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6095 MF.getRegInfo().addLiveOut(StoreAddrReg);
6097 return DAG.getNode(X86ISD::EH_RETURN, dl,
6099 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6102 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6103 SelectionDAG &DAG) {
6104 SDValue Root = Op.getOperand(0);
6105 SDValue Trmp = Op.getOperand(1); // trampoline
6106 SDValue FPtr = Op.getOperand(2); // nested function
6107 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6108 DebugLoc dl = Op.getDebugLoc();
6110 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6112 const X86InstrInfo *TII =
6113 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6115 if (Subtarget->is64Bit()) {
6116 SDValue OutChains[6];
6118 // Large code-model.
6120 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6121 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6123 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6124 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6126 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6128 // Load the pointer to the nested function into R11.
6129 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6130 SDValue Addr = Trmp;
6131 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6134 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6135 DAG.getConstant(2, MVT::i64));
6136 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6138 // Load the 'nest' parameter value into R10.
6139 // R10 is specified in X86CallingConv.td
6140 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6141 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6142 DAG.getConstant(10, MVT::i64));
6143 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6144 Addr, TrmpAddr, 10);
6146 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6147 DAG.getConstant(12, MVT::i64));
6148 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6150 // Jump to the nested function.
6151 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6152 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6153 DAG.getConstant(20, MVT::i64));
6154 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6155 Addr, TrmpAddr, 20);
6157 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6158 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6159 DAG.getConstant(22, MVT::i64));
6160 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6164 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6165 return DAG.getMergeValues(Ops, 2, dl);
6167 const Function *Func =
6168 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6169 unsigned CC = Func->getCallingConv();
6174 assert(0 && "Unsupported calling convention");
6175 case CallingConv::C:
6176 case CallingConv::X86_StdCall: {
6177 // Pass 'nest' parameter in ECX.
6178 // Must be kept in sync with X86CallingConv.td
6181 // Check that ECX wasn't needed by an 'inreg' parameter.
6182 const FunctionType *FTy = Func->getFunctionType();
6183 const AttrListPtr &Attrs = Func->getAttributes();
6185 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6186 unsigned InRegCount = 0;
6189 for (FunctionType::param_iterator I = FTy->param_begin(),
6190 E = FTy->param_end(); I != E; ++I, ++Idx)
6191 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6192 // FIXME: should only count parameters that are lowered to integers.
6193 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6195 if (InRegCount > 2) {
6196 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6202 case CallingConv::X86_FastCall:
6203 case CallingConv::Fast:
6204 // Pass 'nest' parameter in EAX.
6205 // Must be kept in sync with X86CallingConv.td
6210 SDValue OutChains[4];
6213 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6214 DAG.getConstant(10, MVT::i32));
6215 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6217 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6218 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6219 OutChains[0] = DAG.getStore(Root, dl,
6220 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6223 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6224 DAG.getConstant(1, MVT::i32));
6225 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6227 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6228 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6229 DAG.getConstant(5, MVT::i32));
6230 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6231 TrmpAddr, 5, false, 1);
6233 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6234 DAG.getConstant(6, MVT::i32));
6235 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6238 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6239 return DAG.getMergeValues(Ops, 2, dl);
6243 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6245 The rounding mode is in bits 11:10 of FPSR, and has the following
6252 FLT_ROUNDS, on the other hand, expects the following:
6259 To perform the conversion, we do:
6260 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6263 MachineFunction &MF = DAG.getMachineFunction();
6264 const TargetMachine &TM = MF.getTarget();
6265 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6266 unsigned StackAlignment = TFI.getStackAlignment();
6267 MVT VT = Op.getValueType();
6268 DebugLoc dl = Op.getDebugLoc();
6270 // Save FP Control Word to stack slot
6271 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6272 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6274 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6275 DAG.getEntryNode(), StackSlot);
6277 // Load FP Control Word from stack slot
6278 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6280 // Transform as necessary
6282 DAG.getNode(ISD::SRL, dl, MVT::i16,
6283 DAG.getNode(ISD::AND, dl, MVT::i16,
6284 CWD, DAG.getConstant(0x800, MVT::i16)),
6285 DAG.getConstant(11, MVT::i8));
6287 DAG.getNode(ISD::SRL, dl, MVT::i16,
6288 DAG.getNode(ISD::AND, dl, MVT::i16,
6289 CWD, DAG.getConstant(0x400, MVT::i16)),
6290 DAG.getConstant(9, MVT::i8));
6293 DAG.getNode(ISD::AND, dl, MVT::i16,
6294 DAG.getNode(ISD::ADD, dl, MVT::i16,
6295 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6296 DAG.getConstant(1, MVT::i16)),
6297 DAG.getConstant(3, MVT::i16));
6300 return DAG.getNode((VT.getSizeInBits() < 16 ?
6301 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6304 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6305 MVT VT = Op.getValueType();
6307 unsigned NumBits = VT.getSizeInBits();
6308 DebugLoc dl = Op.getDebugLoc();
6310 Op = Op.getOperand(0);
6311 if (VT == MVT::i8) {
6312 // Zero extend to i32 since there is not an i8 bsr.
6314 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6317 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6318 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6319 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6321 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6322 SmallVector<SDValue, 4> Ops;
6324 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6325 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6326 Ops.push_back(Op.getValue(1));
6327 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6329 // Finally xor with NumBits-1.
6330 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6333 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6337 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6338 MVT VT = Op.getValueType();
6340 unsigned NumBits = VT.getSizeInBits();
6341 DebugLoc dl = Op.getDebugLoc();
6343 Op = Op.getOperand(0);
6344 if (VT == MVT::i8) {
6346 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6349 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6350 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6351 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6353 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6354 SmallVector<SDValue, 4> Ops;
6356 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6357 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6358 Ops.push_back(Op.getValue(1));
6359 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6362 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6366 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6367 MVT VT = Op.getValueType();
6368 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6369 DebugLoc dl = Op.getDebugLoc();
6371 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6372 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6373 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6374 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6375 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6377 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6378 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6379 // return AloBlo + AloBhi + AhiBlo;
6381 SDValue A = Op.getOperand(0);
6382 SDValue B = Op.getOperand(1);
6384 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6385 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6386 A, DAG.getConstant(32, MVT::i32));
6387 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6388 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6389 B, DAG.getConstant(32, MVT::i32));
6390 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6391 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6393 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6394 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6396 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6397 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6399 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6400 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6401 AloBhi, DAG.getConstant(32, MVT::i32));
6402 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6403 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6404 AhiBlo, DAG.getConstant(32, MVT::i32));
6405 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6406 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6411 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6412 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6413 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6414 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6415 // has only one use.
6416 SDNode *N = Op.getNode();
6417 SDValue LHS = N->getOperand(0);
6418 SDValue RHS = N->getOperand(1);
6419 unsigned BaseOp = 0;
6421 DebugLoc dl = Op.getDebugLoc();
6423 switch (Op.getOpcode()) {
6424 default: assert(0 && "Unknown ovf instruction!");
6426 // A subtract of one will be selected as a INC. Note that INC doesn't
6427 // set CF, so we can't do this for UADDO.
6428 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6429 if (C->getAPIntValue() == 1) {
6430 BaseOp = X86ISD::INC;
6434 BaseOp = X86ISD::ADD;
6438 BaseOp = X86ISD::ADD;
6442 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6443 // set CF, so we can't do this for USUBO.
6444 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6445 if (C->getAPIntValue() == 1) {
6446 BaseOp = X86ISD::DEC;
6450 BaseOp = X86ISD::SUB;
6454 BaseOp = X86ISD::SUB;
6458 BaseOp = X86ISD::SMUL;
6462 BaseOp = X86ISD::UMUL;
6467 // Also sets EFLAGS.
6468 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6469 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6472 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6473 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6475 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6479 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6480 MVT T = Op.getValueType();
6481 DebugLoc dl = Op.getDebugLoc();
6484 switch(T.getSimpleVT()) {
6486 assert(false && "Invalid value type!");
6487 case MVT::i8: Reg = X86::AL; size = 1; break;
6488 case MVT::i16: Reg = X86::AX; size = 2; break;
6489 case MVT::i32: Reg = X86::EAX; size = 4; break;
6491 assert(Subtarget->is64Bit() && "Node not type legal!");
6492 Reg = X86::RAX; size = 8;
6495 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6496 Op.getOperand(2), SDValue());
6497 SDValue Ops[] = { cpIn.getValue(0),
6500 DAG.getTargetConstant(size, MVT::i8),
6502 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6503 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6505 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6509 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6510 SelectionDAG &DAG) {
6511 assert(Subtarget->is64Bit() && "Result not type legalized?");
6512 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6513 SDValue TheChain = Op.getOperand(0);
6514 DebugLoc dl = Op.getDebugLoc();
6515 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6516 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6517 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6519 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6520 DAG.getConstant(32, MVT::i8));
6522 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6525 return DAG.getMergeValues(Ops, 2, dl);
6528 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6529 SDNode *Node = Op.getNode();
6530 DebugLoc dl = Node->getDebugLoc();
6531 MVT T = Node->getValueType(0);
6532 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6533 DAG.getConstant(0, T), Node->getOperand(2));
6534 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6535 cast<AtomicSDNode>(Node)->getMemoryVT(),
6536 Node->getOperand(0),
6537 Node->getOperand(1), negOp,
6538 cast<AtomicSDNode>(Node)->getSrcValue(),
6539 cast<AtomicSDNode>(Node)->getAlignment());
6542 /// LowerOperation - Provide custom lowering hooks for some operations.
6544 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6545 switch (Op.getOpcode()) {
6546 default: assert(0 && "Should not custom lower this!");
6547 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6548 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6549 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6550 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6551 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6552 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6553 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6554 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6555 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6556 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6557 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6558 case ISD::SHL_PARTS:
6559 case ISD::SRA_PARTS:
6560 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6561 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6562 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6563 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6564 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
6565 case ISD::FABS: return LowerFABS(Op, DAG);
6566 case ISD::FNEG: return LowerFNEG(Op, DAG);
6567 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6568 case ISD::SETCC: return LowerSETCC(Op, DAG);
6569 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6570 case ISD::SELECT: return LowerSELECT(Op, DAG);
6571 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6572 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6573 case ISD::CALL: return LowerCALL(Op, DAG);
6574 case ISD::RET: return LowerRET(Op, DAG);
6575 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6576 case ISD::VASTART: return LowerVASTART(Op, DAG);
6577 case ISD::VAARG: return LowerVAARG(Op, DAG);
6578 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6579 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6580 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6581 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6582 case ISD::FRAME_TO_ARGS_OFFSET:
6583 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6584 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6585 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6586 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6587 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6588 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6589 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6590 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6596 case ISD::UMULO: return LowerXALUO(Op, DAG);
6597 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6601 void X86TargetLowering::
6602 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6603 SelectionDAG &DAG, unsigned NewOp) {
6604 MVT T = Node->getValueType(0);
6605 DebugLoc dl = Node->getDebugLoc();
6606 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6608 SDValue Chain = Node->getOperand(0);
6609 SDValue In1 = Node->getOperand(1);
6610 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6611 Node->getOperand(2), DAG.getIntPtrConstant(0));
6612 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6613 Node->getOperand(2), DAG.getIntPtrConstant(1));
6614 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6615 // have a MemOperand. Pass the info through as a normal operand.
6616 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6617 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6618 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6619 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6620 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6621 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6622 Results.push_back(Result.getValue(2));
6625 /// ReplaceNodeResults - Replace a node with an illegal result type
6626 /// with a new node built out of custom code.
6627 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6628 SmallVectorImpl<SDValue>&Results,
6629 SelectionDAG &DAG) {
6630 DebugLoc dl = N->getDebugLoc();
6631 switch (N->getOpcode()) {
6633 assert(false && "Do not know how to custom type legalize this operation!");
6635 case ISD::FP_TO_SINT: {
6636 std::pair<SDValue,SDValue> Vals =
6637 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
6638 SDValue FIST = Vals.first, StackSlot = Vals.second;
6639 if (FIST.getNode() != 0) {
6640 MVT VT = N->getValueType(0);
6641 // Return a load from the stack slot.
6642 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6646 case ISD::READCYCLECOUNTER: {
6647 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6648 SDValue TheChain = N->getOperand(0);
6649 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6650 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6652 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6654 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6655 SDValue Ops[] = { eax, edx };
6656 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6657 Results.push_back(edx.getValue(1));
6660 case ISD::ATOMIC_CMP_SWAP: {
6661 MVT T = N->getValueType(0);
6662 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6663 SDValue cpInL, cpInH;
6664 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6665 DAG.getConstant(0, MVT::i32));
6666 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6667 DAG.getConstant(1, MVT::i32));
6668 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6669 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6671 SDValue swapInL, swapInH;
6672 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6673 DAG.getConstant(0, MVT::i32));
6674 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6675 DAG.getConstant(1, MVT::i32));
6676 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6678 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6679 swapInL.getValue(1));
6680 SDValue Ops[] = { swapInH.getValue(0),
6682 swapInH.getValue(1) };
6683 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6684 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6685 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6686 MVT::i32, Result.getValue(1));
6687 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6688 MVT::i32, cpOutL.getValue(2));
6689 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6690 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6691 Results.push_back(cpOutH.getValue(1));
6694 case ISD::ATOMIC_LOAD_ADD:
6695 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6697 case ISD::ATOMIC_LOAD_AND:
6698 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6700 case ISD::ATOMIC_LOAD_NAND:
6701 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6703 case ISD::ATOMIC_LOAD_OR:
6704 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6706 case ISD::ATOMIC_LOAD_SUB:
6707 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6709 case ISD::ATOMIC_LOAD_XOR:
6710 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6712 case ISD::ATOMIC_SWAP:
6713 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6718 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6720 default: return NULL;
6721 case X86ISD::BSF: return "X86ISD::BSF";
6722 case X86ISD::BSR: return "X86ISD::BSR";
6723 case X86ISD::SHLD: return "X86ISD::SHLD";
6724 case X86ISD::SHRD: return "X86ISD::SHRD";
6725 case X86ISD::FAND: return "X86ISD::FAND";
6726 case X86ISD::FOR: return "X86ISD::FOR";
6727 case X86ISD::FXOR: return "X86ISD::FXOR";
6728 case X86ISD::FSRL: return "X86ISD::FSRL";
6729 case X86ISD::FILD: return "X86ISD::FILD";
6730 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6731 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6732 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6733 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6734 case X86ISD::FLD: return "X86ISD::FLD";
6735 case X86ISD::FST: return "X86ISD::FST";
6736 case X86ISD::CALL: return "X86ISD::CALL";
6737 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6738 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6739 case X86ISD::BT: return "X86ISD::BT";
6740 case X86ISD::CMP: return "X86ISD::CMP";
6741 case X86ISD::COMI: return "X86ISD::COMI";
6742 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6743 case X86ISD::SETCC: return "X86ISD::SETCC";
6744 case X86ISD::CMOV: return "X86ISD::CMOV";
6745 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6746 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6747 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6748 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6749 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6750 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6751 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6752 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6753 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6754 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6755 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6756 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
6757 case X86ISD::FMAX: return "X86ISD::FMAX";
6758 case X86ISD::FMIN: return "X86ISD::FMIN";
6759 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6760 case X86ISD::FRCP: return "X86ISD::FRCP";
6761 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6762 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
6763 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6764 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6765 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6766 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6767 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6768 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6769 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6770 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6771 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6772 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6773 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6774 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6775 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6776 case X86ISD::VSHL: return "X86ISD::VSHL";
6777 case X86ISD::VSRL: return "X86ISD::VSRL";
6778 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6779 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6780 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6781 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6782 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6783 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6784 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6785 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6786 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6787 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6788 case X86ISD::ADD: return "X86ISD::ADD";
6789 case X86ISD::SUB: return "X86ISD::SUB";
6790 case X86ISD::SMUL: return "X86ISD::SMUL";
6791 case X86ISD::UMUL: return "X86ISD::UMUL";
6792 case X86ISD::INC: return "X86ISD::INC";
6793 case X86ISD::DEC: return "X86ISD::DEC";
6794 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
6798 // isLegalAddressingMode - Return true if the addressing mode represented
6799 // by AM is legal for this target, for a load/store of the specified type.
6800 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6801 const Type *Ty) const {
6802 // X86 supports extremely general addressing modes.
6804 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6805 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6809 // We can only fold this if we don't need an extra load.
6810 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6812 // If BaseGV requires a register, we cannot also have a BaseReg.
6813 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6817 // X86-64 only supports addr of globals in small code model.
6818 if (Subtarget->is64Bit()) {
6819 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6821 // If lower 4G is not available, then we must use rip-relative addressing.
6822 if (AM.BaseOffs || AM.Scale > 1)
6833 // These scales always work.
6838 // These scales are formed with basereg+scalereg. Only accept if there is
6843 default: // Other stuff never works.
6851 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6852 if (!Ty1->isInteger() || !Ty2->isInteger())
6854 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6855 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6856 if (NumBits1 <= NumBits2)
6858 return Subtarget->is64Bit() || NumBits1 < 64;
6861 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6862 if (!VT1.isInteger() || !VT2.isInteger())
6864 unsigned NumBits1 = VT1.getSizeInBits();
6865 unsigned NumBits2 = VT2.getSizeInBits();
6866 if (NumBits1 <= NumBits2)
6868 return Subtarget->is64Bit() || NumBits1 < 64;
6871 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
6872 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6873 return Ty1 == Type::Int32Ty && Ty2 == Type::Int64Ty && Subtarget->is64Bit();
6876 bool X86TargetLowering::isZExtFree(MVT VT1, MVT VT2) const {
6877 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6878 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
6881 bool X86TargetLowering::isNarrowingProfitable(MVT VT1, MVT VT2) const {
6882 // i16 instructions are longer (0x66 prefix) and potentially slower.
6883 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
6886 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6887 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6888 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6889 /// are assumed to be legal.
6891 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6893 // Only do shuffles on 128-bit vector types for now.
6894 if (VT.getSizeInBits() == 64)
6897 // FIXME: pshufb, blends, palignr, shifts.
6898 return (VT.getVectorNumElements() == 2 ||
6899 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6900 isMOVLMask(M, VT) ||
6901 isSHUFPMask(M, VT) ||
6902 isPSHUFDMask(M, VT) ||
6903 isPSHUFHWMask(M, VT) ||
6904 isPSHUFLWMask(M, VT) ||
6905 isUNPCKLMask(M, VT) ||
6906 isUNPCKHMask(M, VT) ||
6907 isUNPCKL_v_undef_Mask(M, VT) ||
6908 isUNPCKH_v_undef_Mask(M, VT));
6912 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
6914 unsigned NumElts = VT.getVectorNumElements();
6915 // FIXME: This collection of masks seems suspect.
6918 if (NumElts == 4 && VT.getSizeInBits() == 128) {
6919 return (isMOVLMask(Mask, VT) ||
6920 isCommutedMOVLMask(Mask, VT, true) ||
6921 isSHUFPMask(Mask, VT) ||
6922 isCommutedSHUFPMask(Mask, VT));
6927 //===----------------------------------------------------------------------===//
6928 // X86 Scheduler Hooks
6929 //===----------------------------------------------------------------------===//
6931 // private utility function
6933 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6934 MachineBasicBlock *MBB,
6942 TargetRegisterClass *RC,
6943 bool invSrc) const {
6944 // For the atomic bitwise operator, we generate
6947 // ld t1 = [bitinstr.addr]
6948 // op t2 = t1, [bitinstr.val]
6950 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6952 // fallthrough -->nextMBB
6953 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6954 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6955 MachineFunction::iterator MBBIter = MBB;
6958 /// First build the CFG
6959 MachineFunction *F = MBB->getParent();
6960 MachineBasicBlock *thisMBB = MBB;
6961 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6962 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6963 F->insert(MBBIter, newMBB);
6964 F->insert(MBBIter, nextMBB);
6966 // Move all successors to thisMBB to nextMBB
6967 nextMBB->transferSuccessors(thisMBB);
6969 // Update thisMBB to fall through to newMBB
6970 thisMBB->addSuccessor(newMBB);
6972 // newMBB jumps to itself and fall through to nextMBB
6973 newMBB->addSuccessor(nextMBB);
6974 newMBB->addSuccessor(newMBB);
6976 // Insert instructions into newMBB based on incoming instruction
6977 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
6978 "unexpected number of operands");
6979 DebugLoc dl = bInstr->getDebugLoc();
6980 MachineOperand& destOper = bInstr->getOperand(0);
6981 MachineOperand* argOpers[2 + X86AddrNumOperands];
6982 int numArgs = bInstr->getNumOperands() - 1;
6983 for (int i=0; i < numArgs; ++i)
6984 argOpers[i] = &bInstr->getOperand(i+1);
6986 // x86 address has 4 operands: base, index, scale, and displacement
6987 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
6988 int valArgIndx = lastAddrIndx + 1;
6990 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6991 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
6992 for (int i=0; i <= lastAddrIndx; ++i)
6993 (*MIB).addOperand(*argOpers[i]);
6995 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6997 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7002 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7003 assert((argOpers[valArgIndx]->isReg() ||
7004 argOpers[valArgIndx]->isImm()) &&
7006 if (argOpers[valArgIndx]->isReg())
7007 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7009 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7011 (*MIB).addOperand(*argOpers[valArgIndx]);
7013 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7016 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7017 for (int i=0; i <= lastAddrIndx; ++i)
7018 (*MIB).addOperand(*argOpers[i]);
7020 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7021 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7023 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7027 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7029 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7033 // private utility function: 64 bit atomics on 32 bit host.
7035 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7036 MachineBasicBlock *MBB,
7041 bool invSrc) const {
7042 // For the atomic bitwise operator, we generate
7043 // thisMBB (instructions are in pairs, except cmpxchg8b)
7044 // ld t1,t2 = [bitinstr.addr]
7046 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7047 // op t5, t6 <- out1, out2, [bitinstr.val]
7048 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7049 // mov ECX, EBX <- t5, t6
7050 // mov EAX, EDX <- t1, t2
7051 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7052 // mov t3, t4 <- EAX, EDX
7054 // result in out1, out2
7055 // fallthrough -->nextMBB
7057 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7058 const unsigned LoadOpc = X86::MOV32rm;
7059 const unsigned copyOpc = X86::MOV32rr;
7060 const unsigned NotOpc = X86::NOT32r;
7061 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7062 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7063 MachineFunction::iterator MBBIter = MBB;
7066 /// First build the CFG
7067 MachineFunction *F = MBB->getParent();
7068 MachineBasicBlock *thisMBB = MBB;
7069 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7070 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7071 F->insert(MBBIter, newMBB);
7072 F->insert(MBBIter, nextMBB);
7074 // Move all successors to thisMBB to nextMBB
7075 nextMBB->transferSuccessors(thisMBB);
7077 // Update thisMBB to fall through to newMBB
7078 thisMBB->addSuccessor(newMBB);
7080 // newMBB jumps to itself and fall through to nextMBB
7081 newMBB->addSuccessor(nextMBB);
7082 newMBB->addSuccessor(newMBB);
7084 DebugLoc dl = bInstr->getDebugLoc();
7085 // Insert instructions into newMBB based on incoming instruction
7086 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7087 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7088 "unexpected number of operands");
7089 MachineOperand& dest1Oper = bInstr->getOperand(0);
7090 MachineOperand& dest2Oper = bInstr->getOperand(1);
7091 MachineOperand* argOpers[2 + X86AddrNumOperands];
7092 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7093 argOpers[i] = &bInstr->getOperand(i+2);
7095 // x86 address has 4 operands: base, index, scale, and displacement
7096 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7098 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7099 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7100 for (int i=0; i <= lastAddrIndx; ++i)
7101 (*MIB).addOperand(*argOpers[i]);
7102 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7103 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7104 // add 4 to displacement.
7105 for (int i=0; i <= lastAddrIndx-2; ++i)
7106 (*MIB).addOperand(*argOpers[i]);
7107 MachineOperand newOp3 = *(argOpers[3]);
7109 newOp3.setImm(newOp3.getImm()+4);
7111 newOp3.setOffset(newOp3.getOffset()+4);
7112 (*MIB).addOperand(newOp3);
7113 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7115 // t3/4 are defined later, at the bottom of the loop
7116 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7117 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7118 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7119 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7120 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7121 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7123 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7124 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7126 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7127 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7133 int valArgIndx = lastAddrIndx + 1;
7134 assert((argOpers[valArgIndx]->isReg() ||
7135 argOpers[valArgIndx]->isImm()) &&
7137 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7138 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7139 if (argOpers[valArgIndx]->isReg())
7140 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7142 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7143 if (regOpcL != X86::MOV32rr)
7145 (*MIB).addOperand(*argOpers[valArgIndx]);
7146 assert(argOpers[valArgIndx + 1]->isReg() ==
7147 argOpers[valArgIndx]->isReg());
7148 assert(argOpers[valArgIndx + 1]->isImm() ==
7149 argOpers[valArgIndx]->isImm());
7150 if (argOpers[valArgIndx + 1]->isReg())
7151 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7153 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7154 if (regOpcH != X86::MOV32rr)
7156 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7158 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7160 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7163 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7165 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7168 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7169 for (int i=0; i <= lastAddrIndx; ++i)
7170 (*MIB).addOperand(*argOpers[i]);
7172 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7173 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7175 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7176 MIB.addReg(X86::EAX);
7177 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7178 MIB.addReg(X86::EDX);
7181 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7183 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7187 // private utility function
7189 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7190 MachineBasicBlock *MBB,
7191 unsigned cmovOpc) const {
7192 // For the atomic min/max operator, we generate
7195 // ld t1 = [min/max.addr]
7196 // mov t2 = [min/max.val]
7198 // cmov[cond] t2 = t1
7200 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7202 // fallthrough -->nextMBB
7204 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7205 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7206 MachineFunction::iterator MBBIter = MBB;
7209 /// First build the CFG
7210 MachineFunction *F = MBB->getParent();
7211 MachineBasicBlock *thisMBB = MBB;
7212 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7213 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7214 F->insert(MBBIter, newMBB);
7215 F->insert(MBBIter, nextMBB);
7217 // Move all successors to thisMBB to nextMBB
7218 nextMBB->transferSuccessors(thisMBB);
7220 // Update thisMBB to fall through to newMBB
7221 thisMBB->addSuccessor(newMBB);
7223 // newMBB jumps to newMBB and fall through to nextMBB
7224 newMBB->addSuccessor(nextMBB);
7225 newMBB->addSuccessor(newMBB);
7227 DebugLoc dl = mInstr->getDebugLoc();
7228 // Insert instructions into newMBB based on incoming instruction
7229 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7230 "unexpected number of operands");
7231 MachineOperand& destOper = mInstr->getOperand(0);
7232 MachineOperand* argOpers[2 + X86AddrNumOperands];
7233 int numArgs = mInstr->getNumOperands() - 1;
7234 for (int i=0; i < numArgs; ++i)
7235 argOpers[i] = &mInstr->getOperand(i+1);
7237 // x86 address has 4 operands: base, index, scale, and displacement
7238 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7239 int valArgIndx = lastAddrIndx + 1;
7241 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7242 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7243 for (int i=0; i <= lastAddrIndx; ++i)
7244 (*MIB).addOperand(*argOpers[i]);
7246 // We only support register and immediate values
7247 assert((argOpers[valArgIndx]->isReg() ||
7248 argOpers[valArgIndx]->isImm()) &&
7251 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7252 if (argOpers[valArgIndx]->isReg())
7253 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7255 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7256 (*MIB).addOperand(*argOpers[valArgIndx]);
7258 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7261 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7266 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7267 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7271 // Cmp and exchange if none has modified the memory location
7272 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7273 for (int i=0; i <= lastAddrIndx; ++i)
7274 (*MIB).addOperand(*argOpers[i]);
7276 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7277 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7279 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7280 MIB.addReg(X86::EAX);
7283 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7285 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7291 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7292 MachineBasicBlock *BB) const {
7293 DebugLoc dl = MI->getDebugLoc();
7294 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7295 switch (MI->getOpcode()) {
7296 default: assert(false && "Unexpected instr type to insert");
7297 case X86::CMOV_V1I64:
7298 case X86::CMOV_FR32:
7299 case X86::CMOV_FR64:
7300 case X86::CMOV_V4F32:
7301 case X86::CMOV_V2F64:
7302 case X86::CMOV_V2I64: {
7303 // To "insert" a SELECT_CC instruction, we actually have to insert the
7304 // diamond control-flow pattern. The incoming instruction knows the
7305 // destination vreg to set, the condition code register to branch on, the
7306 // true/false values to select between, and a branch opcode to use.
7307 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7308 MachineFunction::iterator It = BB;
7314 // cmpTY ccX, r1, r2
7316 // fallthrough --> copy0MBB
7317 MachineBasicBlock *thisMBB = BB;
7318 MachineFunction *F = BB->getParent();
7319 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7320 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7322 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7323 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7324 F->insert(It, copy0MBB);
7325 F->insert(It, sinkMBB);
7326 // Update machine-CFG edges by transferring all successors of the current
7327 // block to the new block which will contain the Phi node for the select.
7328 sinkMBB->transferSuccessors(BB);
7330 // Add the true and fallthrough blocks as its successors.
7331 BB->addSuccessor(copy0MBB);
7332 BB->addSuccessor(sinkMBB);
7335 // %FalseValue = ...
7336 // # fallthrough to sinkMBB
7339 // Update machine-CFG edges
7340 BB->addSuccessor(sinkMBB);
7343 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7346 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7347 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7348 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7350 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7354 case X86::FP32_TO_INT16_IN_MEM:
7355 case X86::FP32_TO_INT32_IN_MEM:
7356 case X86::FP32_TO_INT64_IN_MEM:
7357 case X86::FP64_TO_INT16_IN_MEM:
7358 case X86::FP64_TO_INT32_IN_MEM:
7359 case X86::FP64_TO_INT64_IN_MEM:
7360 case X86::FP80_TO_INT16_IN_MEM:
7361 case X86::FP80_TO_INT32_IN_MEM:
7362 case X86::FP80_TO_INT64_IN_MEM: {
7363 // Change the floating point control register to use "round towards zero"
7364 // mode when truncating to an integer value.
7365 MachineFunction *F = BB->getParent();
7366 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7367 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7369 // Load the old value of the high byte of the control word...
7371 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7372 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7375 // Set the high part to be round to zero...
7376 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7379 // Reload the modified control word now...
7380 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7382 // Restore the memory image of control word to original value
7383 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7386 // Get the X86 opcode to use.
7388 switch (MI->getOpcode()) {
7389 default: assert(0 && "illegal opcode!");
7390 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7391 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7392 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7393 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7394 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7395 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7396 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7397 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7398 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7402 MachineOperand &Op = MI->getOperand(0);
7404 AM.BaseType = X86AddressMode::RegBase;
7405 AM.Base.Reg = Op.getReg();
7407 AM.BaseType = X86AddressMode::FrameIndexBase;
7408 AM.Base.FrameIndex = Op.getIndex();
7410 Op = MI->getOperand(1);
7412 AM.Scale = Op.getImm();
7413 Op = MI->getOperand(2);
7415 AM.IndexReg = Op.getImm();
7416 Op = MI->getOperand(3);
7417 if (Op.isGlobal()) {
7418 AM.GV = Op.getGlobal();
7420 AM.Disp = Op.getImm();
7422 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7423 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7425 // Reload the original control word now.
7426 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7428 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7431 case X86::ATOMAND32:
7432 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7433 X86::AND32ri, X86::MOV32rm,
7434 X86::LCMPXCHG32, X86::MOV32rr,
7435 X86::NOT32r, X86::EAX,
7436 X86::GR32RegisterClass);
7438 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7439 X86::OR32ri, X86::MOV32rm,
7440 X86::LCMPXCHG32, X86::MOV32rr,
7441 X86::NOT32r, X86::EAX,
7442 X86::GR32RegisterClass);
7443 case X86::ATOMXOR32:
7444 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7445 X86::XOR32ri, X86::MOV32rm,
7446 X86::LCMPXCHG32, X86::MOV32rr,
7447 X86::NOT32r, X86::EAX,
7448 X86::GR32RegisterClass);
7449 case X86::ATOMNAND32:
7450 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7451 X86::AND32ri, X86::MOV32rm,
7452 X86::LCMPXCHG32, X86::MOV32rr,
7453 X86::NOT32r, X86::EAX,
7454 X86::GR32RegisterClass, true);
7455 case X86::ATOMMIN32:
7456 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7457 case X86::ATOMMAX32:
7458 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7459 case X86::ATOMUMIN32:
7460 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7461 case X86::ATOMUMAX32:
7462 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7464 case X86::ATOMAND16:
7465 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7466 X86::AND16ri, X86::MOV16rm,
7467 X86::LCMPXCHG16, X86::MOV16rr,
7468 X86::NOT16r, X86::AX,
7469 X86::GR16RegisterClass);
7471 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7472 X86::OR16ri, X86::MOV16rm,
7473 X86::LCMPXCHG16, X86::MOV16rr,
7474 X86::NOT16r, X86::AX,
7475 X86::GR16RegisterClass);
7476 case X86::ATOMXOR16:
7477 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7478 X86::XOR16ri, X86::MOV16rm,
7479 X86::LCMPXCHG16, X86::MOV16rr,
7480 X86::NOT16r, X86::AX,
7481 X86::GR16RegisterClass);
7482 case X86::ATOMNAND16:
7483 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7484 X86::AND16ri, X86::MOV16rm,
7485 X86::LCMPXCHG16, X86::MOV16rr,
7486 X86::NOT16r, X86::AX,
7487 X86::GR16RegisterClass, true);
7488 case X86::ATOMMIN16:
7489 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7490 case X86::ATOMMAX16:
7491 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7492 case X86::ATOMUMIN16:
7493 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7494 case X86::ATOMUMAX16:
7495 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7498 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7499 X86::AND8ri, X86::MOV8rm,
7500 X86::LCMPXCHG8, X86::MOV8rr,
7501 X86::NOT8r, X86::AL,
7502 X86::GR8RegisterClass);
7504 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7505 X86::OR8ri, X86::MOV8rm,
7506 X86::LCMPXCHG8, X86::MOV8rr,
7507 X86::NOT8r, X86::AL,
7508 X86::GR8RegisterClass);
7510 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7511 X86::XOR8ri, X86::MOV8rm,
7512 X86::LCMPXCHG8, X86::MOV8rr,
7513 X86::NOT8r, X86::AL,
7514 X86::GR8RegisterClass);
7515 case X86::ATOMNAND8:
7516 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7517 X86::AND8ri, X86::MOV8rm,
7518 X86::LCMPXCHG8, X86::MOV8rr,
7519 X86::NOT8r, X86::AL,
7520 X86::GR8RegisterClass, true);
7521 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7522 // This group is for 64-bit host.
7523 case X86::ATOMAND64:
7524 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7525 X86::AND64ri32, X86::MOV64rm,
7526 X86::LCMPXCHG64, X86::MOV64rr,
7527 X86::NOT64r, X86::RAX,
7528 X86::GR64RegisterClass);
7530 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7531 X86::OR64ri32, X86::MOV64rm,
7532 X86::LCMPXCHG64, X86::MOV64rr,
7533 X86::NOT64r, X86::RAX,
7534 X86::GR64RegisterClass);
7535 case X86::ATOMXOR64:
7536 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7537 X86::XOR64ri32, X86::MOV64rm,
7538 X86::LCMPXCHG64, X86::MOV64rr,
7539 X86::NOT64r, X86::RAX,
7540 X86::GR64RegisterClass);
7541 case X86::ATOMNAND64:
7542 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7543 X86::AND64ri32, X86::MOV64rm,
7544 X86::LCMPXCHG64, X86::MOV64rr,
7545 X86::NOT64r, X86::RAX,
7546 X86::GR64RegisterClass, true);
7547 case X86::ATOMMIN64:
7548 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7549 case X86::ATOMMAX64:
7550 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7551 case X86::ATOMUMIN64:
7552 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7553 case X86::ATOMUMAX64:
7554 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7556 // This group does 64-bit operations on a 32-bit host.
7557 case X86::ATOMAND6432:
7558 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7559 X86::AND32rr, X86::AND32rr,
7560 X86::AND32ri, X86::AND32ri,
7562 case X86::ATOMOR6432:
7563 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7564 X86::OR32rr, X86::OR32rr,
7565 X86::OR32ri, X86::OR32ri,
7567 case X86::ATOMXOR6432:
7568 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7569 X86::XOR32rr, X86::XOR32rr,
7570 X86::XOR32ri, X86::XOR32ri,
7572 case X86::ATOMNAND6432:
7573 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7574 X86::AND32rr, X86::AND32rr,
7575 X86::AND32ri, X86::AND32ri,
7577 case X86::ATOMADD6432:
7578 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7579 X86::ADD32rr, X86::ADC32rr,
7580 X86::ADD32ri, X86::ADC32ri,
7582 case X86::ATOMSUB6432:
7583 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7584 X86::SUB32rr, X86::SBB32rr,
7585 X86::SUB32ri, X86::SBB32ri,
7587 case X86::ATOMSWAP6432:
7588 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7589 X86::MOV32rr, X86::MOV32rr,
7590 X86::MOV32ri, X86::MOV32ri,
7595 //===----------------------------------------------------------------------===//
7596 // X86 Optimization Hooks
7597 //===----------------------------------------------------------------------===//
7599 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7603 const SelectionDAG &DAG,
7604 unsigned Depth) const {
7605 unsigned Opc = Op.getOpcode();
7606 assert((Opc >= ISD::BUILTIN_OP_END ||
7607 Opc == ISD::INTRINSIC_WO_CHAIN ||
7608 Opc == ISD::INTRINSIC_W_CHAIN ||
7609 Opc == ISD::INTRINSIC_VOID) &&
7610 "Should use MaskedValueIsZero if you don't know whether Op"
7611 " is a target node!");
7613 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7622 // These nodes' second result is a boolean.
7623 if (Op.getResNo() == 0)
7627 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7628 Mask.getBitWidth() - 1);
7633 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7634 /// node is a GlobalAddress + offset.
7635 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7636 GlobalValue* &GA, int64_t &Offset) const{
7637 if (N->getOpcode() == X86ISD::Wrapper) {
7638 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7639 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7640 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7644 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7647 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7648 const TargetLowering &TLI) {
7651 if (TLI.isGAPlusOffset(Base, GV, Offset))
7652 return (GV->getAlignment() >= N && (Offset % N) == 0);
7653 // DAG combine handles the stack object case.
7657 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
7658 MVT EVT, SDNode *&Base,
7659 SelectionDAG &DAG, MachineFrameInfo *MFI,
7660 const TargetLowering &TLI) {
7662 for (unsigned i = 0; i < NumElems; ++i) {
7663 if (N->getMaskElt(i) < 0) {
7669 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7670 if (!Elt.getNode() ||
7671 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7674 Base = Elt.getNode();
7675 if (Base->getOpcode() == ISD::UNDEF)
7679 if (Elt.getOpcode() == ISD::UNDEF)
7682 LoadSDNode *LD = cast<LoadSDNode>(Elt);
7683 LoadSDNode *LDBase = cast<LoadSDNode>(Base);
7684 if (!TLI.isConsecutiveLoad(LD, LDBase, EVT.getSizeInBits()/8, i, MFI))
7690 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7691 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7692 /// if the load addresses are consecutive, non-overlapping, and in the right
7693 /// order. In the case of v2i64, it will see if it can rewrite the
7694 /// shuffle to be an appropriate build vector so it can take advantage of
7695 // performBuildVectorCombine.
7696 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7697 const TargetLowering &TLI) {
7698 DebugLoc dl = N->getDebugLoc();
7699 MVT VT = N->getValueType(0);
7700 MVT EVT = VT.getVectorElementType();
7701 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7702 unsigned NumElems = VT.getVectorNumElements();
7704 // For x86-32 machines, if we see an insert and then a shuffle in a v2i64
7705 // where the upper half is 0, it is advantageous to rewrite it as a build
7706 // vector of (0, val) so it can use movq.
7707 if (VT == MVT::v2i64) {
7709 In[0] = N->getOperand(0);
7710 In[1] = N->getOperand(1);
7711 int Idx0 = SVN->getMaskElt(0);
7712 int Idx1 = SVN->getMaskElt(1);
7713 // FIXME: can we take advantage of undef index?
7714 if (Idx0 >= 0 && Idx1 >= 0 &&
7715 In[Idx0/2].getOpcode() == ISD::INSERT_VECTOR_ELT &&
7716 In[Idx1/2].getOpcode() == ISD::BUILD_VECTOR) {
7717 ConstantSDNode* InsertVecIdx =
7718 dyn_cast<ConstantSDNode>(In[Idx0/2].getOperand(2));
7720 InsertVecIdx->getZExtValue() == (unsigned)(Idx0 % 2) &&
7721 isZeroNode(In[Idx1/2].getOperand(Idx1 % 2))) {
7722 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7723 In[Idx0/2].getOperand(1),
7724 In[Idx1/2].getOperand(Idx1 % 2));
7729 // Try to combine a vector_shuffle into a 128-bit load.
7730 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7731 SDNode *Base = NULL;
7732 if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, Base, DAG, MFI, TLI))
7735 LoadSDNode *LD = cast<LoadSDNode>(Base);
7736 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7737 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7738 LD->getSrcValue(), LD->getSrcValueOffset(),
7740 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7741 LD->getSrcValue(), LD->getSrcValueOffset(),
7742 LD->isVolatile(), LD->getAlignment());
7745 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7746 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7747 TargetLowering::DAGCombinerInfo &DCI,
7748 const X86Subtarget *Subtarget,
7749 const TargetLowering &TLI) {
7750 unsigned NumOps = N->getNumOperands();
7751 DebugLoc dl = N->getDebugLoc();
7753 // Ignore single operand BUILD_VECTOR.
7757 MVT VT = N->getValueType(0);
7758 MVT EVT = VT.getVectorElementType();
7760 // Before or during type legalization, we want to try and convert a
7761 // build_vector of an i64 load and a zero value into vzext_movl before the
7762 // legalizer can break it up.
7763 // FIXME: does the case below remove the need to do this?
7764 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) {
7765 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7768 // This must be an insertion into a zero vector.
7769 SDValue HighElt = N->getOperand(1);
7770 if (!isZeroNode(HighElt))
7773 // Value must be a load.
7774 SDNode *Base = N->getOperand(0).getNode();
7775 if (!isa<LoadSDNode>(Base)) {
7776 if (Base->getOpcode() != ISD::BIT_CONVERT)
7778 Base = Base->getOperand(0).getNode();
7779 if (!isa<LoadSDNode>(Base))
7783 // Transform it into VZEXT_LOAD addr.
7784 LoadSDNode *LD = cast<LoadSDNode>(Base);
7786 // Load must not be an extload.
7787 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7790 // Load type should legal type so we don't have to legalize it.
7791 if (!TLI.isTypeLegal(VT))
7794 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7795 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7796 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7797 TargetLowering::TargetLoweringOpt TLO(DAG);
7798 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
7799 DCI.CommitTargetLoweringOpt(TLO);
7803 // The type legalizer will have broken apart v2i64 build_vector created during
7804 // widening before the code which handles that case is run. Look for build
7805 // vector (load, load + 4, 0/undef, 0/undef)
7806 if (VT == MVT::v4i32 || VT == MVT::v4f32) {
7807 LoadSDNode *LD0 = dyn_cast<LoadSDNode>(N->getOperand(0));
7808 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(N->getOperand(1));
7811 if (LD0->getExtensionType() != ISD::NON_EXTLOAD ||
7812 LD1->getExtensionType() != ISD::NON_EXTLOAD)
7814 // Make sure the second elt is a consecutive load.
7815 if (!TLI.isConsecutiveLoad(LD1, LD0, EVT.getSizeInBits()/8, 1,
7816 DAG.getMachineFunction().getFrameInfo()))
7819 SDValue N2 = N->getOperand(2);
7820 SDValue N3 = N->getOperand(3);
7821 if (!isZeroNode(N2) && N2.getOpcode() != ISD::UNDEF)
7823 if (!isZeroNode(N3) && N3.getOpcode() != ISD::UNDEF)
7826 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
7827 SDValue Ops[] = { LD0->getChain(), LD0->getBasePtr() };
7828 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7829 TargetLowering::TargetLoweringOpt TLO(DAG);
7830 TLO.CombineTo(SDValue(LD0, 1), ResNode.getValue(1));
7831 DCI.CommitTargetLoweringOpt(TLO);
7832 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
7837 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7838 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7839 const X86Subtarget *Subtarget) {
7840 DebugLoc DL = N->getDebugLoc();
7841 SDValue Cond = N->getOperand(0);
7842 // Get the LHS/RHS of the select.
7843 SDValue LHS = N->getOperand(1);
7844 SDValue RHS = N->getOperand(2);
7846 // If we have SSE[12] support, try to form min/max nodes.
7847 if (Subtarget->hasSSE2() &&
7848 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
7849 Cond.getOpcode() == ISD::SETCC) {
7850 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7852 unsigned Opcode = 0;
7853 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7856 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7859 if (!UnsafeFPMath) break;
7861 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7863 Opcode = X86ISD::FMIN;
7866 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7869 if (!UnsafeFPMath) break;
7871 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7873 Opcode = X86ISD::FMAX;
7876 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7879 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7882 if (!UnsafeFPMath) break;
7884 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7886 Opcode = X86ISD::FMIN;
7889 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7892 if (!UnsafeFPMath) break;
7894 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7896 Opcode = X86ISD::FMAX;
7902 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
7905 // If this is a select between two integer constants, try to do some
7907 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
7908 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
7909 // Don't do this for crazy integer types.
7910 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
7911 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
7912 // so that TrueC (the true value) is larger than FalseC.
7913 bool NeedsCondInvert = false;
7915 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
7916 // Efficiently invertible.
7917 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
7918 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
7919 isa<ConstantSDNode>(Cond.getOperand(1))))) {
7920 NeedsCondInvert = true;
7921 std::swap(TrueC, FalseC);
7924 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
7925 if (FalseC->getAPIntValue() == 0 &&
7926 TrueC->getAPIntValue().isPowerOf2()) {
7927 if (NeedsCondInvert) // Invert the condition if needed.
7928 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7929 DAG.getConstant(1, Cond.getValueType()));
7931 // Zero extend the condition if needed.
7932 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
7934 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7935 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
7936 DAG.getConstant(ShAmt, MVT::i8));
7939 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
7940 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
7941 if (NeedsCondInvert) // Invert the condition if needed.
7942 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7943 DAG.getConstant(1, Cond.getValueType()));
7945 // Zero extend the condition if needed.
7946 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
7947 FalseC->getValueType(0), Cond);
7948 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7949 SDValue(FalseC, 0));
7952 // Optimize cases that will turn into an LEA instruction. This requires
7953 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
7954 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
7955 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
7956 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
7958 bool isFastMultiplier = false;
7960 switch ((unsigned char)Diff) {
7962 case 1: // result = add base, cond
7963 case 2: // result = lea base( , cond*2)
7964 case 3: // result = lea base(cond, cond*2)
7965 case 4: // result = lea base( , cond*4)
7966 case 5: // result = lea base(cond, cond*4)
7967 case 8: // result = lea base( , cond*8)
7968 case 9: // result = lea base(cond, cond*8)
7969 isFastMultiplier = true;
7974 if (isFastMultiplier) {
7975 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
7976 if (NeedsCondInvert) // Invert the condition if needed.
7977 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7978 DAG.getConstant(1, Cond.getValueType()));
7980 // Zero extend the condition if needed.
7981 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
7983 // Scale the condition by the difference.
7985 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
7986 DAG.getConstant(Diff, Cond.getValueType()));
7988 // Add the base if non-zero.
7989 if (FalseC->getAPIntValue() != 0)
7990 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7991 SDValue(FalseC, 0));
8001 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8002 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8003 TargetLowering::DAGCombinerInfo &DCI) {
8004 DebugLoc DL = N->getDebugLoc();
8006 // If the flag operand isn't dead, don't touch this CMOV.
8007 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8010 // If this is a select between two integer constants, try to do some
8011 // optimizations. Note that the operands are ordered the opposite of SELECT
8013 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8014 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8015 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8016 // larger than FalseC (the false value).
8017 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8019 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8020 CC = X86::GetOppositeBranchCondition(CC);
8021 std::swap(TrueC, FalseC);
8024 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8025 // This is efficient for any integer data type (including i8/i16) and
8027 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8028 SDValue Cond = N->getOperand(3);
8029 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8030 DAG.getConstant(CC, MVT::i8), Cond);
8032 // Zero extend the condition if needed.
8033 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8035 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8036 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8037 DAG.getConstant(ShAmt, MVT::i8));
8038 if (N->getNumValues() == 2) // Dead flag value?
8039 return DCI.CombineTo(N, Cond, SDValue());
8043 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8044 // for any integer data type, including i8/i16.
8045 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8046 SDValue Cond = N->getOperand(3);
8047 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8048 DAG.getConstant(CC, MVT::i8), Cond);
8050 // Zero extend the condition if needed.
8051 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8052 FalseC->getValueType(0), Cond);
8053 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8054 SDValue(FalseC, 0));
8056 if (N->getNumValues() == 2) // Dead flag value?
8057 return DCI.CombineTo(N, Cond, SDValue());
8061 // Optimize cases that will turn into an LEA instruction. This requires
8062 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8063 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8064 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8065 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8067 bool isFastMultiplier = false;
8069 switch ((unsigned char)Diff) {
8071 case 1: // result = add base, cond
8072 case 2: // result = lea base( , cond*2)
8073 case 3: // result = lea base(cond, cond*2)
8074 case 4: // result = lea base( , cond*4)
8075 case 5: // result = lea base(cond, cond*4)
8076 case 8: // result = lea base( , cond*8)
8077 case 9: // result = lea base(cond, cond*8)
8078 isFastMultiplier = true;
8083 if (isFastMultiplier) {
8084 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8085 SDValue Cond = N->getOperand(3);
8086 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8087 DAG.getConstant(CC, MVT::i8), Cond);
8088 // Zero extend the condition if needed.
8089 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8091 // Scale the condition by the difference.
8093 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8094 DAG.getConstant(Diff, Cond.getValueType()));
8096 // Add the base if non-zero.
8097 if (FalseC->getAPIntValue() != 0)
8098 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8099 SDValue(FalseC, 0));
8100 if (N->getNumValues() == 2) // Dead flag value?
8101 return DCI.CombineTo(N, Cond, SDValue());
8111 /// PerformMulCombine - Optimize a single multiply with constant into two
8112 /// in order to implement it with two cheaper instructions, e.g.
8113 /// LEA + SHL, LEA + LEA.
8114 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8115 TargetLowering::DAGCombinerInfo &DCI) {
8116 if (DAG.getMachineFunction().
8117 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8120 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8123 MVT VT = N->getValueType(0);
8127 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8130 uint64_t MulAmt = C->getZExtValue();
8131 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8134 uint64_t MulAmt1 = 0;
8135 uint64_t MulAmt2 = 0;
8136 if ((MulAmt % 9) == 0) {
8138 MulAmt2 = MulAmt / 9;
8139 } else if ((MulAmt % 5) == 0) {
8141 MulAmt2 = MulAmt / 5;
8142 } else if ((MulAmt % 3) == 0) {
8144 MulAmt2 = MulAmt / 3;
8147 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8148 DebugLoc DL = N->getDebugLoc();
8150 if (isPowerOf2_64(MulAmt2) &&
8151 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8152 // If second multiplifer is pow2, issue it first. We want the multiply by
8153 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8155 std::swap(MulAmt1, MulAmt2);
8158 if (isPowerOf2_64(MulAmt1))
8159 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8160 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8162 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8163 DAG.getConstant(MulAmt1, VT));
8165 if (isPowerOf2_64(MulAmt2))
8166 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8167 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8169 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8170 DAG.getConstant(MulAmt2, VT));
8172 // Do not add new nodes to DAG combiner worklist.
8173 DCI.CombineTo(N, NewMul, false);
8179 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8181 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8182 const X86Subtarget *Subtarget) {
8183 // On X86 with SSE2 support, we can transform this to a vector shift if
8184 // all elements are shifted by the same amount. We can't do this in legalize
8185 // because the a constant vector is typically transformed to a constant pool
8186 // so we have no knowledge of the shift amount.
8187 if (!Subtarget->hasSSE2())
8190 MVT VT = N->getValueType(0);
8191 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8194 SDValue ShAmtOp = N->getOperand(1);
8195 MVT EltVT = VT.getVectorElementType();
8196 DebugLoc DL = N->getDebugLoc();
8198 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8199 unsigned NumElts = VT.getVectorNumElements();
8201 for (; i != NumElts; ++i) {
8202 SDValue Arg = ShAmtOp.getOperand(i);
8203 if (Arg.getOpcode() == ISD::UNDEF) continue;
8207 for (; i != NumElts; ++i) {
8208 SDValue Arg = ShAmtOp.getOperand(i);
8209 if (Arg.getOpcode() == ISD::UNDEF) continue;
8210 if (Arg != BaseShAmt) {
8214 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8215 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8216 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8217 DAG.getIntPtrConstant(0));
8221 if (EltVT.bitsGT(MVT::i32))
8222 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8223 else if (EltVT.bitsLT(MVT::i32))
8224 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8226 // The shift amount is identical so we can do a vector shift.
8227 SDValue ValOp = N->getOperand(0);
8228 switch (N->getOpcode()) {
8230 assert(0 && "Unknown shift opcode!");
8233 if (VT == MVT::v2i64)
8234 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8235 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8237 if (VT == MVT::v4i32)
8238 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8239 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8241 if (VT == MVT::v8i16)
8242 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8243 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8247 if (VT == MVT::v4i32)
8248 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8249 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8251 if (VT == MVT::v8i16)
8252 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8253 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8257 if (VT == MVT::v2i64)
8258 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8259 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8261 if (VT == MVT::v4i32)
8262 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8263 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8265 if (VT == MVT::v8i16)
8266 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8267 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8274 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8275 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8276 const X86Subtarget *Subtarget) {
8277 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8278 // the FP state in cases where an emms may be missing.
8279 // A preferable solution to the general problem is to figure out the right
8280 // places to insert EMMS. This qualifies as a quick hack.
8282 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8283 StoreSDNode *St = cast<StoreSDNode>(N);
8284 MVT VT = St->getValue().getValueType();
8285 if (VT.getSizeInBits() != 64)
8288 const Function *F = DAG.getMachineFunction().getFunction();
8289 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
8290 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
8291 && Subtarget->hasSSE2();
8292 if ((VT.isVector() ||
8293 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8294 isa<LoadSDNode>(St->getValue()) &&
8295 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8296 St->getChain().hasOneUse() && !St->isVolatile()) {
8297 SDNode* LdVal = St->getValue().getNode();
8299 int TokenFactorIndex = -1;
8300 SmallVector<SDValue, 8> Ops;
8301 SDNode* ChainVal = St->getChain().getNode();
8302 // Must be a store of a load. We currently handle two cases: the load
8303 // is a direct child, and it's under an intervening TokenFactor. It is
8304 // possible to dig deeper under nested TokenFactors.
8305 if (ChainVal == LdVal)
8306 Ld = cast<LoadSDNode>(St->getChain());
8307 else if (St->getValue().hasOneUse() &&
8308 ChainVal->getOpcode() == ISD::TokenFactor) {
8309 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8310 if (ChainVal->getOperand(i).getNode() == LdVal) {
8311 TokenFactorIndex = i;
8312 Ld = cast<LoadSDNode>(St->getValue());
8314 Ops.push_back(ChainVal->getOperand(i));
8318 if (!Ld || !ISD::isNormalLoad(Ld))
8321 // If this is not the MMX case, i.e. we are just turning i64 load/store
8322 // into f64 load/store, avoid the transformation if there are multiple
8323 // uses of the loaded value.
8324 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8327 DebugLoc LdDL = Ld->getDebugLoc();
8328 DebugLoc StDL = N->getDebugLoc();
8329 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8330 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8332 if (Subtarget->is64Bit() || F64IsLegal) {
8333 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8334 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8335 Ld->getBasePtr(), Ld->getSrcValue(),
8336 Ld->getSrcValueOffset(), Ld->isVolatile(),
8337 Ld->getAlignment());
8338 SDValue NewChain = NewLd.getValue(1);
8339 if (TokenFactorIndex != -1) {
8340 Ops.push_back(NewChain);
8341 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8344 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8345 St->getSrcValue(), St->getSrcValueOffset(),
8346 St->isVolatile(), St->getAlignment());
8349 // Otherwise, lower to two pairs of 32-bit loads / stores.
8350 SDValue LoAddr = Ld->getBasePtr();
8351 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8352 DAG.getConstant(4, MVT::i32));
8354 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8355 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8356 Ld->isVolatile(), Ld->getAlignment());
8357 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8358 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8360 MinAlign(Ld->getAlignment(), 4));
8362 SDValue NewChain = LoLd.getValue(1);
8363 if (TokenFactorIndex != -1) {
8364 Ops.push_back(LoLd);
8365 Ops.push_back(HiLd);
8366 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8370 LoAddr = St->getBasePtr();
8371 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8372 DAG.getConstant(4, MVT::i32));
8374 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8375 St->getSrcValue(), St->getSrcValueOffset(),
8376 St->isVolatile(), St->getAlignment());
8377 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8379 St->getSrcValueOffset() + 4,
8381 MinAlign(St->getAlignment(), 4));
8382 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8387 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8388 /// X86ISD::FXOR nodes.
8389 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8390 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8391 // F[X]OR(0.0, x) -> x
8392 // F[X]OR(x, 0.0) -> x
8393 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8394 if (C->getValueAPF().isPosZero())
8395 return N->getOperand(1);
8396 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8397 if (C->getValueAPF().isPosZero())
8398 return N->getOperand(0);
8402 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8403 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8404 // FAND(0.0, x) -> 0.0
8405 // FAND(x, 0.0) -> 0.0
8406 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8407 if (C->getValueAPF().isPosZero())
8408 return N->getOperand(0);
8409 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8410 if (C->getValueAPF().isPosZero())
8411 return N->getOperand(1);
8415 static SDValue PerformBTCombine(SDNode *N,
8417 TargetLowering::DAGCombinerInfo &DCI) {
8418 // BT ignores high bits in the bit index operand.
8419 SDValue Op1 = N->getOperand(1);
8420 if (Op1.hasOneUse()) {
8421 unsigned BitWidth = Op1.getValueSizeInBits();
8422 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8423 APInt KnownZero, KnownOne;
8424 TargetLowering::TargetLoweringOpt TLO(DAG);
8425 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8426 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8427 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8428 DCI.CommitTargetLoweringOpt(TLO);
8433 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8434 DAGCombinerInfo &DCI) const {
8435 SelectionDAG &DAG = DCI.DAG;
8436 switch (N->getOpcode()) {
8438 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8439 case ISD::BUILD_VECTOR:
8440 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8441 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8442 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
8443 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
8446 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8447 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8449 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8450 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8451 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8457 //===----------------------------------------------------------------------===//
8458 // X86 Inline Assembly Support
8459 //===----------------------------------------------------------------------===//
8461 /// getConstraintType - Given a constraint letter, return the type of
8462 /// constraint it is for this target.
8463 X86TargetLowering::ConstraintType
8464 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8465 if (Constraint.size() == 1) {
8466 switch (Constraint[0]) {
8478 return C_RegisterClass;
8486 return TargetLowering::getConstraintType(Constraint);
8489 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8490 /// with another that has more specific requirements based on the type of the
8491 /// corresponding operand.
8492 const char *X86TargetLowering::
8493 LowerXConstraint(MVT ConstraintVT) const {
8494 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8495 // 'f' like normal targets.
8496 if (ConstraintVT.isFloatingPoint()) {
8497 if (Subtarget->hasSSE2())
8499 if (Subtarget->hasSSE1())
8503 return TargetLowering::LowerXConstraint(ConstraintVT);
8506 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8507 /// vector. If it is invalid, don't add anything to Ops.
8508 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8511 std::vector<SDValue>&Ops,
8512 SelectionDAG &DAG) const {
8513 SDValue Result(0, 0);
8515 switch (Constraint) {
8518 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8519 if (C->getZExtValue() <= 31) {
8520 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8526 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8527 if (C->getZExtValue() <= 63) {
8528 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8534 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8535 if (C->getZExtValue() <= 255) {
8536 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8542 // 32-bit signed value
8543 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8544 const ConstantInt *CI = C->getConstantIntValue();
8545 if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8546 // Widen to 64 bits here to get it sign extended.
8547 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8550 // FIXME gcc accepts some relocatable values here too, but only in certain
8551 // memory models; it's complicated.
8556 // 32-bit unsigned value
8557 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8558 const ConstantInt *CI = C->getConstantIntValue();
8559 if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8560 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8564 // FIXME gcc accepts some relocatable values here too, but only in certain
8565 // memory models; it's complicated.
8569 // Literal immediates are always ok.
8570 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8571 // Widen to 64 bits here to get it sign extended.
8572 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8576 // If we are in non-pic codegen mode, we allow the address of a global (with
8577 // an optional displacement) to be used with 'i'.
8578 GlobalAddressSDNode *GA = 0;
8581 // Match either (GA), (GA+C), (GA+C1+C2), etc.
8583 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
8584 Offset += GA->getOffset();
8586 } else if (Op.getOpcode() == ISD::ADD) {
8587 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8588 Offset += C->getZExtValue();
8589 Op = Op.getOperand(0);
8592 } else if (Op.getOpcode() == ISD::SUB) {
8593 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8594 Offset += -C->getZExtValue();
8595 Op = Op.getOperand(0);
8600 // Otherwise, this isn't something we can handle, reject it.
8605 Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(), Offset, DAG);
8607 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8614 if (Result.getNode()) {
8615 Ops.push_back(Result);
8618 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8622 std::vector<unsigned> X86TargetLowering::
8623 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8625 if (Constraint.size() == 1) {
8626 // FIXME: not handling fp-stack yet!
8627 switch (Constraint[0]) { // GCC X86 Constraint Letters
8628 default: break; // Unknown constraint letter
8629 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8632 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8633 else if (VT == MVT::i16)
8634 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8635 else if (VT == MVT::i8)
8636 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8637 else if (VT == MVT::i64)
8638 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8643 return std::vector<unsigned>();
8646 std::pair<unsigned, const TargetRegisterClass*>
8647 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8649 // First, see if this is a constraint that directly corresponds to an LLVM
8651 if (Constraint.size() == 1) {
8652 // GCC Constraint Letters
8653 switch (Constraint[0]) {
8655 case 'r': // GENERAL_REGS
8656 case 'R': // LEGACY_REGS
8657 case 'l': // INDEX_REGS
8659 return std::make_pair(0U, X86::GR8RegisterClass);
8661 return std::make_pair(0U, X86::GR16RegisterClass);
8662 if (VT == MVT::i32 || !Subtarget->is64Bit())
8663 return std::make_pair(0U, X86::GR32RegisterClass);
8664 return std::make_pair(0U, X86::GR64RegisterClass);
8665 case 'f': // FP Stack registers.
8666 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8667 // value to the correct fpstack register class.
8668 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8669 return std::make_pair(0U, X86::RFP32RegisterClass);
8670 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8671 return std::make_pair(0U, X86::RFP64RegisterClass);
8672 return std::make_pair(0U, X86::RFP80RegisterClass);
8673 case 'y': // MMX_REGS if MMX allowed.
8674 if (!Subtarget->hasMMX()) break;
8675 return std::make_pair(0U, X86::VR64RegisterClass);
8676 case 'Y': // SSE_REGS if SSE2 allowed
8677 if (!Subtarget->hasSSE2()) break;
8679 case 'x': // SSE_REGS if SSE1 allowed
8680 if (!Subtarget->hasSSE1()) break;
8682 switch (VT.getSimpleVT()) {
8684 // Scalar SSE types.
8687 return std::make_pair(0U, X86::FR32RegisterClass);
8690 return std::make_pair(0U, X86::FR64RegisterClass);
8698 return std::make_pair(0U, X86::VR128RegisterClass);
8704 // Use the default implementation in TargetLowering to convert the register
8705 // constraint into a member of a register class.
8706 std::pair<unsigned, const TargetRegisterClass*> Res;
8707 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8709 // Not found as a standard register?
8710 if (Res.second == 0) {
8711 // GCC calls "st(0)" just plain "st".
8712 if (StringsEqualNoCase("{st}", Constraint)) {
8713 Res.first = X86::ST0;
8714 Res.second = X86::RFP80RegisterClass;
8716 // 'A' means EAX + EDX.
8717 if (Constraint == "A") {
8718 Res.first = X86::EAX;
8719 Res.second = X86::GRADRegisterClass;
8724 // Otherwise, check to see if this is a register class of the wrong value
8725 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8726 // turn into {ax},{dx}.
8727 if (Res.second->hasType(VT))
8728 return Res; // Correct type already, nothing to do.
8730 // All of the single-register GCC register classes map their values onto
8731 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8732 // really want an 8-bit or 32-bit register, map to the appropriate register
8733 // class and return the appropriate register.
8734 if (Res.second == X86::GR16RegisterClass) {
8735 if (VT == MVT::i8) {
8736 unsigned DestReg = 0;
8737 switch (Res.first) {
8739 case X86::AX: DestReg = X86::AL; break;
8740 case X86::DX: DestReg = X86::DL; break;
8741 case X86::CX: DestReg = X86::CL; break;
8742 case X86::BX: DestReg = X86::BL; break;
8745 Res.first = DestReg;
8746 Res.second = X86::GR8RegisterClass;
8748 } else if (VT == MVT::i32) {
8749 unsigned DestReg = 0;
8750 switch (Res.first) {
8752 case X86::AX: DestReg = X86::EAX; break;
8753 case X86::DX: DestReg = X86::EDX; break;
8754 case X86::CX: DestReg = X86::ECX; break;
8755 case X86::BX: DestReg = X86::EBX; break;
8756 case X86::SI: DestReg = X86::ESI; break;
8757 case X86::DI: DestReg = X86::EDI; break;
8758 case X86::BP: DestReg = X86::EBP; break;
8759 case X86::SP: DestReg = X86::ESP; break;
8762 Res.first = DestReg;
8763 Res.second = X86::GR32RegisterClass;
8765 } else if (VT == MVT::i64) {
8766 unsigned DestReg = 0;
8767 switch (Res.first) {
8769 case X86::AX: DestReg = X86::RAX; break;
8770 case X86::DX: DestReg = X86::RDX; break;
8771 case X86::CX: DestReg = X86::RCX; break;
8772 case X86::BX: DestReg = X86::RBX; break;
8773 case X86::SI: DestReg = X86::RSI; break;
8774 case X86::DI: DestReg = X86::RDI; break;
8775 case X86::BP: DestReg = X86::RBP; break;
8776 case X86::SP: DestReg = X86::RSP; break;
8779 Res.first = DestReg;
8780 Res.second = X86::GR64RegisterClass;
8783 } else if (Res.second == X86::FR32RegisterClass ||
8784 Res.second == X86::FR64RegisterClass ||
8785 Res.second == X86::VR128RegisterClass) {
8786 // Handle references to XMM physical registers that got mapped into the
8787 // wrong class. This can happen with constraints like {xmm0} where the
8788 // target independent register mapper will just pick the first match it can
8789 // find, ignoring the required type.
8791 Res.second = X86::FR32RegisterClass;
8792 else if (VT == MVT::f64)
8793 Res.second = X86::FR64RegisterClass;
8794 else if (X86::VR128RegisterClass->hasType(VT))
8795 Res.second = X86::VR128RegisterClass;
8801 //===----------------------------------------------------------------------===//
8802 // X86 Widen vector type
8803 //===----------------------------------------------------------------------===//
8805 /// getWidenVectorType: given a vector type, returns the type to widen
8806 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8807 /// If there is no vector type that we want to widen to, returns MVT::Other
8808 /// When and where to widen is target dependent based on the cost of
8809 /// scalarizing vs using the wider vector type.
8811 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8812 assert(VT.isVector());
8813 if (isTypeLegal(VT))
8816 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8817 // type based on element type. This would speed up our search (though
8818 // it may not be worth it since the size of the list is relatively
8820 MVT EltVT = VT.getVectorElementType();
8821 unsigned NElts = VT.getVectorNumElements();
8823 // On X86, it make sense to widen any vector wider than 1
8827 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8828 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8829 MVT SVT = (MVT::SimpleValueType)nVT;
8831 if (isTypeLegal(SVT) &&
8832 SVT.getVectorElementType() == EltVT &&
8833 SVT.getVectorNumElements() > NElts)