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);
553 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
559 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
560 // with -msoft-float, disable use of MMX as well.
561 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
562 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
563 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
564 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
565 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
566 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
568 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
569 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
570 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
571 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
573 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
574 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
575 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
576 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
578 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
579 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
581 setOperationAction(ISD::AND, MVT::v8i8, Promote);
582 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
583 setOperationAction(ISD::AND, MVT::v4i16, Promote);
584 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
585 setOperationAction(ISD::AND, MVT::v2i32, Promote);
586 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
587 setOperationAction(ISD::AND, MVT::v1i64, Legal);
589 setOperationAction(ISD::OR, MVT::v8i8, Promote);
590 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
591 setOperationAction(ISD::OR, MVT::v4i16, Promote);
592 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
593 setOperationAction(ISD::OR, MVT::v2i32, Promote);
594 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
595 setOperationAction(ISD::OR, MVT::v1i64, Legal);
597 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
598 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
599 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
600 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
601 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
602 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
603 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
605 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
606 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
607 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
608 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
609 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
610 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
611 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
612 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
613 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
615 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
616 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
617 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
618 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
619 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
621 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
622 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
623 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
624 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
626 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
627 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
628 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
629 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
631 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
633 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
634 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
635 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
636 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
637 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
638 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
641 if (!UseSoftFloat && Subtarget->hasSSE1()) {
642 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
644 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
645 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
646 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
647 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
648 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
649 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
650 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
651 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
652 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
653 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
654 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
655 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
658 if (!UseSoftFloat && Subtarget->hasSSE2()) {
659 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
661 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
662 // registers cannot be used even for integer operations.
663 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
664 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
665 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
666 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
668 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
669 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
670 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
671 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
672 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
673 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
674 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
675 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
676 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
677 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
678 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
679 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
680 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
681 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
682 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
683 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
685 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
686 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
687 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
688 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
690 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
691 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
692 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
693 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
694 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
696 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
697 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
698 MVT VT = (MVT::SimpleValueType)i;
699 // Do not attempt to custom lower non-power-of-2 vectors
700 if (!isPowerOf2_32(VT.getVectorNumElements()))
702 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
703 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
704 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
707 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
708 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
709 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
710 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
711 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
714 if (Subtarget->is64Bit()) {
715 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
716 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
719 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
720 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
721 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
722 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
723 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
724 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
725 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
726 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
727 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
728 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
729 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
730 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
733 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
735 // Custom lower v2i64 and v2f64 selects.
736 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
737 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
738 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
739 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
741 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
742 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
743 if (!DisableMMX && Subtarget->hasMMX()) {
744 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
745 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
749 if (Subtarget->hasSSE41()) {
750 // FIXME: Do we need to handle scalar-to-vector here?
751 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
753 // i8 and i16 vectors are custom , because the source register and source
754 // source memory operand types are not the same width. f32 vectors are
755 // custom since the immediate controlling the insert encodes additional
757 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
758 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
759 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
760 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
762 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
763 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
764 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
765 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
767 if (Subtarget->is64Bit()) {
768 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
769 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
773 if (Subtarget->hasSSE42()) {
774 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
777 // We want to custom lower some of our intrinsics.
778 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
780 // Add/Sub/Mul with overflow operations are custom lowered.
781 setOperationAction(ISD::SADDO, MVT::i32, Custom);
782 setOperationAction(ISD::SADDO, MVT::i64, Custom);
783 setOperationAction(ISD::UADDO, MVT::i32, Custom);
784 setOperationAction(ISD::UADDO, MVT::i64, Custom);
785 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
786 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
787 setOperationAction(ISD::USUBO, MVT::i32, Custom);
788 setOperationAction(ISD::USUBO, MVT::i64, Custom);
789 setOperationAction(ISD::SMULO, MVT::i32, Custom);
790 setOperationAction(ISD::SMULO, MVT::i64, Custom);
792 if (!Subtarget->is64Bit()) {
793 // These libcalls are not available in 32-bit.
794 setLibcallName(RTLIB::SHL_I128, 0);
795 setLibcallName(RTLIB::SRL_I128, 0);
796 setLibcallName(RTLIB::SRA_I128, 0);
799 // We have target-specific dag combine patterns for the following nodes:
800 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
801 setTargetDAGCombine(ISD::BUILD_VECTOR);
802 setTargetDAGCombine(ISD::SELECT);
803 setTargetDAGCombine(ISD::SHL);
804 setTargetDAGCombine(ISD::SRA);
805 setTargetDAGCombine(ISD::SRL);
806 setTargetDAGCombine(ISD::STORE);
807 if (Subtarget->is64Bit())
808 setTargetDAGCombine(ISD::MUL);
810 computeRegisterProperties();
812 // FIXME: These should be based on subtarget info. Plus, the values should
813 // be smaller when we are in optimizing for size mode.
814 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
815 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
816 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
817 allowUnalignedMemoryAccesses = true; // x86 supports it!
818 setPrefLoopAlignment(16);
819 benefitFromCodePlacementOpt = true;
823 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
828 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
829 /// the desired ByVal argument alignment.
830 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
833 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
834 if (VTy->getBitWidth() == 128)
836 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
837 unsigned EltAlign = 0;
838 getMaxByValAlign(ATy->getElementType(), EltAlign);
839 if (EltAlign > MaxAlign)
841 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
842 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
843 unsigned EltAlign = 0;
844 getMaxByValAlign(STy->getElementType(i), EltAlign);
845 if (EltAlign > MaxAlign)
854 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
855 /// function arguments in the caller parameter area. For X86, aggregates
856 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
857 /// are at 4-byte boundaries.
858 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
859 if (Subtarget->is64Bit()) {
860 // Max of 8 and alignment of type.
861 unsigned TyAlign = TD->getABITypeAlignment(Ty);
868 if (Subtarget->hasSSE1())
869 getMaxByValAlign(Ty, Align);
873 /// getOptimalMemOpType - Returns the target specific optimal type for load
874 /// and store operations as a result of memset, memcpy, and memmove
875 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
878 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
879 bool isSrcConst, bool isSrcStr,
880 SelectionDAG &DAG) const {
881 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
882 // linux. This is because the stack realignment code can't handle certain
883 // cases like PR2962. This should be removed when PR2962 is fixed.
884 const Function *F = DAG.getMachineFunction().getFunction();
885 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
886 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
887 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
889 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
892 if (Subtarget->is64Bit() && Size >= 8)
897 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
899 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
900 SelectionDAG &DAG) const {
901 if (usesGlobalOffsetTable())
902 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
903 if (!Subtarget->isPICStyleRIPRel())
904 // This doesn't have DebugLoc associated with it, but is not really the
905 // same as a Register.
906 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
911 //===----------------------------------------------------------------------===//
912 // Return Value Calling Convention Implementation
913 //===----------------------------------------------------------------------===//
915 #include "X86GenCallingConv.inc"
917 /// LowerRET - Lower an ISD::RET node.
918 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
919 DebugLoc dl = Op.getDebugLoc();
920 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
922 SmallVector<CCValAssign, 16> RVLocs;
923 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
924 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
925 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
926 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
928 // If this is the first return lowered for this function, add the regs to the
929 // liveout set for the function.
930 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
931 for (unsigned i = 0; i != RVLocs.size(); ++i)
932 if (RVLocs[i].isRegLoc())
933 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
935 SDValue Chain = Op.getOperand(0);
937 // Handle tail call return.
938 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
939 if (Chain.getOpcode() == X86ISD::TAILCALL) {
940 SDValue TailCall = Chain;
941 SDValue TargetAddress = TailCall.getOperand(1);
942 SDValue StackAdjustment = TailCall.getOperand(2);
943 assert(((TargetAddress.getOpcode() == ISD::Register &&
944 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
945 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R11)) ||
946 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
947 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
948 "Expecting an global address, external symbol, or register");
949 assert(StackAdjustment.getOpcode() == ISD::Constant &&
950 "Expecting a const value");
952 SmallVector<SDValue,8> Operands;
953 Operands.push_back(Chain.getOperand(0));
954 Operands.push_back(TargetAddress);
955 Operands.push_back(StackAdjustment);
956 // Copy registers used by the call. Last operand is a flag so it is not
958 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
959 Operands.push_back(Chain.getOperand(i));
961 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
968 SmallVector<SDValue, 6> RetOps;
969 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
970 // Operand #1 = Bytes To Pop
971 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
973 // Copy the result values into the output registers.
974 for (unsigned i = 0; i != RVLocs.size(); ++i) {
975 CCValAssign &VA = RVLocs[i];
976 assert(VA.isRegLoc() && "Can only return in registers!");
977 SDValue ValToCopy = Op.getOperand(i*2+1);
979 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
980 // the RET instruction and handled by the FP Stackifier.
981 if (VA.getLocReg() == X86::ST0 ||
982 VA.getLocReg() == X86::ST1) {
983 // If this is a copy from an xmm register to ST(0), use an FPExtend to
984 // change the value to the FP stack register class.
985 if (isScalarFPTypeInSSEReg(VA.getValVT()))
986 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
987 RetOps.push_back(ValToCopy);
988 // Don't emit a copytoreg.
992 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
993 // which is returned in RAX / RDX.
994 if (Subtarget->is64Bit()) {
995 MVT ValVT = ValToCopy.getValueType();
996 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
997 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
998 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
999 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1003 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1004 Flag = Chain.getValue(1);
1007 // The x86-64 ABI for returning structs by value requires that we copy
1008 // the sret argument into %rax for the return. We saved the argument into
1009 // a virtual register in the entry block, so now we copy the value out
1011 if (Subtarget->is64Bit() &&
1012 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1013 MachineFunction &MF = DAG.getMachineFunction();
1014 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1015 unsigned Reg = FuncInfo->getSRetReturnReg();
1017 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1018 FuncInfo->setSRetReturnReg(Reg);
1020 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1022 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1023 Flag = Chain.getValue(1);
1026 RetOps[0] = Chain; // Update chain.
1028 // Add the flag if we have it.
1030 RetOps.push_back(Flag);
1032 return DAG.getNode(X86ISD::RET_FLAG, dl,
1033 MVT::Other, &RetOps[0], RetOps.size());
1037 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1038 /// appropriate copies out of appropriate physical registers. This assumes that
1039 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1040 /// being lowered. The returns a SDNode with the same number of values as the
1042 SDNode *X86TargetLowering::
1043 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1044 unsigned CallingConv, SelectionDAG &DAG) {
1046 DebugLoc dl = TheCall->getDebugLoc();
1047 // Assign locations to each value returned by this call.
1048 SmallVector<CCValAssign, 16> RVLocs;
1049 bool isVarArg = TheCall->isVarArg();
1050 bool Is64Bit = Subtarget->is64Bit();
1051 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1052 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1054 SmallVector<SDValue, 8> ResultVals;
1056 // Copy all of the result registers out of their specified physreg.
1057 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1058 CCValAssign &VA = RVLocs[i];
1059 MVT CopyVT = VA.getValVT();
1061 // If this is x86-64, and we disabled SSE, we can't return FP values
1062 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1063 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1064 cerr << "SSE register return with SSE disabled\n";
1068 // If this is a call to a function that returns an fp value on the floating
1069 // point stack, but where we prefer to use the value in xmm registers, copy
1070 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1071 if ((VA.getLocReg() == X86::ST0 ||
1072 VA.getLocReg() == X86::ST1) &&
1073 isScalarFPTypeInSSEReg(VA.getValVT())) {
1078 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1079 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1080 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1081 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1082 MVT::v2i64, InFlag).getValue(1);
1083 Val = Chain.getValue(0);
1084 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1085 Val, DAG.getConstant(0, MVT::i64));
1087 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1088 MVT::i64, InFlag).getValue(1);
1089 Val = Chain.getValue(0);
1091 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1093 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1094 CopyVT, InFlag).getValue(1);
1095 Val = Chain.getValue(0);
1097 InFlag = Chain.getValue(2);
1099 if (CopyVT != VA.getValVT()) {
1100 // Round the F80 the right size, which also moves to the appropriate xmm
1102 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1103 // This truncation won't change the value.
1104 DAG.getIntPtrConstant(1));
1107 ResultVals.push_back(Val);
1110 // Merge everything together with a MERGE_VALUES node.
1111 ResultVals.push_back(Chain);
1112 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1113 &ResultVals[0], ResultVals.size()).getNode();
1117 //===----------------------------------------------------------------------===//
1118 // C & StdCall & Fast Calling Convention implementation
1119 //===----------------------------------------------------------------------===//
1120 // StdCall calling convention seems to be standard for many Windows' API
1121 // routines and around. It differs from C calling convention just a little:
1122 // callee should clean up the stack, not caller. Symbols should be also
1123 // decorated in some fancy way :) It doesn't support any vector arguments.
1124 // For info on fast calling convention see Fast Calling Convention (tail call)
1125 // implementation LowerX86_32FastCCCallTo.
1127 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1129 static bool CallIsStructReturn(CallSDNode *TheCall) {
1130 unsigned NumOps = TheCall->getNumArgs();
1134 return TheCall->getArgFlags(0).isSRet();
1137 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1138 /// return semantics.
1139 static bool ArgsAreStructReturn(SDValue Op) {
1140 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1144 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1147 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1148 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1150 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1154 switch (CallingConv) {
1157 case CallingConv::X86_StdCall:
1158 return !Subtarget->is64Bit();
1159 case CallingConv::X86_FastCall:
1160 return !Subtarget->is64Bit();
1161 case CallingConv::Fast:
1162 return PerformTailCallOpt;
1166 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1167 /// given CallingConvention value.
1168 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1169 if (Subtarget->is64Bit()) {
1170 if (Subtarget->isTargetWin64())
1171 return CC_X86_Win64_C;
1176 if (CC == CallingConv::X86_FastCall)
1177 return CC_X86_32_FastCall;
1178 else if (CC == CallingConv::Fast)
1179 return CC_X86_32_FastCC;
1184 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1185 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1187 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1188 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1189 if (CC == CallingConv::X86_FastCall)
1191 else if (CC == CallingConv::X86_StdCall)
1197 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1198 /// in a register before calling.
1199 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1200 return !IsTailCall && !Is64Bit &&
1201 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1202 Subtarget->isPICStyleGOT();
1205 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1206 /// address to be loaded in a register.
1208 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1209 return !Is64Bit && IsTailCall &&
1210 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1211 Subtarget->isPICStyleGOT();
1214 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1215 /// by "Src" to address "Dst" with size and alignment information specified by
1216 /// the specific parameter attribute. The copy will be passed as a byval
1217 /// function parameter.
1219 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1220 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1222 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1223 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1224 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1227 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1228 const CCValAssign &VA,
1229 MachineFrameInfo *MFI,
1231 SDValue Root, unsigned i) {
1232 // Create the nodes corresponding to a load from this parameter slot.
1233 ISD::ArgFlagsTy Flags =
1234 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1235 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1236 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1238 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1239 // changed with more analysis.
1240 // In case of tail call optimization mark all arguments mutable. Since they
1241 // could be overwritten by lowering of arguments in case of a tail call.
1242 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1243 VA.getLocMemOffset(), isImmutable);
1244 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1245 if (Flags.isByVal())
1247 return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1248 PseudoSourceValue::getFixedStack(FI), 0);
1252 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1253 MachineFunction &MF = DAG.getMachineFunction();
1254 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1255 DebugLoc dl = Op.getDebugLoc();
1257 const Function* Fn = MF.getFunction();
1258 if (Fn->hasExternalLinkage() &&
1259 Subtarget->isTargetCygMing() &&
1260 Fn->getName() == "main")
1261 FuncInfo->setForceFramePointer(true);
1263 // Decorate the function name.
1264 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1266 MachineFrameInfo *MFI = MF.getFrameInfo();
1267 SDValue Root = Op.getOperand(0);
1268 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1269 unsigned CC = MF.getFunction()->getCallingConv();
1270 bool Is64Bit = Subtarget->is64Bit();
1271 bool IsWin64 = Subtarget->isTargetWin64();
1273 assert(!(isVarArg && CC == CallingConv::Fast) &&
1274 "Var args not supported with calling convention fastcc");
1276 // Assign locations to all of the incoming arguments.
1277 SmallVector<CCValAssign, 16> ArgLocs;
1278 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1279 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1281 SmallVector<SDValue, 8> ArgValues;
1282 unsigned LastVal = ~0U;
1283 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1284 CCValAssign &VA = ArgLocs[i];
1285 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1287 assert(VA.getValNo() != LastVal &&
1288 "Don't support value assigned to multiple locs yet");
1289 LastVal = VA.getValNo();
1291 if (VA.isRegLoc()) {
1292 MVT RegVT = VA.getLocVT();
1293 TargetRegisterClass *RC = NULL;
1294 if (RegVT == MVT::i32)
1295 RC = X86::GR32RegisterClass;
1296 else if (Is64Bit && RegVT == MVT::i64)
1297 RC = X86::GR64RegisterClass;
1298 else if (RegVT == MVT::f32)
1299 RC = X86::FR32RegisterClass;
1300 else if (RegVT == MVT::f64)
1301 RC = X86::FR64RegisterClass;
1302 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1303 RC = X86::VR128RegisterClass;
1304 else if (RegVT.isVector()) {
1305 assert(RegVT.getSizeInBits() == 64);
1307 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1309 // Darwin calling convention passes MMX values in either GPRs or
1310 // XMMs in x86-64. Other targets pass them in memory.
1311 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1312 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1315 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1320 assert(0 && "Unknown argument type!");
1323 unsigned Reg = DAG.getMachineFunction().addLiveIn(VA.getLocReg(), RC);
1324 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1326 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1327 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1329 if (VA.getLocInfo() == CCValAssign::SExt)
1330 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1331 DAG.getValueType(VA.getValVT()));
1332 else if (VA.getLocInfo() == CCValAssign::ZExt)
1333 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1334 DAG.getValueType(VA.getValVT()));
1336 if (VA.getLocInfo() != CCValAssign::Full)
1337 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1339 // Handle MMX values passed in GPRs.
1340 if (Is64Bit && RegVT != VA.getLocVT()) {
1341 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1342 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1343 else if (RC == X86::VR128RegisterClass) {
1344 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1345 ArgValue, DAG.getConstant(0, MVT::i64));
1346 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1350 ArgValues.push_back(ArgValue);
1352 assert(VA.isMemLoc());
1353 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1357 // The x86-64 ABI for returning structs by value requires that we copy
1358 // the sret argument into %rax for the return. Save the argument into
1359 // a virtual register so that we can access it from the return points.
1360 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1361 MachineFunction &MF = DAG.getMachineFunction();
1362 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1363 unsigned Reg = FuncInfo->getSRetReturnReg();
1365 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1366 FuncInfo->setSRetReturnReg(Reg);
1368 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1369 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1372 unsigned StackSize = CCInfo.getNextStackOffset();
1373 // align stack specially for tail calls
1374 if (PerformTailCallOpt && CC == CallingConv::Fast)
1375 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1377 // If the function takes variable number of arguments, make a frame index for
1378 // the start of the first vararg value... for expansion of llvm.va_start.
1380 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1381 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1384 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1386 // FIXME: We should really autogenerate these arrays
1387 static const unsigned GPR64ArgRegsWin64[] = {
1388 X86::RCX, X86::RDX, X86::R8, X86::R9
1390 static const unsigned XMMArgRegsWin64[] = {
1391 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1393 static const unsigned GPR64ArgRegs64Bit[] = {
1394 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1396 static const unsigned XMMArgRegs64Bit[] = {
1397 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1398 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1400 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1403 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1404 GPR64ArgRegs = GPR64ArgRegsWin64;
1405 XMMArgRegs = XMMArgRegsWin64;
1407 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1408 GPR64ArgRegs = GPR64ArgRegs64Bit;
1409 XMMArgRegs = XMMArgRegs64Bit;
1411 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1413 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1416 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1417 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1418 "SSE register cannot be used when SSE is disabled!");
1419 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1420 "SSE register cannot be used when SSE is disabled!");
1421 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1422 // Kernel mode asks for SSE to be disabled, so don't push them
1424 TotalNumXMMRegs = 0;
1426 // For X86-64, if there are vararg parameters that are passed via
1427 // registers, then we must store them to their spots on the stack so they
1428 // may be loaded by deferencing the result of va_next.
1429 VarArgsGPOffset = NumIntRegs * 8;
1430 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1431 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1432 TotalNumXMMRegs * 16, 16);
1434 // Store the integer parameter registers.
1435 SmallVector<SDValue, 8> MemOps;
1436 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1437 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1438 DAG.getIntPtrConstant(VarArgsGPOffset));
1439 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1440 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1441 X86::GR64RegisterClass);
1442 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1444 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1445 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1446 MemOps.push_back(Store);
1447 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1448 DAG.getIntPtrConstant(8));
1451 // Now store the XMM (fp + vector) parameter registers.
1452 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1453 DAG.getIntPtrConstant(VarArgsFPOffset));
1454 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1455 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1456 X86::VR128RegisterClass);
1457 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1459 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1460 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1461 MemOps.push_back(Store);
1462 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1463 DAG.getIntPtrConstant(16));
1465 if (!MemOps.empty())
1466 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1467 &MemOps[0], MemOps.size());
1471 ArgValues.push_back(Root);
1473 // Some CCs need callee pop.
1474 if (IsCalleePop(isVarArg, CC)) {
1475 BytesToPopOnReturn = StackSize; // Callee pops everything.
1476 BytesCallerReserves = 0;
1478 BytesToPopOnReturn = 0; // Callee pops nothing.
1479 // If this is an sret function, the return should pop the hidden pointer.
1480 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1481 BytesToPopOnReturn = 4;
1482 BytesCallerReserves = StackSize;
1486 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1487 if (CC == CallingConv::X86_FastCall)
1488 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1491 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1493 // Return the new list of results.
1494 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1495 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1499 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1500 const SDValue &StackPtr,
1501 const CCValAssign &VA,
1503 SDValue Arg, ISD::ArgFlagsTy Flags) {
1504 DebugLoc dl = TheCall->getDebugLoc();
1505 unsigned LocMemOffset = VA.getLocMemOffset();
1506 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1507 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1508 if (Flags.isByVal()) {
1509 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1511 return DAG.getStore(Chain, dl, Arg, PtrOff,
1512 PseudoSourceValue::getStack(), LocMemOffset);
1515 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1516 /// optimization is performed and it is required.
1518 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1519 SDValue &OutRetAddr,
1525 if (!IsTailCall || FPDiff==0) return Chain;
1527 // Adjust the Return address stack slot.
1528 MVT VT = getPointerTy();
1529 OutRetAddr = getReturnAddressFrameIndex(DAG);
1531 // Load the "old" Return address.
1532 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1533 return SDValue(OutRetAddr.getNode(), 1);
1536 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1537 /// optimization is performed and it is required (FPDiff!=0).
1539 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1540 SDValue Chain, SDValue RetAddrFrIdx,
1541 bool Is64Bit, int FPDiff, DebugLoc dl) {
1542 // Store the return address to the appropriate stack slot.
1543 if (!FPDiff) return Chain;
1544 // Calculate the new stack slot for the return address.
1545 int SlotSize = Is64Bit ? 8 : 4;
1546 int NewReturnAddrFI =
1547 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1548 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1549 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1550 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1551 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1555 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1556 MachineFunction &MF = DAG.getMachineFunction();
1557 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1558 SDValue Chain = TheCall->getChain();
1559 unsigned CC = TheCall->getCallingConv();
1560 bool isVarArg = TheCall->isVarArg();
1561 bool IsTailCall = TheCall->isTailCall() &&
1562 CC == CallingConv::Fast && PerformTailCallOpt;
1563 SDValue Callee = TheCall->getCallee();
1564 bool Is64Bit = Subtarget->is64Bit();
1565 bool IsStructRet = CallIsStructReturn(TheCall);
1566 DebugLoc dl = TheCall->getDebugLoc();
1568 assert(!(isVarArg && CC == CallingConv::Fast) &&
1569 "Var args not supported with calling convention fastcc");
1571 // Analyze operands of the call, assigning locations to each operand.
1572 SmallVector<CCValAssign, 16> ArgLocs;
1573 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1574 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1576 // Get a count of how many bytes are to be pushed on the stack.
1577 unsigned NumBytes = CCInfo.getNextStackOffset();
1578 if (PerformTailCallOpt && CC == CallingConv::Fast)
1579 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1583 // Lower arguments at fp - stackoffset + fpdiff.
1584 unsigned NumBytesCallerPushed =
1585 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1586 FPDiff = NumBytesCallerPushed - NumBytes;
1588 // Set the delta of movement of the returnaddr stackslot.
1589 // But only set if delta is greater than previous delta.
1590 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1591 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1594 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1596 SDValue RetAddrFrIdx;
1597 // Load return adress for tail calls.
1598 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1601 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1602 SmallVector<SDValue, 8> MemOpChains;
1605 // Walk the register/memloc assignments, inserting copies/loads. In the case
1606 // of tail call optimization arguments are handle later.
1607 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1608 CCValAssign &VA = ArgLocs[i];
1609 SDValue Arg = TheCall->getArg(i);
1610 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1611 bool isByVal = Flags.isByVal();
1613 // Promote the value if needed.
1614 switch (VA.getLocInfo()) {
1615 default: assert(0 && "Unknown loc info!");
1616 case CCValAssign::Full: break;
1617 case CCValAssign::SExt:
1618 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1620 case CCValAssign::ZExt:
1621 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1623 case CCValAssign::AExt:
1624 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1628 if (VA.isRegLoc()) {
1630 MVT RegVT = VA.getLocVT();
1631 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1632 switch (VA.getLocReg()) {
1635 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1637 // Special case: passing MMX values in GPR registers.
1638 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1641 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1642 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1643 // Special case: passing MMX values in XMM registers.
1644 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1645 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1646 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1651 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1653 if (!IsTailCall || (IsTailCall && isByVal)) {
1654 assert(VA.isMemLoc());
1655 if (StackPtr.getNode() == 0)
1656 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1658 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1659 Chain, Arg, Flags));
1664 if (!MemOpChains.empty())
1665 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1666 &MemOpChains[0], MemOpChains.size());
1668 // Build a sequence of copy-to-reg nodes chained together with token chain
1669 // and flag operands which copy the outgoing args into registers.
1671 // Tail call byval lowering might overwrite argument registers so in case of
1672 // tail call optimization the copies to registers are lowered later.
1674 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1675 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1676 RegsToPass[i].second, InFlag);
1677 InFlag = Chain.getValue(1);
1680 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1682 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1683 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1684 DAG.getNode(X86ISD::GlobalBaseReg,
1685 DebugLoc::getUnknownLoc(),
1688 InFlag = Chain.getValue(1);
1690 // If we are tail calling and generating PIC/GOT style code load the address
1691 // of the callee into ecx. The value in ecx is used as target of the tail
1692 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1693 // calls on PIC/GOT architectures. Normally we would just put the address of
1694 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1695 // restored (since ebx is callee saved) before jumping to the target@PLT.
1696 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1697 // Note: The actual moving to ecx is done further down.
1698 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1699 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1700 !G->getGlobal()->hasProtectedVisibility())
1701 Callee = LowerGlobalAddress(Callee, DAG);
1702 else if (isa<ExternalSymbolSDNode>(Callee))
1703 Callee = LowerExternalSymbol(Callee,DAG);
1706 if (Is64Bit && isVarArg) {
1707 // From AMD64 ABI document:
1708 // For calls that may call functions that use varargs or stdargs
1709 // (prototype-less calls or calls to functions containing ellipsis (...) in
1710 // the declaration) %al is used as hidden argument to specify the number
1711 // of SSE registers used. The contents of %al do not need to match exactly
1712 // the number of registers, but must be an ubound on the number of SSE
1713 // registers used and is in the range 0 - 8 inclusive.
1715 // FIXME: Verify this on Win64
1716 // Count the number of XMM registers allocated.
1717 static const unsigned XMMArgRegs[] = {
1718 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1719 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1721 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1722 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1723 && "SSE registers cannot be used when SSE is disabled");
1725 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1726 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1727 InFlag = Chain.getValue(1);
1731 // For tail calls lower the arguments to the 'real' stack slot.
1733 SmallVector<SDValue, 8> MemOpChains2;
1736 // Do not flag preceeding copytoreg stuff together with the following stuff.
1738 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1739 CCValAssign &VA = ArgLocs[i];
1740 if (!VA.isRegLoc()) {
1741 assert(VA.isMemLoc());
1742 SDValue Arg = TheCall->getArg(i);
1743 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1744 // Create frame index.
1745 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1746 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1747 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1748 FIN = DAG.getFrameIndex(FI, getPointerTy());
1750 if (Flags.isByVal()) {
1751 // Copy relative to framepointer.
1752 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1753 if (StackPtr.getNode() == 0)
1754 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1756 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1758 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1761 // Store relative to framepointer.
1762 MemOpChains2.push_back(
1763 DAG.getStore(Chain, dl, Arg, FIN,
1764 PseudoSourceValue::getFixedStack(FI), 0));
1769 if (!MemOpChains2.empty())
1770 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1771 &MemOpChains2[0], MemOpChains2.size());
1773 // Copy arguments to their registers.
1774 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1775 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1776 RegsToPass[i].second, InFlag);
1777 InFlag = Chain.getValue(1);
1781 // Store the return address to the appropriate stack slot.
1782 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1786 // If the callee is a GlobalAddress node (quite common, every direct call is)
1787 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1788 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1789 // We should use extra load for direct calls to dllimported functions in
1791 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1792 getTargetMachine(), true))
1793 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1795 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1796 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1797 } else if (IsTailCall) {
1798 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
1800 Chain = DAG.getCopyToReg(Chain, dl,
1801 DAG.getRegister(Opc, getPointerTy()),
1803 Callee = DAG.getRegister(Opc, getPointerTy());
1804 // Add register as live out.
1805 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1808 // Returns a chain & a flag for retval copy to use.
1809 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1810 SmallVector<SDValue, 8> Ops;
1813 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1814 DAG.getIntPtrConstant(0, true), InFlag);
1815 InFlag = Chain.getValue(1);
1817 // Returns a chain & a flag for retval copy to use.
1818 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1822 Ops.push_back(Chain);
1823 Ops.push_back(Callee);
1826 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1828 // Add argument registers to the end of the list so that they are known live
1830 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1831 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1832 RegsToPass[i].second.getValueType()));
1834 // Add an implicit use GOT pointer in EBX.
1835 if (!IsTailCall && !Is64Bit &&
1836 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1837 Subtarget->isPICStyleGOT())
1838 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1840 // Add an implicit use of AL for x86 vararg functions.
1841 if (Is64Bit && isVarArg)
1842 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1844 if (InFlag.getNode())
1845 Ops.push_back(InFlag);
1848 assert(InFlag.getNode() &&
1849 "Flag must be set. Depend on flag being set in LowerRET");
1850 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1851 TheCall->getVTList(), &Ops[0], Ops.size());
1853 return SDValue(Chain.getNode(), Op.getResNo());
1856 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1857 InFlag = Chain.getValue(1);
1859 // Create the CALLSEQ_END node.
1860 unsigned NumBytesForCalleeToPush;
1861 if (IsCalleePop(isVarArg, CC))
1862 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1863 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1864 // If this is is a call to a struct-return function, the callee
1865 // pops the hidden struct pointer, so we have to push it back.
1866 // This is common for Darwin/X86, Linux & Mingw32 targets.
1867 NumBytesForCalleeToPush = 4;
1869 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1871 // Returns a flag for retval copy to use.
1872 Chain = DAG.getCALLSEQ_END(Chain,
1873 DAG.getIntPtrConstant(NumBytes, true),
1874 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1877 InFlag = Chain.getValue(1);
1879 // Handle result values, copying them out of physregs into vregs that we
1881 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1886 //===----------------------------------------------------------------------===//
1887 // Fast Calling Convention (tail call) implementation
1888 //===----------------------------------------------------------------------===//
1890 // Like std call, callee cleans arguments, convention except that ECX is
1891 // reserved for storing the tail called function address. Only 2 registers are
1892 // free for argument passing (inreg). Tail call optimization is performed
1894 // * tailcallopt is enabled
1895 // * caller/callee are fastcc
1896 // On X86_64 architecture with GOT-style position independent code only local
1897 // (within module) calls are supported at the moment.
1898 // To keep the stack aligned according to platform abi the function
1899 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1900 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1901 // If a tail called function callee has more arguments than the caller the
1902 // caller needs to make sure that there is room to move the RETADDR to. This is
1903 // achieved by reserving an area the size of the argument delta right after the
1904 // original REtADDR, but before the saved framepointer or the spilled registers
1905 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1917 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1918 /// for a 16 byte align requirement.
1919 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1920 SelectionDAG& DAG) {
1921 MachineFunction &MF = DAG.getMachineFunction();
1922 const TargetMachine &TM = MF.getTarget();
1923 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1924 unsigned StackAlignment = TFI.getStackAlignment();
1925 uint64_t AlignMask = StackAlignment - 1;
1926 int64_t Offset = StackSize;
1927 uint64_t SlotSize = TD->getPointerSize();
1928 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1929 // Number smaller than 12 so just add the difference.
1930 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1932 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1933 Offset = ((~AlignMask) & Offset) + StackAlignment +
1934 (StackAlignment-SlotSize);
1939 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1940 /// following the call is a return. A function is eligible if caller/callee
1941 /// calling conventions match, currently only fastcc supports tail calls, and
1942 /// the function CALL is immediatly followed by a RET.
1943 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1945 SelectionDAG& DAG) const {
1946 if (!PerformTailCallOpt)
1949 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1950 MachineFunction &MF = DAG.getMachineFunction();
1951 unsigned CallerCC = MF.getFunction()->getCallingConv();
1952 unsigned CalleeCC= TheCall->getCallingConv();
1953 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1954 SDValue Callee = TheCall->getCallee();
1955 // On x86/32Bit PIC/GOT tail calls are supported.
1956 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1957 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1960 // Can only do local tail calls (in same module, hidden or protected) on
1961 // x86_64 PIC/GOT at the moment.
1962 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1963 return G->getGlobal()->hasHiddenVisibility()
1964 || G->getGlobal()->hasProtectedVisibility();
1972 X86TargetLowering::createFastISel(MachineFunction &mf,
1973 MachineModuleInfo *mmo,
1975 DenseMap<const Value *, unsigned> &vm,
1976 DenseMap<const BasicBlock *,
1977 MachineBasicBlock *> &bm,
1978 DenseMap<const AllocaInst *, int> &am
1980 , SmallSet<Instruction*, 8> &cil
1983 return X86::createFastISel(mf, mmo, dw, vm, bm, am
1991 //===----------------------------------------------------------------------===//
1992 // Other Lowering Hooks
1993 //===----------------------------------------------------------------------===//
1996 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1997 MachineFunction &MF = DAG.getMachineFunction();
1998 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1999 int ReturnAddrIndex = FuncInfo->getRAIndex();
2001 if (ReturnAddrIndex == 0) {
2002 // Set up a frame object for the return address.
2003 uint64_t SlotSize = TD->getPointerSize();
2004 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2005 FuncInfo->setRAIndex(ReturnAddrIndex);
2008 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2012 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2013 /// specific condition code, returning the condition code and the LHS/RHS of the
2014 /// comparison to make.
2015 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2016 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2018 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2019 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2020 // X > -1 -> X == 0, jump !sign.
2021 RHS = DAG.getConstant(0, RHS.getValueType());
2022 return X86::COND_NS;
2023 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2024 // X < 0 -> X == 0, jump on sign.
2026 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2028 RHS = DAG.getConstant(0, RHS.getValueType());
2029 return X86::COND_LE;
2033 switch (SetCCOpcode) {
2034 default: assert(0 && "Invalid integer condition!");
2035 case ISD::SETEQ: return X86::COND_E;
2036 case ISD::SETGT: return X86::COND_G;
2037 case ISD::SETGE: return X86::COND_GE;
2038 case ISD::SETLT: return X86::COND_L;
2039 case ISD::SETLE: return X86::COND_LE;
2040 case ISD::SETNE: return X86::COND_NE;
2041 case ISD::SETULT: return X86::COND_B;
2042 case ISD::SETUGT: return X86::COND_A;
2043 case ISD::SETULE: return X86::COND_BE;
2044 case ISD::SETUGE: return X86::COND_AE;
2048 // First determine if it is required or is profitable to flip the operands.
2050 // If LHS is a foldable load, but RHS is not, flip the condition.
2051 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2052 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2053 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2054 std::swap(LHS, RHS);
2057 switch (SetCCOpcode) {
2063 std::swap(LHS, RHS);
2067 // On a floating point condition, the flags are set as follows:
2069 // 0 | 0 | 0 | X > Y
2070 // 0 | 0 | 1 | X < Y
2071 // 1 | 0 | 0 | X == Y
2072 // 1 | 1 | 1 | unordered
2073 switch (SetCCOpcode) {
2074 default: assert(0 && "Condcode should be pre-legalized away");
2076 case ISD::SETEQ: return X86::COND_E;
2077 case ISD::SETOLT: // flipped
2079 case ISD::SETGT: return X86::COND_A;
2080 case ISD::SETOLE: // flipped
2082 case ISD::SETGE: return X86::COND_AE;
2083 case ISD::SETUGT: // flipped
2085 case ISD::SETLT: return X86::COND_B;
2086 case ISD::SETUGE: // flipped
2088 case ISD::SETLE: return X86::COND_BE;
2090 case ISD::SETNE: return X86::COND_NE;
2091 case ISD::SETUO: return X86::COND_P;
2092 case ISD::SETO: return X86::COND_NP;
2096 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2097 /// code. Current x86 isa includes the following FP cmov instructions:
2098 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2099 static bool hasFPCMov(unsigned X86CC) {
2115 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2116 /// the specified range (L, H].
2117 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2118 return (Val < 0) || (Val >= Low && Val < Hi);
2121 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2122 /// specified value.
2123 static bool isUndefOrEqual(int Val, int CmpVal) {
2124 if (Val < 0 || Val == CmpVal)
2129 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2130 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2131 /// the second operand.
2132 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2133 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2134 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2135 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2136 return (Mask[0] < 2 && Mask[1] < 2);
2140 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2141 SmallVector<int, 8> M;
2143 return ::isPSHUFDMask(M, N->getValueType(0));
2146 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2147 /// is suitable for input to PSHUFHW.
2148 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2149 if (VT != MVT::v8i16)
2152 // Lower quadword copied in order or undef.
2153 for (int i = 0; i != 4; ++i)
2154 if (Mask[i] >= 0 && Mask[i] != i)
2157 // Upper quadword shuffled.
2158 for (int i = 4; i != 8; ++i)
2159 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2165 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2166 SmallVector<int, 8> M;
2168 return ::isPSHUFHWMask(M, N->getValueType(0));
2171 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2172 /// is suitable for input to PSHUFLW.
2173 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2174 if (VT != MVT::v8i16)
2177 // Upper quadword copied in order.
2178 for (int i = 4; i != 8; ++i)
2179 if (Mask[i] >= 0 && Mask[i] != i)
2182 // Lower quadword shuffled.
2183 for (int i = 0; i != 4; ++i)
2190 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2191 SmallVector<int, 8> M;
2193 return ::isPSHUFLWMask(M, N->getValueType(0));
2196 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2197 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2198 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2199 int NumElems = VT.getVectorNumElements();
2200 if (NumElems != 2 && NumElems != 4)
2203 int Half = NumElems / 2;
2204 for (int i = 0; i < Half; ++i)
2205 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2207 for (int i = Half; i < NumElems; ++i)
2208 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2214 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2215 SmallVector<int, 8> M;
2217 return ::isSHUFPMask(M, N->getValueType(0));
2220 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2221 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2222 /// half elements to come from vector 1 (which would equal the dest.) and
2223 /// the upper half to come from vector 2.
2224 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2225 int NumElems = VT.getVectorNumElements();
2227 if (NumElems != 2 && NumElems != 4)
2230 int Half = NumElems / 2;
2231 for (int i = 0; i < Half; ++i)
2232 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2234 for (int i = Half; i < NumElems; ++i)
2235 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2240 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2241 SmallVector<int, 8> M;
2243 return isCommutedSHUFPMask(M, N->getValueType(0));
2246 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2247 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2248 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2249 if (N->getValueType(0).getVectorNumElements() != 4)
2252 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2253 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2254 isUndefOrEqual(N->getMaskElt(1), 7) &&
2255 isUndefOrEqual(N->getMaskElt(2), 2) &&
2256 isUndefOrEqual(N->getMaskElt(3), 3);
2259 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2260 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2261 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2262 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2264 if (NumElems != 2 && NumElems != 4)
2267 for (unsigned i = 0; i < NumElems/2; ++i)
2268 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2271 for (unsigned i = NumElems/2; i < NumElems; ++i)
2272 if (!isUndefOrEqual(N->getMaskElt(i), i))
2278 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2279 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2281 bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2282 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2284 if (NumElems != 2 && NumElems != 4)
2287 for (unsigned i = 0; i < NumElems/2; ++i)
2288 if (!isUndefOrEqual(N->getMaskElt(i), i))
2291 for (unsigned i = 0; i < NumElems/2; ++i)
2292 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2298 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2299 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2301 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2302 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2307 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2308 isUndefOrEqual(N->getMaskElt(1), 3) &&
2309 isUndefOrEqual(N->getMaskElt(2), 2) &&
2310 isUndefOrEqual(N->getMaskElt(3), 3);
2313 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2314 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2315 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2316 bool V2IsSplat = false) {
2317 int NumElts = VT.getVectorNumElements();
2318 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2321 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2323 int BitI1 = Mask[i+1];
2324 if (!isUndefOrEqual(BitI, j))
2327 if (!isUndefOrEqual(BitI1, NumElts))
2330 if (!isUndefOrEqual(BitI1, j + NumElts))
2337 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2338 SmallVector<int, 8> M;
2340 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2343 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2344 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2345 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, MVT VT,
2346 bool V2IsSplat = false) {
2347 int NumElts = VT.getVectorNumElements();
2348 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2351 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2353 int BitI1 = Mask[i+1];
2354 if (!isUndefOrEqual(BitI, j + NumElts/2))
2357 if (isUndefOrEqual(BitI1, NumElts))
2360 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2367 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2368 SmallVector<int, 8> M;
2370 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2373 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2374 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2376 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2377 int NumElems = VT.getVectorNumElements();
2378 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2381 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2383 int BitI1 = Mask[i+1];
2384 if (!isUndefOrEqual(BitI, j))
2386 if (!isUndefOrEqual(BitI1, j))
2392 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2393 SmallVector<int, 8> M;
2395 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2398 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2399 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2401 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2402 int NumElems = VT.getVectorNumElements();
2403 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2406 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2408 int BitI1 = Mask[i+1];
2409 if (!isUndefOrEqual(BitI, j))
2411 if (!isUndefOrEqual(BitI1, j))
2417 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2418 SmallVector<int, 8> M;
2420 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2423 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2424 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2425 /// MOVSD, and MOVD, i.e. setting the lowest element.
2426 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2427 if (VT.getVectorElementType().getSizeInBits() < 32)
2430 int NumElts = VT.getVectorNumElements();
2432 if (!isUndefOrEqual(Mask[0], NumElts))
2435 for (int i = 1; i < NumElts; ++i)
2436 if (!isUndefOrEqual(Mask[i], i))
2442 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2443 SmallVector<int, 8> M;
2445 return ::isMOVLMask(M, N->getValueType(0));
2448 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2449 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2450 /// element of vector 2 and the other elements to come from vector 1 in order.
2451 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2452 bool V2IsSplat = false, bool V2IsUndef = false) {
2453 int NumOps = VT.getVectorNumElements();
2454 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2457 if (!isUndefOrEqual(Mask[0], 0))
2460 for (int i = 1; i < NumOps; ++i)
2461 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2462 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2463 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2469 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2470 bool V2IsUndef = false) {
2471 SmallVector<int, 8> M;
2473 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2476 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2477 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2478 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2479 if (N->getValueType(0).getVectorNumElements() != 4)
2482 // Expect 1, 1, 3, 3
2483 for (unsigned i = 0; i < 2; ++i) {
2484 int Elt = N->getMaskElt(i);
2485 if (Elt >= 0 && Elt != 1)
2490 for (unsigned i = 2; i < 4; ++i) {
2491 int Elt = N->getMaskElt(i);
2492 if (Elt >= 0 && Elt != 3)
2497 // Don't use movshdup if it can be done with a shufps.
2498 // FIXME: verify that matching u, u, 3, 3 is what we want.
2502 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2503 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2504 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2505 if (N->getValueType(0).getVectorNumElements() != 4)
2508 // Expect 0, 0, 2, 2
2509 for (unsigned i = 0; i < 2; ++i)
2510 if (N->getMaskElt(i) > 0)
2514 for (unsigned i = 2; i < 4; ++i) {
2515 int Elt = N->getMaskElt(i);
2516 if (Elt >= 0 && Elt != 2)
2521 // Don't use movsldup if it can be done with a shufps.
2525 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2526 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2527 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2528 int e = N->getValueType(0).getVectorNumElements() / 2;
2530 for (int i = 0; i < e; ++i)
2531 if (!isUndefOrEqual(N->getMaskElt(i), i))
2533 for (int i = 0; i < e; ++i)
2534 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2539 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2540 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2542 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2543 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2544 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2546 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2548 for (int i = 0; i < NumOperands; ++i) {
2549 int Val = SVOp->getMaskElt(NumOperands-i-1);
2550 if (Val < 0) Val = 0;
2551 if (Val >= NumOperands) Val -= NumOperands;
2553 if (i != NumOperands - 1)
2559 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2560 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2562 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2563 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2565 // 8 nodes, but we only care about the last 4.
2566 for (unsigned i = 7; i >= 4; --i) {
2567 int Val = SVOp->getMaskElt(i);
2576 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2577 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2579 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2580 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2582 // 8 nodes, but we only care about the first 4.
2583 for (int i = 3; i >= 0; --i) {
2584 int Val = SVOp->getMaskElt(i);
2593 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2594 /// their permute mask.
2595 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2596 SelectionDAG &DAG) {
2597 MVT VT = SVOp->getValueType(0);
2598 unsigned NumElems = VT.getVectorNumElements();
2599 SmallVector<int, 8> MaskVec;
2601 for (unsigned i = 0; i != NumElems; ++i) {
2602 int idx = SVOp->getMaskElt(i);
2604 MaskVec.push_back(idx);
2605 else if (idx < (int)NumElems)
2606 MaskVec.push_back(idx + NumElems);
2608 MaskVec.push_back(idx - NumElems);
2610 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2611 SVOp->getOperand(0), &MaskVec[0]);
2614 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2615 /// the two vector operands have swapped position.
2616 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, MVT VT) {
2617 unsigned NumElems = VT.getVectorNumElements();
2618 for (unsigned i = 0; i != NumElems; ++i) {
2622 else if (idx < (int)NumElems)
2623 Mask[i] = idx + NumElems;
2625 Mask[i] = idx - NumElems;
2629 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2630 /// match movhlps. The lower half elements should come from upper half of
2631 /// V1 (and in order), and the upper half elements should come from the upper
2632 /// half of V2 (and in order).
2633 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2634 if (Op->getValueType(0).getVectorNumElements() != 4)
2636 for (unsigned i = 0, e = 2; i != e; ++i)
2637 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2639 for (unsigned i = 2; i != 4; ++i)
2640 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2645 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2646 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2648 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2649 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2651 N = N->getOperand(0).getNode();
2652 if (!ISD::isNON_EXTLoad(N))
2655 *LD = cast<LoadSDNode>(N);
2659 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2660 /// match movlp{s|d}. The lower half elements should come from lower half of
2661 /// V1 (and in order), and the upper half elements should come from the upper
2662 /// half of V2 (and in order). And since V1 will become the source of the
2663 /// MOVLP, it must be either a vector load or a scalar load to vector.
2664 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2665 ShuffleVectorSDNode *Op) {
2666 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2668 // Is V2 is a vector load, don't do this transformation. We will try to use
2669 // load folding shufps op.
2670 if (ISD::isNON_EXTLoad(V2))
2673 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2675 if (NumElems != 2 && NumElems != 4)
2677 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2678 if (!isUndefOrEqual(Op->getMaskElt(i), i))
2680 for (unsigned i = NumElems/2; i != NumElems; ++i)
2681 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2686 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2688 static bool isSplatVector(SDNode *N) {
2689 if (N->getOpcode() != ISD::BUILD_VECTOR)
2692 SDValue SplatValue = N->getOperand(0);
2693 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2694 if (N->getOperand(i) != SplatValue)
2699 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2701 static inline bool isZeroNode(SDValue Elt) {
2702 return ((isa<ConstantSDNode>(Elt) &&
2703 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2704 (isa<ConstantFPSDNode>(Elt) &&
2705 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2708 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2709 /// to an zero vector.
2710 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2711 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2712 SDValue V1 = N->getOperand(0);
2713 SDValue V2 = N->getOperand(1);
2714 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2715 for (unsigned i = 0; i != NumElems; ++i) {
2716 int Idx = N->getMaskElt(i);
2717 if (Idx >= (int)NumElems) {
2718 unsigned Opc = V2.getOpcode();
2719 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2721 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V2.getOperand(Idx-NumElems)))
2723 } else if (Idx >= 0) {
2724 unsigned Opc = V1.getOpcode();
2725 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2727 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V1.getOperand(Idx)))
2734 /// getZeroVector - Returns a vector of specified type with all zero elements.
2736 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2738 assert(VT.isVector() && "Expected a vector type");
2740 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2741 // type. This ensures they get CSE'd.
2743 if (VT.getSizeInBits() == 64) { // MMX
2744 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2745 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2746 } else if (HasSSE2) { // SSE2
2747 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2748 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2750 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2751 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2753 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2756 /// getOnesVector - Returns a vector of specified type with all bits set.
2758 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2759 assert(VT.isVector() && "Expected a vector type");
2761 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2762 // type. This ensures they get CSE'd.
2763 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2765 if (VT.getSizeInBits() == 64) // MMX
2766 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2768 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2769 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2773 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2774 /// that point to V2 points to its first element.
2775 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2776 MVT VT = SVOp->getValueType(0);
2777 unsigned NumElems = VT.getVectorNumElements();
2779 bool Changed = false;
2780 SmallVector<int, 8> MaskVec;
2781 SVOp->getMask(MaskVec);
2783 for (unsigned i = 0; i != NumElems; ++i) {
2784 if (MaskVec[i] > (int)NumElems) {
2785 MaskVec[i] = NumElems;
2790 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
2791 SVOp->getOperand(1), &MaskVec[0]);
2792 return SDValue(SVOp, 0);
2795 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2796 /// operation of specified width.
2797 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2799 unsigned NumElems = VT.getVectorNumElements();
2800 SmallVector<int, 8> Mask;
2801 Mask.push_back(NumElems);
2802 for (unsigned i = 1; i != NumElems; ++i)
2804 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2807 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
2808 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2810 unsigned NumElems = VT.getVectorNumElements();
2811 SmallVector<int, 8> Mask;
2812 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2814 Mask.push_back(i + NumElems);
2816 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2819 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
2820 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2822 unsigned NumElems = VT.getVectorNumElements();
2823 unsigned Half = NumElems/2;
2824 SmallVector<int, 8> Mask;
2825 for (unsigned i = 0; i != Half; ++i) {
2826 Mask.push_back(i + Half);
2827 Mask.push_back(i + NumElems + Half);
2829 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2832 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2833 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
2835 if (SV->getValueType(0).getVectorNumElements() <= 4)
2836 return SDValue(SV, 0);
2838 MVT PVT = MVT::v4f32;
2839 MVT VT = SV->getValueType(0);
2840 DebugLoc dl = SV->getDebugLoc();
2841 SDValue V1 = SV->getOperand(0);
2842 int NumElems = VT.getVectorNumElements();
2843 int EltNo = SV->getSplatIndex();
2845 // unpack elements to the correct location
2846 while (NumElems > 4) {
2847 if (EltNo < NumElems/2) {
2848 V1 = getUnpackl(DAG, dl, VT, V1, V1);
2850 V1 = getUnpackh(DAG, dl, VT, V1, V1);
2851 EltNo -= NumElems/2;
2856 // Perform the splat.
2857 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
2858 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
2859 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
2860 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
2863 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2864 /// vector of zero or undef vector. This produces a shuffle where the low
2865 /// element of V2 is swizzled into the zero/undef vector, landing at element
2866 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2867 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2868 bool isZero, bool HasSSE2,
2869 SelectionDAG &DAG) {
2870 MVT VT = V2.getValueType();
2872 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
2873 unsigned NumElems = VT.getVectorNumElements();
2874 SmallVector<int, 16> MaskVec;
2875 for (unsigned i = 0; i != NumElems; ++i)
2876 // If this is the insertion idx, put the low elt of V2 here.
2877 MaskVec.push_back(i == Idx ? NumElems : i);
2878 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
2881 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2882 /// a shuffle that is zero.
2884 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
2885 bool Low, SelectionDAG &DAG) {
2886 unsigned NumZeros = 0;
2887 for (int i = 0; i < NumElems; ++i) {
2888 unsigned Index = Low ? i : NumElems-i-1;
2889 int Idx = SVOp->getMaskElt(Index);
2894 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
2895 if (Elt.getNode() && isZeroNode(Elt))
2903 /// isVectorShift - Returns true if the shuffle can be implemented as a
2904 /// logical left or right shift of a vector.
2905 /// FIXME: split into pslldqi, psrldqi, palignr variants.
2906 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
2907 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
2908 int NumElems = SVOp->getValueType(0).getVectorNumElements();
2911 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
2914 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
2918 bool SeenV1 = false;
2919 bool SeenV2 = false;
2920 for (int i = NumZeros; i < NumElems; ++i) {
2921 int Val = isLeft ? (i - NumZeros) : i;
2922 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
2934 if (SeenV1 && SeenV2)
2937 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
2943 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2945 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
2946 unsigned NumNonZero, unsigned NumZero,
2947 SelectionDAG &DAG, TargetLowering &TLI) {
2951 DebugLoc dl = Op.getDebugLoc();
2954 for (unsigned i = 0; i < 16; ++i) {
2955 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2956 if (ThisIsNonZero && First) {
2958 V = getZeroVector(MVT::v8i16, true, DAG, dl);
2960 V = DAG.getUNDEF(MVT::v8i16);
2965 SDValue ThisElt(0, 0), LastElt(0, 0);
2966 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2967 if (LastIsNonZero) {
2968 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
2969 MVT::i16, Op.getOperand(i-1));
2971 if (ThisIsNonZero) {
2972 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
2973 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
2974 ThisElt, DAG.getConstant(8, MVT::i8));
2976 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
2980 if (ThisElt.getNode())
2981 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
2982 DAG.getIntPtrConstant(i/2));
2986 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
2989 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2991 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
2992 unsigned NumNonZero, unsigned NumZero,
2993 SelectionDAG &DAG, TargetLowering &TLI) {
2997 DebugLoc dl = Op.getDebugLoc();
3000 for (unsigned i = 0; i < 8; ++i) {
3001 bool isNonZero = (NonZeros & (1 << i)) != 0;
3005 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3007 V = DAG.getUNDEF(MVT::v8i16);
3010 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3011 MVT::v8i16, V, Op.getOperand(i),
3012 DAG.getIntPtrConstant(i));
3019 /// getVShift - Return a vector logical shift node.
3021 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3022 unsigned NumBits, SelectionDAG &DAG,
3023 const TargetLowering &TLI, DebugLoc dl) {
3024 bool isMMX = VT.getSizeInBits() == 64;
3025 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3026 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3027 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3028 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3029 DAG.getNode(Opc, dl, ShVT, SrcOp,
3030 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3034 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3035 DebugLoc dl = Op.getDebugLoc();
3036 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3037 if (ISD::isBuildVectorAllZeros(Op.getNode())
3038 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3039 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3040 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3041 // eliminated on x86-32 hosts.
3042 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3045 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3046 return getOnesVector(Op.getValueType(), DAG, dl);
3047 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3050 MVT VT = Op.getValueType();
3051 MVT EVT = VT.getVectorElementType();
3052 unsigned EVTBits = EVT.getSizeInBits();
3054 unsigned NumElems = Op.getNumOperands();
3055 unsigned NumZero = 0;
3056 unsigned NumNonZero = 0;
3057 unsigned NonZeros = 0;
3058 bool IsAllConstants = true;
3059 SmallSet<SDValue, 8> Values;
3060 for (unsigned i = 0; i < NumElems; ++i) {
3061 SDValue Elt = Op.getOperand(i);
3062 if (Elt.getOpcode() == ISD::UNDEF)
3065 if (Elt.getOpcode() != ISD::Constant &&
3066 Elt.getOpcode() != ISD::ConstantFP)
3067 IsAllConstants = false;
3068 if (isZeroNode(Elt))
3071 NonZeros |= (1 << i);
3076 if (NumNonZero == 0) {
3077 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3078 return DAG.getUNDEF(VT);
3081 // Special case for single non-zero, non-undef, element.
3082 if (NumNonZero == 1) {
3083 unsigned Idx = CountTrailingZeros_32(NonZeros);
3084 SDValue Item = Op.getOperand(Idx);
3086 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3087 // the value are obviously zero, truncate the value to i32 and do the
3088 // insertion that way. Only do this if the value is non-constant or if the
3089 // value is a constant being inserted into element 0. It is cheaper to do
3090 // a constant pool load than it is to do a movd + shuffle.
3091 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3092 (!IsAllConstants || Idx == 0)) {
3093 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3094 // Handle MMX and SSE both.
3095 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3096 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3098 // Truncate the value (which may itself be a constant) to i32, and
3099 // convert it to a vector with movd (S2V+shuffle to zero extend).
3100 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3101 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3102 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3103 Subtarget->hasSSE2(), DAG);
3105 // Now we have our 32-bit value zero extended in the low element of
3106 // a vector. If Idx != 0, swizzle it into place.
3108 SmallVector<int, 4> Mask;
3109 Mask.push_back(Idx);
3110 for (unsigned i = 1; i != VecElts; ++i)
3112 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3113 DAG.getUNDEF(Item.getValueType()),
3116 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3120 // If we have a constant or non-constant insertion into the low element of
3121 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3122 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3123 // depending on what the source datatype is.
3126 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3127 } else if (EVT == MVT::i32 || EVT == MVT::f32 || EVT == MVT::f64 ||
3128 (EVT == MVT::i64 && Subtarget->is64Bit())) {
3129 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3130 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3131 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3133 } else if (EVT == MVT::i16 || EVT == MVT::i8) {
3134 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3135 MVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3136 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3137 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3138 Subtarget->hasSSE2(), DAG);
3139 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3143 // Is it a vector logical left shift?
3144 if (NumElems == 2 && Idx == 1 &&
3145 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3146 unsigned NumBits = VT.getSizeInBits();
3147 return getVShift(true, VT,
3148 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3149 VT, Op.getOperand(1)),
3150 NumBits/2, DAG, *this, dl);
3153 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3156 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3157 // is a non-constant being inserted into an element other than the low one,
3158 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3159 // movd/movss) to move this into the low element, then shuffle it into
3161 if (EVTBits == 32) {
3162 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3164 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3165 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3166 Subtarget->hasSSE2(), DAG);
3167 SmallVector<int, 8> MaskVec;
3168 for (unsigned i = 0; i < NumElems; i++)
3169 MaskVec.push_back(i == Idx ? 0 : 1);
3170 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3174 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3175 if (Values.size() == 1)
3178 // A vector full of immediates; various special cases are already
3179 // handled, so this is best done with a single constant-pool load.
3183 // Let legalizer expand 2-wide build_vectors.
3184 if (EVTBits == 64) {
3185 if (NumNonZero == 1) {
3186 // One half is zero or undef.
3187 unsigned Idx = CountTrailingZeros_32(NonZeros);
3188 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3189 Op.getOperand(Idx));
3190 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3191 Subtarget->hasSSE2(), DAG);
3196 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3197 if (EVTBits == 8 && NumElems == 16) {
3198 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3200 if (V.getNode()) return V;
3203 if (EVTBits == 16 && NumElems == 8) {
3204 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3206 if (V.getNode()) return V;
3209 // If element VT is == 32 bits, turn it into a number of shuffles.
3210 SmallVector<SDValue, 8> V;
3212 if (NumElems == 4 && NumZero > 0) {
3213 for (unsigned i = 0; i < 4; ++i) {
3214 bool isZero = !(NonZeros & (1 << i));
3216 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3218 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3221 for (unsigned i = 0; i < 2; ++i) {
3222 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3225 V[i] = V[i*2]; // Must be a zero vector.
3228 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3231 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3234 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3239 SmallVector<int, 8> MaskVec;
3240 bool Reverse = (NonZeros & 0x3) == 2;
3241 for (unsigned i = 0; i < 2; ++i)
3242 MaskVec.push_back(Reverse ? 1-i : i);
3243 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3244 for (unsigned i = 0; i < 2; ++i)
3245 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3246 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3249 if (Values.size() > 2) {
3250 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3251 // values to be inserted is equal to the number of elements, in which case
3252 // use the unpack code below in the hopes of matching the consecutive elts
3253 // load merge pattern for shuffles.
3254 // FIXME: We could probably just check that here directly.
3255 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3256 getSubtarget()->hasSSE41()) {
3257 V[0] = DAG.getUNDEF(VT);
3258 for (unsigned i = 0; i < NumElems; ++i)
3259 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3260 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3261 Op.getOperand(i), DAG.getIntPtrConstant(i));
3264 // Expand into a number of unpckl*.
3266 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3267 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3268 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3269 for (unsigned i = 0; i < NumElems; ++i)
3270 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3272 while (NumElems != 0) {
3273 for (unsigned i = 0; i < NumElems; ++i)
3274 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3283 // v8i16 shuffles - Prefer shuffles in the following order:
3284 // 1. [all] pshuflw, pshufhw, optional move
3285 // 2. [ssse3] 1 x pshufb
3286 // 3. [ssse3] 2 x pshufb + 1 x por
3287 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3289 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3290 SelectionDAG &DAG, X86TargetLowering &TLI) {
3291 SDValue V1 = SVOp->getOperand(0);
3292 SDValue V2 = SVOp->getOperand(1);
3293 DebugLoc dl = SVOp->getDebugLoc();
3294 SmallVector<int, 8> MaskVals;
3296 // Determine if more than 1 of the words in each of the low and high quadwords
3297 // of the result come from the same quadword of one of the two inputs. Undef
3298 // mask values count as coming from any quadword, for better codegen.
3299 SmallVector<unsigned, 4> LoQuad(4);
3300 SmallVector<unsigned, 4> HiQuad(4);
3301 BitVector InputQuads(4);
3302 for (unsigned i = 0; i < 8; ++i) {
3303 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3304 int EltIdx = SVOp->getMaskElt(i);
3305 MaskVals.push_back(EltIdx);
3314 InputQuads.set(EltIdx / 4);
3317 int BestLoQuad = -1;
3318 unsigned MaxQuad = 1;
3319 for (unsigned i = 0; i < 4; ++i) {
3320 if (LoQuad[i] > MaxQuad) {
3322 MaxQuad = LoQuad[i];
3326 int BestHiQuad = -1;
3328 for (unsigned i = 0; i < 4; ++i) {
3329 if (HiQuad[i] > MaxQuad) {
3331 MaxQuad = HiQuad[i];
3335 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3336 // of the two input vectors, shuffle them into one input vector so only a
3337 // single pshufb instruction is necessary. If There are more than 2 input
3338 // quads, disable the next transformation since it does not help SSSE3.
3339 bool V1Used = InputQuads[0] || InputQuads[1];
3340 bool V2Used = InputQuads[2] || InputQuads[3];
3341 if (TLI.getSubtarget()->hasSSSE3()) {
3342 if (InputQuads.count() == 2 && V1Used && V2Used) {
3343 BestLoQuad = InputQuads.find_first();
3344 BestHiQuad = InputQuads.find_next(BestLoQuad);
3346 if (InputQuads.count() > 2) {
3352 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3353 // the shuffle mask. If a quad is scored as -1, that means that it contains
3354 // words from all 4 input quadwords.
3356 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3357 SmallVector<int, 8> MaskV;
3358 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3359 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3360 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3361 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3362 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3363 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3365 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3366 // source words for the shuffle, to aid later transformations.
3367 bool AllWordsInNewV = true;
3368 bool InOrder[2] = { true, true };
3369 for (unsigned i = 0; i != 8; ++i) {
3370 int idx = MaskVals[i];
3372 InOrder[i/4] = false;
3373 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3375 AllWordsInNewV = false;
3379 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3380 if (AllWordsInNewV) {
3381 for (int i = 0; i != 8; ++i) {
3382 int idx = MaskVals[i];
3385 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3386 if ((idx != i) && idx < 4)
3388 if ((idx != i) && idx > 3)
3397 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3398 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3399 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3400 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3401 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3405 // If we have SSSE3, and all words of the result are from 1 input vector,
3406 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3407 // is present, fall back to case 4.
3408 if (TLI.getSubtarget()->hasSSSE3()) {
3409 SmallVector<SDValue,16> pshufbMask;
3411 // If we have elements from both input vectors, set the high bit of the
3412 // shuffle mask element to zero out elements that come from V2 in the V1
3413 // mask, and elements that come from V1 in the V2 mask, so that the two
3414 // results can be OR'd together.
3415 bool TwoInputs = V1Used && V2Used;
3416 for (unsigned i = 0; i != 8; ++i) {
3417 int EltIdx = MaskVals[i] * 2;
3418 if (TwoInputs && (EltIdx >= 16)) {
3419 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3420 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3423 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3424 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3426 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3427 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3428 DAG.getNode(ISD::BUILD_VECTOR, dl,
3429 MVT::v16i8, &pshufbMask[0], 16));
3431 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3433 // Calculate the shuffle mask for the second input, shuffle it, and
3434 // OR it with the first shuffled input.
3436 for (unsigned i = 0; i != 8; ++i) {
3437 int EltIdx = MaskVals[i] * 2;
3439 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3440 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3443 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3444 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3446 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3447 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3448 DAG.getNode(ISD::BUILD_VECTOR, dl,
3449 MVT::v16i8, &pshufbMask[0], 16));
3450 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3451 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3454 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3455 // and update MaskVals with new element order.
3456 BitVector InOrder(8);
3457 if (BestLoQuad >= 0) {
3458 SmallVector<int, 8> MaskV;
3459 for (int i = 0; i != 4; ++i) {
3460 int idx = MaskVals[i];
3462 MaskV.push_back(-1);
3464 } else if ((idx / 4) == BestLoQuad) {
3465 MaskV.push_back(idx & 3);
3468 MaskV.push_back(-1);
3471 for (unsigned i = 4; i != 8; ++i)
3473 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3477 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3478 // and update MaskVals with the new element order.
3479 if (BestHiQuad >= 0) {
3480 SmallVector<int, 8> MaskV;
3481 for (unsigned i = 0; i != 4; ++i)
3483 for (unsigned i = 4; i != 8; ++i) {
3484 int idx = MaskVals[i];
3486 MaskV.push_back(-1);
3488 } else if ((idx / 4) == BestHiQuad) {
3489 MaskV.push_back((idx & 3) + 4);
3492 MaskV.push_back(-1);
3495 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3499 // In case BestHi & BestLo were both -1, which means each quadword has a word
3500 // from each of the four input quadwords, calculate the InOrder bitvector now
3501 // before falling through to the insert/extract cleanup.
3502 if (BestLoQuad == -1 && BestHiQuad == -1) {
3504 for (int i = 0; i != 8; ++i)
3505 if (MaskVals[i] < 0 || MaskVals[i] == i)
3509 // The other elements are put in the right place using pextrw and pinsrw.
3510 for (unsigned i = 0; i != 8; ++i) {
3513 int EltIdx = MaskVals[i];
3516 SDValue ExtOp = (EltIdx < 8)
3517 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3518 DAG.getIntPtrConstant(EltIdx))
3519 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3520 DAG.getIntPtrConstant(EltIdx - 8));
3521 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3522 DAG.getIntPtrConstant(i));
3527 // v16i8 shuffles - Prefer shuffles in the following order:
3528 // 1. [ssse3] 1 x pshufb
3529 // 2. [ssse3] 2 x pshufb + 1 x por
3530 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3532 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3533 SelectionDAG &DAG, X86TargetLowering &TLI) {
3534 SDValue V1 = SVOp->getOperand(0);
3535 SDValue V2 = SVOp->getOperand(1);
3536 DebugLoc dl = SVOp->getDebugLoc();
3537 SmallVector<int, 16> MaskVals;
3538 SVOp->getMask(MaskVals);
3540 // If we have SSSE3, case 1 is generated when all result bytes come from
3541 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3542 // present, fall back to case 3.
3543 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3546 for (unsigned i = 0; i < 16; ++i) {
3547 int EltIdx = MaskVals[i];
3556 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3557 if (TLI.getSubtarget()->hasSSSE3()) {
3558 SmallVector<SDValue,16> pshufbMask;
3560 // If all result elements are from one input vector, then only translate
3561 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3563 // Otherwise, we have elements from both input vectors, and must zero out
3564 // elements that come from V2 in the first mask, and V1 in the second mask
3565 // so that we can OR them together.
3566 bool TwoInputs = !(V1Only || V2Only);
3567 for (unsigned i = 0; i != 16; ++i) {
3568 int EltIdx = MaskVals[i];
3569 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3570 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3573 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3575 // If all the elements are from V2, assign it to V1 and return after
3576 // building the first pshufb.
3579 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3580 DAG.getNode(ISD::BUILD_VECTOR, dl,
3581 MVT::v16i8, &pshufbMask[0], 16));
3585 // Calculate the shuffle mask for the second input, shuffle it, and
3586 // OR it with the first shuffled input.
3588 for (unsigned i = 0; i != 16; ++i) {
3589 int EltIdx = MaskVals[i];
3591 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3594 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3596 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3597 DAG.getNode(ISD::BUILD_VECTOR, dl,
3598 MVT::v16i8, &pshufbMask[0], 16));
3599 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3602 // No SSSE3 - Calculate in place words and then fix all out of place words
3603 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3604 // the 16 different words that comprise the two doublequadword input vectors.
3605 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3606 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3607 SDValue NewV = V2Only ? V2 : V1;
3608 for (int i = 0; i != 8; ++i) {
3609 int Elt0 = MaskVals[i*2];
3610 int Elt1 = MaskVals[i*2+1];
3612 // This word of the result is all undef, skip it.
3613 if (Elt0 < 0 && Elt1 < 0)
3616 // This word of the result is already in the correct place, skip it.
3617 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3619 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3622 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3623 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3626 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3627 // using a single extract together, load it and store it.
3628 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3629 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3630 DAG.getIntPtrConstant(Elt1 / 2));
3631 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3632 DAG.getIntPtrConstant(i));
3636 // If Elt1 is defined, extract it from the appropriate source. If the
3637 // source byte is not also odd, shift the extracted word left 8 bits
3638 // otherwise clear the bottom 8 bits if we need to do an or.
3640 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3641 DAG.getIntPtrConstant(Elt1 / 2));
3642 if ((Elt1 & 1) == 0)
3643 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3644 DAG.getConstant(8, TLI.getShiftAmountTy()));
3646 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3647 DAG.getConstant(0xFF00, MVT::i16));
3649 // If Elt0 is defined, extract it from the appropriate source. If the
3650 // source byte is not also even, shift the extracted word right 8 bits. If
3651 // Elt1 was also defined, OR the extracted values together before
3652 // inserting them in the result.
3654 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3655 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3656 if ((Elt0 & 1) != 0)
3657 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3658 DAG.getConstant(8, TLI.getShiftAmountTy()));
3660 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3661 DAG.getConstant(0x00FF, MVT::i16));
3662 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3665 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3666 DAG.getIntPtrConstant(i));
3668 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3671 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3672 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3673 /// done when every pair / quad of shuffle mask elements point to elements in
3674 /// the right sequence. e.g.
3675 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3677 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3679 TargetLowering &TLI, DebugLoc dl) {
3680 MVT VT = SVOp->getValueType(0);
3681 SDValue V1 = SVOp->getOperand(0);
3682 SDValue V2 = SVOp->getOperand(1);
3683 unsigned NumElems = VT.getVectorNumElements();
3684 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3685 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3686 MVT MaskEltVT = MaskVT.getVectorElementType();
3688 switch (VT.getSimpleVT()) {
3689 default: assert(false && "Unexpected!");
3690 case MVT::v4f32: NewVT = MVT::v2f64; break;
3691 case MVT::v4i32: NewVT = MVT::v2i64; break;
3692 case MVT::v8i16: NewVT = MVT::v4i32; break;
3693 case MVT::v16i8: NewVT = MVT::v4i32; break;
3696 if (NewWidth == 2) {
3702 int Scale = NumElems / NewWidth;
3703 SmallVector<int, 8> MaskVec;
3704 for (unsigned i = 0; i < NumElems; i += Scale) {
3706 for (int j = 0; j < Scale; ++j) {
3707 int EltIdx = SVOp->getMaskElt(i+j);
3711 StartIdx = EltIdx - (EltIdx % Scale);
3712 if (EltIdx != StartIdx + j)
3716 MaskVec.push_back(-1);
3718 MaskVec.push_back(StartIdx / Scale);
3721 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3722 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3723 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3726 /// getVZextMovL - Return a zero-extending vector move low node.
3728 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3729 SDValue SrcOp, SelectionDAG &DAG,
3730 const X86Subtarget *Subtarget, DebugLoc dl) {
3731 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3732 LoadSDNode *LD = NULL;
3733 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3734 LD = dyn_cast<LoadSDNode>(SrcOp);
3736 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3738 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3739 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3740 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3741 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3742 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3744 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3745 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3746 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3747 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3755 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3756 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3757 DAG.getNode(ISD::BIT_CONVERT, dl,
3761 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3764 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3765 SDValue V1 = SVOp->getOperand(0);
3766 SDValue V2 = SVOp->getOperand(1);
3767 DebugLoc dl = SVOp->getDebugLoc();
3768 MVT VT = SVOp->getValueType(0);
3770 SmallVector<std::pair<int, int>, 8> Locs;
3772 SmallVector<int, 8> Mask1(4U, -1);
3773 SmallVector<int, 8> PermMask;
3774 SVOp->getMask(PermMask);
3778 for (unsigned i = 0; i != 4; ++i) {
3779 int Idx = PermMask[i];
3781 Locs[i] = std::make_pair(-1, -1);
3783 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3785 Locs[i] = std::make_pair(0, NumLo);
3789 Locs[i] = std::make_pair(1, NumHi);
3791 Mask1[2+NumHi] = Idx;
3797 if (NumLo <= 2 && NumHi <= 2) {
3798 // If no more than two elements come from either vector. This can be
3799 // implemented with two shuffles. First shuffle gather the elements.
3800 // The second shuffle, which takes the first shuffle as both of its
3801 // vector operands, put the elements into the right order.
3802 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3804 SmallVector<int, 8> Mask2(4U, -1);
3806 for (unsigned i = 0; i != 4; ++i) {
3807 if (Locs[i].first == -1)
3810 unsigned Idx = (i < 2) ? 0 : 4;
3811 Idx += Locs[i].first * 2 + Locs[i].second;
3816 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
3817 } else if (NumLo == 3 || NumHi == 3) {
3818 // Otherwise, we must have three elements from one vector, call it X, and
3819 // one element from the other, call it Y. First, use a shufps to build an
3820 // intermediate vector with the one element from Y and the element from X
3821 // that will be in the same half in the final destination (the indexes don't
3822 // matter). Then, use a shufps to build the final vector, taking the half
3823 // containing the element from Y from the intermediate, and the other half
3826 // Normalize it so the 3 elements come from V1.
3827 CommuteVectorShuffleMask(PermMask, VT);
3831 // Find the element from V2.
3833 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3834 int Val = PermMask[HiIndex];
3841 Mask1[0] = PermMask[HiIndex];
3843 Mask1[2] = PermMask[HiIndex^1];
3845 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3848 Mask1[0] = PermMask[0];
3849 Mask1[1] = PermMask[1];
3850 Mask1[2] = HiIndex & 1 ? 6 : 4;
3851 Mask1[3] = HiIndex & 1 ? 4 : 6;
3852 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3854 Mask1[0] = HiIndex & 1 ? 2 : 0;
3855 Mask1[1] = HiIndex & 1 ? 0 : 2;
3856 Mask1[2] = PermMask[2];
3857 Mask1[3] = PermMask[3];
3862 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
3866 // Break it into (shuffle shuffle_hi, shuffle_lo).
3868 SmallVector<int,8> LoMask(4U, -1);
3869 SmallVector<int,8> HiMask(4U, -1);
3871 SmallVector<int,8> *MaskPtr = &LoMask;
3872 unsigned MaskIdx = 0;
3875 for (unsigned i = 0; i != 4; ++i) {
3882 int Idx = PermMask[i];
3884 Locs[i] = std::make_pair(-1, -1);
3885 } else if (Idx < 4) {
3886 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3887 (*MaskPtr)[LoIdx] = Idx;
3890 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3891 (*MaskPtr)[HiIdx] = Idx;
3896 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
3897 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
3898 SmallVector<int, 8> MaskOps;
3899 for (unsigned i = 0; i != 4; ++i) {
3900 if (Locs[i].first == -1) {
3901 MaskOps.push_back(-1);
3903 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3904 MaskOps.push_back(Idx);
3907 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
3911 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3912 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
3913 SDValue V1 = Op.getOperand(0);
3914 SDValue V2 = Op.getOperand(1);
3915 MVT VT = Op.getValueType();
3916 DebugLoc dl = Op.getDebugLoc();
3917 unsigned NumElems = VT.getVectorNumElements();
3918 bool isMMX = VT.getSizeInBits() == 64;
3919 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3920 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3921 bool V1IsSplat = false;
3922 bool V2IsSplat = false;
3924 if (isZeroShuffle(SVOp))
3925 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3927 // Promote splats to v4f32.
3928 if (SVOp->isSplat()) {
3929 if (isMMX || NumElems < 4)
3931 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
3934 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3936 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3937 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3938 if (NewOp.getNode())
3939 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3940 LowerVECTOR_SHUFFLE(NewOp, DAG));
3941 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3942 // FIXME: Figure out a cleaner way to do this.
3943 // Try to make use of movq to zero out the top part.
3944 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
3945 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3946 if (NewOp.getNode()) {
3947 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
3948 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
3949 DAG, Subtarget, dl);
3951 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
3952 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3953 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
3954 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3955 DAG, Subtarget, dl);
3959 if (X86::isPSHUFDMask(SVOp))
3962 // Check if this can be converted into a logical shift.
3963 bool isLeft = false;
3966 bool isShift = getSubtarget()->hasSSE2() &&
3967 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
3968 if (isShift && ShVal.hasOneUse()) {
3969 // If the shifted value has multiple uses, it may be cheaper to use
3970 // v_set0 + movlhps or movhlps, etc.
3971 MVT EVT = VT.getVectorElementType();
3972 ShAmt *= EVT.getSizeInBits();
3973 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
3976 if (X86::isMOVLMask(SVOp)) {
3979 if (ISD::isBuildVectorAllZeros(V1.getNode()))
3980 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
3985 // FIXME: fold these into legal mask.
3986 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
3987 X86::isMOVSLDUPMask(SVOp) ||
3988 X86::isMOVHLPSMask(SVOp) ||
3989 X86::isMOVHPMask(SVOp) ||
3990 X86::isMOVLPMask(SVOp)))
3993 if (ShouldXformToMOVHLPS(SVOp) ||
3994 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
3995 return CommuteVectorShuffle(SVOp, DAG);
3998 // No better options. Use a vshl / vsrl.
3999 MVT EVT = VT.getVectorElementType();
4000 ShAmt *= EVT.getSizeInBits();
4001 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4004 bool Commuted = false;
4005 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4006 // 1,1,1,1 -> v8i16 though.
4007 V1IsSplat = isSplatVector(V1.getNode());
4008 V2IsSplat = isSplatVector(V2.getNode());
4010 // Canonicalize the splat or undef, if present, to be on the RHS.
4011 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4012 Op = CommuteVectorShuffle(SVOp, DAG);
4013 SVOp = cast<ShuffleVectorSDNode>(Op);
4014 V1 = SVOp->getOperand(0);
4015 V2 = SVOp->getOperand(1);
4016 std::swap(V1IsSplat, V2IsSplat);
4017 std::swap(V1IsUndef, V2IsUndef);
4021 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4022 // Shuffling low element of v1 into undef, just return v1.
4025 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4026 // the instruction selector will not match, so get a canonical MOVL with
4027 // swapped operands to undo the commute.
4028 return getMOVL(DAG, dl, VT, V2, V1);
4031 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4032 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4033 X86::isUNPCKLMask(SVOp) ||
4034 X86::isUNPCKHMask(SVOp))
4038 // Normalize mask so all entries that point to V2 points to its first
4039 // element then try to match unpck{h|l} again. If match, return a
4040 // new vector_shuffle with the corrected mask.
4041 SDValue NewMask = NormalizeMask(SVOp, DAG);
4042 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4043 if (NSVOp != SVOp) {
4044 if (X86::isUNPCKLMask(NSVOp, true)) {
4046 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4053 // Commute is back and try unpck* again.
4054 // FIXME: this seems wrong.
4055 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4056 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4057 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4058 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4059 X86::isUNPCKLMask(NewSVOp) ||
4060 X86::isUNPCKHMask(NewSVOp))
4064 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4066 // Normalize the node to match x86 shuffle ops if needed
4067 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4068 return CommuteVectorShuffle(SVOp, DAG);
4070 // Check for legal shuffle and return?
4071 SmallVector<int, 16> PermMask;
4072 SVOp->getMask(PermMask);
4073 if (isShuffleMaskLegal(PermMask, VT))
4076 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4077 if (VT == MVT::v8i16) {
4078 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4079 if (NewOp.getNode())
4083 if (VT == MVT::v16i8) {
4084 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4085 if (NewOp.getNode())
4089 // Handle all 4 wide cases with a number of shuffles except for MMX.
4090 if (NumElems == 4 && !isMMX)
4091 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4097 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4098 SelectionDAG &DAG) {
4099 MVT VT = Op.getValueType();
4100 DebugLoc dl = Op.getDebugLoc();
4101 if (VT.getSizeInBits() == 8) {
4102 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4103 Op.getOperand(0), Op.getOperand(1));
4104 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4105 DAG.getValueType(VT));
4106 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4107 } else if (VT.getSizeInBits() == 16) {
4108 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4109 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4111 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4112 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4113 DAG.getNode(ISD::BIT_CONVERT, dl,
4117 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4118 Op.getOperand(0), Op.getOperand(1));
4119 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4120 DAG.getValueType(VT));
4121 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4122 } else if (VT == MVT::f32) {
4123 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4124 // the result back to FR32 register. It's only worth matching if the
4125 // result has a single use which is a store or a bitcast to i32. And in
4126 // the case of a store, it's not worth it if the index is a constant 0,
4127 // because a MOVSSmr can be used instead, which is smaller and faster.
4128 if (!Op.hasOneUse())
4130 SDNode *User = *Op.getNode()->use_begin();
4131 if ((User->getOpcode() != ISD::STORE ||
4132 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4133 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4134 (User->getOpcode() != ISD::BIT_CONVERT ||
4135 User->getValueType(0) != MVT::i32))
4137 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4138 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4141 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4142 } else if (VT == MVT::i32) {
4143 // ExtractPS works with constant index.
4144 if (isa<ConstantSDNode>(Op.getOperand(1)))
4152 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4153 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4156 if (Subtarget->hasSSE41()) {
4157 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4162 MVT VT = Op.getValueType();
4163 DebugLoc dl = Op.getDebugLoc();
4164 // TODO: handle v16i8.
4165 if (VT.getSizeInBits() == 16) {
4166 SDValue Vec = Op.getOperand(0);
4167 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4169 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4170 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4171 DAG.getNode(ISD::BIT_CONVERT, dl,
4174 // Transform it so it match pextrw which produces a 32-bit result.
4175 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4176 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4177 Op.getOperand(0), Op.getOperand(1));
4178 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4179 DAG.getValueType(VT));
4180 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4181 } else if (VT.getSizeInBits() == 32) {
4182 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4186 // SHUFPS the element to the lowest double word, then movss.
4187 int Mask[4] = { Idx, -1, -1, -1 };
4188 MVT VVT = Op.getOperand(0).getValueType();
4189 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4190 DAG.getUNDEF(VVT), Mask);
4191 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4192 DAG.getIntPtrConstant(0));
4193 } else if (VT.getSizeInBits() == 64) {
4194 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4195 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4196 // to match extract_elt for f64.
4197 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4201 // UNPCKHPD the element to the lowest double word, then movsd.
4202 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4203 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4204 int Mask[2] = { 1, -1 };
4205 MVT VVT = Op.getOperand(0).getValueType();
4206 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4207 DAG.getUNDEF(VVT), Mask);
4208 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4209 DAG.getIntPtrConstant(0));
4216 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4217 MVT VT = Op.getValueType();
4218 MVT EVT = VT.getVectorElementType();
4219 DebugLoc dl = Op.getDebugLoc();
4221 SDValue N0 = Op.getOperand(0);
4222 SDValue N1 = Op.getOperand(1);
4223 SDValue N2 = Op.getOperand(2);
4225 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4226 isa<ConstantSDNode>(N2)) {
4227 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4229 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4231 if (N1.getValueType() != MVT::i32)
4232 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4233 if (N2.getValueType() != MVT::i32)
4234 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4235 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4236 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4237 // Bits [7:6] of the constant are the source select. This will always be
4238 // zero here. The DAG Combiner may combine an extract_elt index into these
4239 // bits. For example (insert (extract, 3), 2) could be matched by putting
4240 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4241 // Bits [5:4] of the constant are the destination select. This is the
4242 // value of the incoming immediate.
4243 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4244 // combine either bitwise AND or insert of float 0.0 to set these bits.
4245 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4246 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4247 } else if (EVT == MVT::i32) {
4248 // InsertPS works with constant index.
4249 if (isa<ConstantSDNode>(N2))
4256 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4257 MVT VT = Op.getValueType();
4258 MVT EVT = VT.getVectorElementType();
4260 if (Subtarget->hasSSE41())
4261 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4266 DebugLoc dl = Op.getDebugLoc();
4267 SDValue N0 = Op.getOperand(0);
4268 SDValue N1 = Op.getOperand(1);
4269 SDValue N2 = Op.getOperand(2);
4271 if (EVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4272 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4273 // as its second argument.
4274 if (N1.getValueType() != MVT::i32)
4275 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4276 if (N2.getValueType() != MVT::i32)
4277 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4278 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4284 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4285 DebugLoc dl = Op.getDebugLoc();
4286 if (Op.getValueType() == MVT::v2f32)
4287 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4288 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4289 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4290 Op.getOperand(0))));
4292 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4293 MVT VT = MVT::v2i32;
4294 switch (Op.getValueType().getSimpleVT()) {
4301 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4302 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4305 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4306 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4307 // one of the above mentioned nodes. It has to be wrapped because otherwise
4308 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4309 // be used to form addressing mode. These wrapped nodes will be selected
4312 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4313 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4314 // FIXME there isn't really any debug info here, should come from the parent
4315 DebugLoc dl = CP->getDebugLoc();
4316 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4317 CP->getAlignment());
4318 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4319 // With PIC, the address is actually $g + Offset.
4320 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4321 !Subtarget->isPICStyleRIPRel()) {
4322 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4323 DAG.getNode(X86ISD::GlobalBaseReg,
4324 DebugLoc::getUnknownLoc(),
4333 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4335 SelectionDAG &DAG) const {
4336 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4337 bool ExtraLoadRequired =
4338 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4340 // Create the TargetGlobalAddress node, folding in the constant
4341 // offset if it is legal.
4343 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4344 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4347 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4348 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4350 // With PIC, the address is actually $g + Offset.
4351 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4352 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4353 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4357 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4358 // load the value at address GV, not the value of GV itself. This means that
4359 // the GlobalAddress must be in the base or index register of the address, not
4360 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4361 // The same applies for external symbols during PIC codegen
4362 if (ExtraLoadRequired)
4363 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4364 PseudoSourceValue::getGOT(), 0);
4366 // If there was a non-zero offset that we didn't fold, create an explicit
4369 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4370 DAG.getConstant(Offset, getPointerTy()));
4376 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4377 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4378 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4379 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4383 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4384 SDValue *InFlag, const MVT PtrVT, unsigned ReturnReg) {
4385 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4386 DebugLoc dl = GA->getDebugLoc();
4387 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4388 GA->getValueType(0),
4391 SDValue Ops[] = { Chain, TGA, *InFlag };
4392 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4394 SDValue Ops[] = { Chain, TGA };
4395 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4397 SDValue Flag = Chain.getValue(1);
4398 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4401 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4403 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4406 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4407 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4408 DAG.getNode(X86ISD::GlobalBaseReg,
4409 DebugLoc::getUnknownLoc(),
4411 InFlag = Chain.getValue(1);
4413 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX);
4416 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4418 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4420 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX);
4423 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4424 // "local exec" model.
4425 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4426 const MVT PtrVT, TLSModel::Model model,
4428 DebugLoc dl = GA->getDebugLoc();
4429 // Get the Thread Pointer
4430 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4431 DebugLoc::getUnknownLoc(), PtrVT,
4432 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4435 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4438 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4440 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4442 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
4444 if (model == TLSModel::InitialExec)
4445 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4446 PseudoSourceValue::getGOT(), 0);
4448 // The address of the thread local variable is the add of the thread
4449 // pointer with the offset of the variable.
4450 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4454 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4455 // TODO: implement the "local dynamic" model
4456 // TODO: implement the "initial exec"model for pic executables
4457 assert(Subtarget->isTargetELF() &&
4458 "TLS not implemented for non-ELF targets");
4459 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4460 GlobalValue *GV = GA->getGlobal();
4461 TLSModel::Model model =
4462 getTLSModel (GV, getTargetMachine().getRelocationModel());
4463 if (Subtarget->is64Bit()) {
4465 case TLSModel::GeneralDynamic:
4466 case TLSModel::LocalDynamic: // not implemented
4467 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4469 case TLSModel::InitialExec:
4470 case TLSModel::LocalExec:
4471 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, true);
4475 case TLSModel::GeneralDynamic:
4476 case TLSModel::LocalDynamic: // not implemented
4477 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4479 case TLSModel::InitialExec:
4480 case TLSModel::LocalExec:
4481 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, false);
4484 assert(0 && "Unreachable");
4489 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4490 // FIXME there isn't really any debug info here
4491 DebugLoc dl = Op.getDebugLoc();
4492 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4493 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4494 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4495 // With PIC, the address is actually $g + Offset.
4496 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4497 !Subtarget->isPICStyleRIPRel()) {
4498 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4499 DAG.getNode(X86ISD::GlobalBaseReg,
4500 DebugLoc::getUnknownLoc(),
4508 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4509 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4511 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4513 unsigned char JTFlag = 0;
4514 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
4515 if (Subtarget->isPICStyleStub())
4516 JTFlag = X86II::MO_PIC_BASE_OFFSET;
4517 else if (Subtarget->isPICStyleGOT())
4518 JTFlag = X86II::MO_GOTOFF;
4521 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4523 DebugLoc DL = JT->getDebugLoc();
4524 Result = DAG.getNode(X86ISD::Wrapper, DL, getPointerTy(), Result);
4526 // With PIC, the address is actually $g + Offset.
4528 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4529 DAG.getNode(X86ISD::GlobalBaseReg,
4530 DebugLoc::getUnknownLoc(),
4538 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4539 /// take a 2 x i32 value to shift plus a shift amount.
4540 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4541 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4542 MVT VT = Op.getValueType();
4543 unsigned VTBits = VT.getSizeInBits();
4544 DebugLoc dl = Op.getDebugLoc();
4545 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4546 SDValue ShOpLo = Op.getOperand(0);
4547 SDValue ShOpHi = Op.getOperand(1);
4548 SDValue ShAmt = Op.getOperand(2);
4549 SDValue Tmp1 = isSRA ?
4550 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4551 DAG.getConstant(VTBits - 1, MVT::i8)) :
4552 DAG.getConstant(0, VT);
4555 if (Op.getOpcode() == ISD::SHL_PARTS) {
4556 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4557 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4559 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4560 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4563 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4564 DAG.getConstant(VTBits, MVT::i8));
4565 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4566 AndNode, DAG.getConstant(0, MVT::i8));
4569 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4570 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4571 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4573 if (Op.getOpcode() == ISD::SHL_PARTS) {
4574 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4575 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4577 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4578 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4581 SDValue Ops[2] = { Lo, Hi };
4582 return DAG.getMergeValues(Ops, 2, dl);
4585 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4586 MVT SrcVT = Op.getOperand(0).getValueType();
4588 if (SrcVT.isVector()) {
4589 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
4595 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4596 "Unknown SINT_TO_FP to lower!");
4598 // These are really Legal; return the operand so the caller accepts it as
4600 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4602 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4603 Subtarget->is64Bit()) {
4607 DebugLoc dl = Op.getDebugLoc();
4608 unsigned Size = SrcVT.getSizeInBits()/8;
4609 MachineFunction &MF = DAG.getMachineFunction();
4610 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4611 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4612 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4614 PseudoSourceValue::getFixedStack(SSFI), 0);
4615 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4618 SDValue X86TargetLowering::BuildFILD(SDValue Op, MVT SrcVT, SDValue Chain,
4620 SelectionDAG &DAG) {
4622 DebugLoc dl = Op.getDebugLoc();
4624 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4626 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4628 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4629 SmallVector<SDValue, 8> Ops;
4630 Ops.push_back(Chain);
4631 Ops.push_back(StackSlot);
4632 Ops.push_back(DAG.getValueType(SrcVT));
4633 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4634 Tys, &Ops[0], Ops.size());
4637 Chain = Result.getValue(1);
4638 SDValue InFlag = Result.getValue(2);
4640 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4641 // shouldn't be necessary except that RFP cannot be live across
4642 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4643 MachineFunction &MF = DAG.getMachineFunction();
4644 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4645 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4646 Tys = DAG.getVTList(MVT::Other);
4647 SmallVector<SDValue, 8> Ops;
4648 Ops.push_back(Chain);
4649 Ops.push_back(Result);
4650 Ops.push_back(StackSlot);
4651 Ops.push_back(DAG.getValueType(Op.getValueType()));
4652 Ops.push_back(InFlag);
4653 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4654 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4655 PseudoSourceValue::getFixedStack(SSFI), 0);
4661 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4662 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4663 // This algorithm is not obvious. Here it is in C code, more or less:
4665 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4666 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4667 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4669 // Copy ints to xmm registers.
4670 __m128i xh = _mm_cvtsi32_si128( hi );
4671 __m128i xl = _mm_cvtsi32_si128( lo );
4673 // Combine into low half of a single xmm register.
4674 __m128i x = _mm_unpacklo_epi32( xh, xl );
4678 // Merge in appropriate exponents to give the integer bits the right
4680 x = _mm_unpacklo_epi32( x, exp );
4682 // Subtract away the biases to deal with the IEEE-754 double precision
4684 d = _mm_sub_pd( (__m128d) x, bias );
4686 // All conversions up to here are exact. The correctly rounded result is
4687 // calculated using the current rounding mode using the following
4689 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4690 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4691 // store doesn't really need to be here (except
4692 // maybe to zero the other double)
4697 DebugLoc dl = Op.getDebugLoc();
4699 // Build some magic constants.
4700 std::vector<Constant*> CV0;
4701 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4702 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4703 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4704 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4705 Constant *C0 = ConstantVector::get(CV0);
4706 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4708 std::vector<Constant*> CV1;
4709 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4710 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4711 Constant *C1 = ConstantVector::get(CV1);
4712 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4714 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4715 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4717 DAG.getIntPtrConstant(1)));
4718 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4719 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4721 DAG.getIntPtrConstant(0)));
4722 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4723 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4724 PseudoSourceValue::getConstantPool(), 0,
4726 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
4727 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4728 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4729 PseudoSourceValue::getConstantPool(), 0,
4731 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4733 // Add the halves; easiest way is to swap them into another reg first.
4734 int ShufMask[2] = { 1, -1 };
4735 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
4736 DAG.getUNDEF(MVT::v2f64), ShufMask);
4737 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4738 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4739 DAG.getIntPtrConstant(0));
4742 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4743 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4744 DebugLoc dl = Op.getDebugLoc();
4745 // FP constant to bias correct the final result.
4746 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4749 // Load the 32-bit value into an XMM register.
4750 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4751 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4753 DAG.getIntPtrConstant(0)));
4755 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4756 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4757 DAG.getIntPtrConstant(0));
4759 // Or the load with the bias.
4760 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4761 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4762 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4764 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4765 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4766 MVT::v2f64, Bias)));
4767 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4768 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4769 DAG.getIntPtrConstant(0));
4771 // Subtract the bias.
4772 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4774 // Handle final rounding.
4775 MVT DestVT = Op.getValueType();
4777 if (DestVT.bitsLT(MVT::f64)) {
4778 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4779 DAG.getIntPtrConstant(0));
4780 } else if (DestVT.bitsGT(MVT::f64)) {
4781 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4784 // Handle final rounding.
4788 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4789 SDValue N0 = Op.getOperand(0);
4790 DebugLoc dl = Op.getDebugLoc();
4792 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4793 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4794 // the optimization here.
4795 if (DAG.SignBitIsZero(N0))
4796 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4798 MVT SrcVT = N0.getValueType();
4799 if (SrcVT == MVT::i64) {
4800 // We only handle SSE2 f64 target here; caller can expand the rest.
4801 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4804 return LowerUINT_TO_FP_i64(Op, DAG);
4805 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
4806 return LowerUINT_TO_FP_i32(Op, DAG);
4809 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
4811 // Make a 64-bit buffer, and use it to build an FILD.
4812 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
4813 SDValue WordOff = DAG.getConstant(4, getPointerTy());
4814 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
4815 getPointerTy(), StackSlot, WordOff);
4816 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4817 StackSlot, NULL, 0);
4818 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
4819 OffsetSlot, NULL, 0);
4820 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
4823 std::pair<SDValue,SDValue> X86TargetLowering::
4824 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
4825 DebugLoc dl = Op.getDebugLoc();
4827 MVT DstTy = Op.getValueType();
4830 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
4834 assert(DstTy.getSimpleVT() <= MVT::i64 &&
4835 DstTy.getSimpleVT() >= MVT::i16 &&
4836 "Unknown FP_TO_SINT to lower!");
4838 // These are really Legal.
4839 if (DstTy == MVT::i32 &&
4840 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4841 return std::make_pair(SDValue(), SDValue());
4842 if (Subtarget->is64Bit() &&
4843 DstTy == MVT::i64 &&
4844 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4845 return std::make_pair(SDValue(), SDValue());
4847 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4849 MachineFunction &MF = DAG.getMachineFunction();
4850 unsigned MemSize = DstTy.getSizeInBits()/8;
4851 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4852 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4855 switch (DstTy.getSimpleVT()) {
4856 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4857 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4858 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4859 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4862 SDValue Chain = DAG.getEntryNode();
4863 SDValue Value = Op.getOperand(0);
4864 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4865 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4866 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
4867 PseudoSourceValue::getFixedStack(SSFI), 0);
4868 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4870 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4872 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
4873 Chain = Value.getValue(1);
4874 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4875 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4878 // Build the FP_TO_INT*_IN_MEM
4879 SDValue Ops[] = { Chain, Value, StackSlot };
4880 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
4882 return std::make_pair(FIST, StackSlot);
4885 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4886 if (Op.getValueType().isVector()) {
4887 if (Op.getValueType() == MVT::v2i32 &&
4888 Op.getOperand(0).getValueType() == MVT::v2f64) {
4894 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
4895 SDValue FIST = Vals.first, StackSlot = Vals.second;
4896 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
4897 if (FIST.getNode() == 0) return Op;
4900 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4901 FIST, StackSlot, NULL, 0);
4904 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
4905 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
4906 SDValue FIST = Vals.first, StackSlot = Vals.second;
4907 assert(FIST.getNode() && "Unexpected failure");
4910 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4911 FIST, StackSlot, NULL, 0);
4914 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4915 DebugLoc dl = Op.getDebugLoc();
4916 MVT VT = Op.getValueType();
4919 EltVT = VT.getVectorElementType();
4920 std::vector<Constant*> CV;
4921 if (EltVT == MVT::f64) {
4922 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4926 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4932 Constant *C = ConstantVector::get(CV);
4933 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4934 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4935 PseudoSourceValue::getConstantPool(), 0,
4937 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
4940 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4941 DebugLoc dl = Op.getDebugLoc();
4942 MVT VT = Op.getValueType();
4944 unsigned EltNum = 1;
4945 if (VT.isVector()) {
4946 EltVT = VT.getVectorElementType();
4947 EltNum = VT.getVectorNumElements();
4949 std::vector<Constant*> CV;
4950 if (EltVT == MVT::f64) {
4951 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4955 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4961 Constant *C = ConstantVector::get(CV);
4962 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4963 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4964 PseudoSourceValue::getConstantPool(), 0,
4966 if (VT.isVector()) {
4967 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4968 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
4969 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4971 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
4973 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
4977 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4978 SDValue Op0 = Op.getOperand(0);
4979 SDValue Op1 = Op.getOperand(1);
4980 DebugLoc dl = Op.getDebugLoc();
4981 MVT VT = Op.getValueType();
4982 MVT SrcVT = Op1.getValueType();
4984 // If second operand is smaller, extend it first.
4985 if (SrcVT.bitsLT(VT)) {
4986 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
4989 // And if it is bigger, shrink it first.
4990 if (SrcVT.bitsGT(VT)) {
4991 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
4995 // At this point the operands and the result should have the same
4996 // type, and that won't be f80 since that is not custom lowered.
4998 // First get the sign bit of second operand.
4999 std::vector<Constant*> CV;
5000 if (SrcVT == MVT::f64) {
5001 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5002 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5004 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5005 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5006 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5007 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5009 Constant *C = ConstantVector::get(CV);
5010 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5011 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5012 PseudoSourceValue::getConstantPool(), 0,
5014 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5016 // Shift sign bit right or left if the two operands have different types.
5017 if (SrcVT.bitsGT(VT)) {
5018 // Op0 is MVT::f32, Op1 is MVT::f64.
5019 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5020 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5021 DAG.getConstant(32, MVT::i32));
5022 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5023 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5024 DAG.getIntPtrConstant(0));
5027 // Clear first operand sign bit.
5029 if (VT == MVT::f64) {
5030 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5031 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5033 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5034 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5035 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5036 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5038 C = ConstantVector::get(CV);
5039 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5040 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5041 PseudoSourceValue::getConstantPool(), 0,
5043 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5045 // Or the value with the sign bit.
5046 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5049 /// Emit nodes that will be selected as "test Op0,Op0", or something
5051 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5052 SelectionDAG &DAG) {
5053 DebugLoc dl = Op.getDebugLoc();
5055 // CF and OF aren't always set the way we want. Determine which
5056 // of these we need.
5057 bool NeedCF = false;
5058 bool NeedOF = false;
5060 case X86::COND_A: case X86::COND_AE:
5061 case X86::COND_B: case X86::COND_BE:
5064 case X86::COND_G: case X86::COND_GE:
5065 case X86::COND_L: case X86::COND_LE:
5066 case X86::COND_O: case X86::COND_NO:
5072 // See if we can use the EFLAGS value from the operand instead of
5073 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5074 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5075 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5076 unsigned Opcode = 0;
5077 unsigned NumOperands = 0;
5078 switch (Op.getNode()->getOpcode()) {
5080 // Due to an isel shortcoming, be conservative if this add is likely to
5081 // be selected as part of a load-modify-store instruction. When the root
5082 // node in a match is a store, isel doesn't know how to remap non-chain
5083 // non-flag uses of other nodes in the match, such as the ADD in this
5084 // case. This leads to the ADD being left around and reselected, with
5085 // the result being two adds in the output.
5086 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5087 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5088 if (UI->getOpcode() == ISD::STORE)
5090 if (ConstantSDNode *C =
5091 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5092 // An add of one will be selected as an INC.
5093 if (C->getAPIntValue() == 1) {
5094 Opcode = X86ISD::INC;
5098 // An add of negative one (subtract of one) will be selected as a DEC.
5099 if (C->getAPIntValue().isAllOnesValue()) {
5100 Opcode = X86ISD::DEC;
5105 // Otherwise use a regular EFLAGS-setting add.
5106 Opcode = X86ISD::ADD;
5110 // Due to the ISEL shortcoming noted above, be conservative if this sub is
5111 // likely to be selected as part of a load-modify-store instruction.
5112 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5113 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5114 if (UI->getOpcode() == ISD::STORE)
5116 // Otherwise use a regular EFLAGS-setting sub.
5117 Opcode = X86ISD::SUB;
5124 return SDValue(Op.getNode(), 1);
5130 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5131 SmallVector<SDValue, 4> Ops;
5132 for (unsigned i = 0; i != NumOperands; ++i)
5133 Ops.push_back(Op.getOperand(i));
5134 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5135 DAG.ReplaceAllUsesWith(Op, New);
5136 return SDValue(New.getNode(), 1);
5140 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5141 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5142 DAG.getConstant(0, Op.getValueType()));
5145 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5147 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5148 SelectionDAG &DAG) {
5149 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5150 if (C->getAPIntValue() == 0)
5151 return EmitTest(Op0, X86CC, DAG);
5153 DebugLoc dl = Op0.getDebugLoc();
5154 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5157 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5158 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5159 SDValue Op0 = Op.getOperand(0);
5160 SDValue Op1 = Op.getOperand(1);
5161 DebugLoc dl = Op.getDebugLoc();
5162 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5164 // Lower (X & (1 << N)) == 0 to BT(X, N).
5165 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5166 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5167 if (Op0.getOpcode() == ISD::AND &&
5169 Op1.getOpcode() == ISD::Constant &&
5170 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5171 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5173 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5174 if (ConstantSDNode *Op010C =
5175 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5176 if (Op010C->getZExtValue() == 1) {
5177 LHS = Op0.getOperand(0);
5178 RHS = Op0.getOperand(1).getOperand(1);
5180 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5181 if (ConstantSDNode *Op000C =
5182 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5183 if (Op000C->getZExtValue() == 1) {
5184 LHS = Op0.getOperand(1);
5185 RHS = Op0.getOperand(0).getOperand(1);
5187 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5188 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5189 SDValue AndLHS = Op0.getOperand(0);
5190 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5191 LHS = AndLHS.getOperand(0);
5192 RHS = AndLHS.getOperand(1);
5196 if (LHS.getNode()) {
5197 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5198 // instruction. Since the shift amount is in-range-or-undefined, we know
5199 // that doing a bittest on the i16 value is ok. We extend to i32 because
5200 // the encoding for the i16 version is larger than the i32 version.
5201 if (LHS.getValueType() == MVT::i8)
5202 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5204 // If the operand types disagree, extend the shift amount to match. Since
5205 // BT ignores high bits (like shifts) we can use anyextend.
5206 if (LHS.getValueType() != RHS.getValueType())
5207 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5209 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5210 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5211 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5212 DAG.getConstant(Cond, MVT::i8), BT);
5216 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5217 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5219 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5220 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5221 DAG.getConstant(X86CC, MVT::i8), Cond);
5224 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5226 SDValue Op0 = Op.getOperand(0);
5227 SDValue Op1 = Op.getOperand(1);
5228 SDValue CC = Op.getOperand(2);
5229 MVT VT = Op.getValueType();
5230 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5231 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5232 DebugLoc dl = Op.getDebugLoc();
5236 MVT VT0 = Op0.getValueType();
5237 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5238 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5241 switch (SetCCOpcode) {
5244 case ISD::SETEQ: SSECC = 0; break;
5246 case ISD::SETGT: Swap = true; // Fallthrough
5248 case ISD::SETOLT: SSECC = 1; break;
5250 case ISD::SETGE: Swap = true; // Fallthrough
5252 case ISD::SETOLE: SSECC = 2; break;
5253 case ISD::SETUO: SSECC = 3; break;
5255 case ISD::SETNE: SSECC = 4; break;
5256 case ISD::SETULE: Swap = true;
5257 case ISD::SETUGE: SSECC = 5; break;
5258 case ISD::SETULT: Swap = true;
5259 case ISD::SETUGT: SSECC = 6; break;
5260 case ISD::SETO: SSECC = 7; break;
5263 std::swap(Op0, Op1);
5265 // In the two special cases we can't handle, emit two comparisons.
5267 if (SetCCOpcode == ISD::SETUEQ) {
5269 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5270 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5271 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5273 else if (SetCCOpcode == ISD::SETONE) {
5275 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5276 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5277 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5279 assert(0 && "Illegal FP comparison");
5281 // Handle all other FP comparisons here.
5282 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5285 // We are handling one of the integer comparisons here. Since SSE only has
5286 // GT and EQ comparisons for integer, swapping operands and multiple
5287 // operations may be required for some comparisons.
5288 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5289 bool Swap = false, Invert = false, FlipSigns = false;
5291 switch (VT.getSimpleVT()) {
5293 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5294 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5295 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5296 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5299 switch (SetCCOpcode) {
5301 case ISD::SETNE: Invert = true;
5302 case ISD::SETEQ: Opc = EQOpc; break;
5303 case ISD::SETLT: Swap = true;
5304 case ISD::SETGT: Opc = GTOpc; break;
5305 case ISD::SETGE: Swap = true;
5306 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5307 case ISD::SETULT: Swap = true;
5308 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5309 case ISD::SETUGE: Swap = true;
5310 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5313 std::swap(Op0, Op1);
5315 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5316 // bits of the inputs before performing those operations.
5318 MVT EltVT = VT.getVectorElementType();
5319 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5321 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5322 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5324 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5325 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5328 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5330 // If the logical-not of the result is required, perform that now.
5332 Result = DAG.getNOT(dl, Result, VT);
5337 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5338 static bool isX86LogicalCmp(SDValue Op) {
5339 unsigned Opc = Op.getNode()->getOpcode();
5340 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5342 if (Op.getResNo() == 1 &&
5343 (Opc == X86ISD::ADD ||
5344 Opc == X86ISD::SUB ||
5345 Opc == X86ISD::SMUL ||
5346 Opc == X86ISD::UMUL ||
5347 Opc == X86ISD::INC ||
5348 Opc == X86ISD::DEC))
5354 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5355 bool addTest = true;
5356 SDValue Cond = Op.getOperand(0);
5357 DebugLoc dl = Op.getDebugLoc();
5360 if (Cond.getOpcode() == ISD::SETCC)
5361 Cond = LowerSETCC(Cond, DAG);
5363 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5364 // setting operand in place of the X86ISD::SETCC.
5365 if (Cond.getOpcode() == X86ISD::SETCC) {
5366 CC = Cond.getOperand(0);
5368 SDValue Cmp = Cond.getOperand(1);
5369 unsigned Opc = Cmp.getOpcode();
5370 MVT VT = Op.getValueType();
5372 bool IllegalFPCMov = false;
5373 if (VT.isFloatingPoint() && !VT.isVector() &&
5374 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5375 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5377 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5378 Opc == X86ISD::BT) { // FIXME
5385 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5386 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5389 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5390 SmallVector<SDValue, 4> Ops;
5391 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5392 // condition is true.
5393 Ops.push_back(Op.getOperand(2));
5394 Ops.push_back(Op.getOperand(1));
5396 Ops.push_back(Cond);
5397 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5400 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5401 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5402 // from the AND / OR.
5403 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5404 Opc = Op.getOpcode();
5405 if (Opc != ISD::OR && Opc != ISD::AND)
5407 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5408 Op.getOperand(0).hasOneUse() &&
5409 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5410 Op.getOperand(1).hasOneUse());
5413 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5414 // 1 and that the SETCC node has a single use.
5415 static bool isXor1OfSetCC(SDValue Op) {
5416 if (Op.getOpcode() != ISD::XOR)
5418 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5419 if (N1C && N1C->getAPIntValue() == 1) {
5420 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5421 Op.getOperand(0).hasOneUse();
5426 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5427 bool addTest = true;
5428 SDValue Chain = Op.getOperand(0);
5429 SDValue Cond = Op.getOperand(1);
5430 SDValue Dest = Op.getOperand(2);
5431 DebugLoc dl = Op.getDebugLoc();
5434 if (Cond.getOpcode() == ISD::SETCC)
5435 Cond = LowerSETCC(Cond, DAG);
5437 // FIXME: LowerXALUO doesn't handle these!!
5438 else if (Cond.getOpcode() == X86ISD::ADD ||
5439 Cond.getOpcode() == X86ISD::SUB ||
5440 Cond.getOpcode() == X86ISD::SMUL ||
5441 Cond.getOpcode() == X86ISD::UMUL)
5442 Cond = LowerXALUO(Cond, DAG);
5445 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5446 // setting operand in place of the X86ISD::SETCC.
5447 if (Cond.getOpcode() == X86ISD::SETCC) {
5448 CC = Cond.getOperand(0);
5450 SDValue Cmp = Cond.getOperand(1);
5451 unsigned Opc = Cmp.getOpcode();
5452 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5453 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5457 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5461 // These can only come from an arithmetic instruction with overflow,
5462 // e.g. SADDO, UADDO.
5463 Cond = Cond.getNode()->getOperand(1);
5470 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5471 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5472 if (CondOpc == ISD::OR) {
5473 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5474 // two branches instead of an explicit OR instruction with a
5476 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5477 isX86LogicalCmp(Cmp)) {
5478 CC = Cond.getOperand(0).getOperand(0);
5479 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5480 Chain, Dest, CC, Cmp);
5481 CC = Cond.getOperand(1).getOperand(0);
5485 } else { // ISD::AND
5486 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5487 // two branches instead of an explicit AND instruction with a
5488 // separate test. However, we only do this if this block doesn't
5489 // have a fall-through edge, because this requires an explicit
5490 // jmp when the condition is false.
5491 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5492 isX86LogicalCmp(Cmp) &&
5493 Op.getNode()->hasOneUse()) {
5494 X86::CondCode CCode =
5495 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5496 CCode = X86::GetOppositeBranchCondition(CCode);
5497 CC = DAG.getConstant(CCode, MVT::i8);
5498 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5499 // Look for an unconditional branch following this conditional branch.
5500 // We need this because we need to reverse the successors in order
5501 // to implement FCMP_OEQ.
5502 if (User.getOpcode() == ISD::BR) {
5503 SDValue FalseBB = User.getOperand(1);
5505 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5506 assert(NewBR == User);
5509 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5510 Chain, Dest, CC, Cmp);
5511 X86::CondCode CCode =
5512 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5513 CCode = X86::GetOppositeBranchCondition(CCode);
5514 CC = DAG.getConstant(CCode, MVT::i8);
5520 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5521 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5522 // It should be transformed during dag combiner except when the condition
5523 // is set by a arithmetics with overflow node.
5524 X86::CondCode CCode =
5525 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5526 CCode = X86::GetOppositeBranchCondition(CCode);
5527 CC = DAG.getConstant(CCode, MVT::i8);
5528 Cond = Cond.getOperand(0).getOperand(1);
5534 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5535 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5537 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5538 Chain, Dest, CC, Cond);
5542 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5543 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5544 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5545 // that the guard pages used by the OS virtual memory manager are allocated in
5546 // correct sequence.
5548 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5549 SelectionDAG &DAG) {
5550 assert(Subtarget->isTargetCygMing() &&
5551 "This should be used only on Cygwin/Mingw targets");
5552 DebugLoc dl = Op.getDebugLoc();
5555 SDValue Chain = Op.getOperand(0);
5556 SDValue Size = Op.getOperand(1);
5557 // FIXME: Ensure alignment here
5561 MVT IntPtr = getPointerTy();
5562 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5564 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5566 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5567 Flag = Chain.getValue(1);
5569 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5570 SDValue Ops[] = { Chain,
5571 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5572 DAG.getRegister(X86::EAX, IntPtr),
5573 DAG.getRegister(X86StackPtr, SPTy),
5575 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5576 Flag = Chain.getValue(1);
5578 Chain = DAG.getCALLSEQ_END(Chain,
5579 DAG.getIntPtrConstant(0, true),
5580 DAG.getIntPtrConstant(0, true),
5583 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5585 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5586 return DAG.getMergeValues(Ops1, 2, dl);
5590 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5592 SDValue Dst, SDValue Src,
5593 SDValue Size, unsigned Align,
5595 uint64_t DstSVOff) {
5596 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5598 // If not DWORD aligned or size is more than the threshold, call the library.
5599 // The libc version is likely to be faster for these cases. It can use the
5600 // address value and run time information about the CPU.
5601 if ((Align & 3) != 0 ||
5603 ConstantSize->getZExtValue() >
5604 getSubtarget()->getMaxInlineSizeThreshold()) {
5605 SDValue InFlag(0, 0);
5607 // Check to see if there is a specialized entry-point for memory zeroing.
5608 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5610 if (const char *bzeroEntry = V &&
5611 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5612 MVT IntPtr = getPointerTy();
5613 const Type *IntPtrTy = TD->getIntPtrType();
5614 TargetLowering::ArgListTy Args;
5615 TargetLowering::ArgListEntry Entry;
5617 Entry.Ty = IntPtrTy;
5618 Args.push_back(Entry);
5620 Args.push_back(Entry);
5621 std::pair<SDValue,SDValue> CallResult =
5622 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5623 CallingConv::C, false,
5624 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5625 return CallResult.second;
5628 // Otherwise have the target-independent code call memset.
5632 uint64_t SizeVal = ConstantSize->getZExtValue();
5633 SDValue InFlag(0, 0);
5636 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5637 unsigned BytesLeft = 0;
5638 bool TwoRepStos = false;
5641 uint64_t Val = ValC->getZExtValue() & 255;
5643 // If the value is a constant, then we can potentially use larger sets.
5644 switch (Align & 3) {
5645 case 2: // WORD aligned
5648 Val = (Val << 8) | Val;
5650 case 0: // DWORD aligned
5653 Val = (Val << 8) | Val;
5654 Val = (Val << 16) | Val;
5655 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5658 Val = (Val << 32) | Val;
5661 default: // Byte aligned
5664 Count = DAG.getIntPtrConstant(SizeVal);
5668 if (AVT.bitsGT(MVT::i8)) {
5669 unsigned UBytes = AVT.getSizeInBits() / 8;
5670 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5671 BytesLeft = SizeVal % UBytes;
5674 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5676 InFlag = Chain.getValue(1);
5679 Count = DAG.getIntPtrConstant(SizeVal);
5680 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5681 InFlag = Chain.getValue(1);
5684 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5687 InFlag = Chain.getValue(1);
5688 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5691 InFlag = Chain.getValue(1);
5693 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5694 SmallVector<SDValue, 8> Ops;
5695 Ops.push_back(Chain);
5696 Ops.push_back(DAG.getValueType(AVT));
5697 Ops.push_back(InFlag);
5698 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5701 InFlag = Chain.getValue(1);
5703 MVT CVT = Count.getValueType();
5704 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5705 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5706 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5709 InFlag = Chain.getValue(1);
5710 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5712 Ops.push_back(Chain);
5713 Ops.push_back(DAG.getValueType(MVT::i8));
5714 Ops.push_back(InFlag);
5715 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5716 } else if (BytesLeft) {
5717 // Handle the last 1 - 7 bytes.
5718 unsigned Offset = SizeVal - BytesLeft;
5719 MVT AddrVT = Dst.getValueType();
5720 MVT SizeVT = Size.getValueType();
5722 Chain = DAG.getMemset(Chain, dl,
5723 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5724 DAG.getConstant(Offset, AddrVT)),
5726 DAG.getConstant(BytesLeft, SizeVT),
5727 Align, DstSV, DstSVOff + Offset);
5730 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5735 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5736 SDValue Chain, SDValue Dst, SDValue Src,
5737 SDValue Size, unsigned Align,
5739 const Value *DstSV, uint64_t DstSVOff,
5740 const Value *SrcSV, uint64_t SrcSVOff) {
5741 // This requires the copy size to be a constant, preferrably
5742 // within a subtarget-specific limit.
5743 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5746 uint64_t SizeVal = ConstantSize->getZExtValue();
5747 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5750 /// If not DWORD aligned, call the library.
5751 if ((Align & 3) != 0)
5756 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5759 unsigned UBytes = AVT.getSizeInBits() / 8;
5760 unsigned CountVal = SizeVal / UBytes;
5761 SDValue Count = DAG.getIntPtrConstant(CountVal);
5762 unsigned BytesLeft = SizeVal % UBytes;
5764 SDValue InFlag(0, 0);
5765 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5768 InFlag = Chain.getValue(1);
5769 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5772 InFlag = Chain.getValue(1);
5773 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5776 InFlag = Chain.getValue(1);
5778 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5779 SmallVector<SDValue, 8> Ops;
5780 Ops.push_back(Chain);
5781 Ops.push_back(DAG.getValueType(AVT));
5782 Ops.push_back(InFlag);
5783 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5785 SmallVector<SDValue, 4> Results;
5786 Results.push_back(RepMovs);
5788 // Handle the last 1 - 7 bytes.
5789 unsigned Offset = SizeVal - BytesLeft;
5790 MVT DstVT = Dst.getValueType();
5791 MVT SrcVT = Src.getValueType();
5792 MVT SizeVT = Size.getValueType();
5793 Results.push_back(DAG.getMemcpy(Chain, dl,
5794 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5795 DAG.getConstant(Offset, DstVT)),
5796 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5797 DAG.getConstant(Offset, SrcVT)),
5798 DAG.getConstant(BytesLeft, SizeVT),
5799 Align, AlwaysInline,
5800 DstSV, DstSVOff + Offset,
5801 SrcSV, SrcSVOff + Offset));
5804 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5805 &Results[0], Results.size());
5808 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5809 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5810 DebugLoc dl = Op.getDebugLoc();
5812 if (!Subtarget->is64Bit()) {
5813 // vastart just stores the address of the VarArgsFrameIndex slot into the
5814 // memory location argument.
5815 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5816 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
5820 // gp_offset (0 - 6 * 8)
5821 // fp_offset (48 - 48 + 8 * 16)
5822 // overflow_arg_area (point to parameters coming in memory).
5824 SmallVector<SDValue, 8> MemOps;
5825 SDValue FIN = Op.getOperand(1);
5827 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
5828 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5830 MemOps.push_back(Store);
5833 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5834 FIN, DAG.getIntPtrConstant(4));
5835 Store = DAG.getStore(Op.getOperand(0), dl,
5836 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5838 MemOps.push_back(Store);
5840 // Store ptr to overflow_arg_area
5841 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5842 FIN, DAG.getIntPtrConstant(4));
5843 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5844 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
5845 MemOps.push_back(Store);
5847 // Store ptr to reg_save_area.
5848 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5849 FIN, DAG.getIntPtrConstant(8));
5850 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5851 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
5852 MemOps.push_back(Store);
5853 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5854 &MemOps[0], MemOps.size());
5857 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5858 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5859 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5860 SDValue Chain = Op.getOperand(0);
5861 SDValue SrcPtr = Op.getOperand(1);
5862 SDValue SrcSV = Op.getOperand(2);
5864 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5869 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5870 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5871 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5872 SDValue Chain = Op.getOperand(0);
5873 SDValue DstPtr = Op.getOperand(1);
5874 SDValue SrcPtr = Op.getOperand(2);
5875 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5876 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5877 DebugLoc dl = Op.getDebugLoc();
5879 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
5880 DAG.getIntPtrConstant(24), 8, false,
5881 DstSV, 0, SrcSV, 0);
5885 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5886 DebugLoc dl = Op.getDebugLoc();
5887 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5889 default: return SDValue(); // Don't custom lower most intrinsics.
5890 // Comparison intrinsics.
5891 case Intrinsic::x86_sse_comieq_ss:
5892 case Intrinsic::x86_sse_comilt_ss:
5893 case Intrinsic::x86_sse_comile_ss:
5894 case Intrinsic::x86_sse_comigt_ss:
5895 case Intrinsic::x86_sse_comige_ss:
5896 case Intrinsic::x86_sse_comineq_ss:
5897 case Intrinsic::x86_sse_ucomieq_ss:
5898 case Intrinsic::x86_sse_ucomilt_ss:
5899 case Intrinsic::x86_sse_ucomile_ss:
5900 case Intrinsic::x86_sse_ucomigt_ss:
5901 case Intrinsic::x86_sse_ucomige_ss:
5902 case Intrinsic::x86_sse_ucomineq_ss:
5903 case Intrinsic::x86_sse2_comieq_sd:
5904 case Intrinsic::x86_sse2_comilt_sd:
5905 case Intrinsic::x86_sse2_comile_sd:
5906 case Intrinsic::x86_sse2_comigt_sd:
5907 case Intrinsic::x86_sse2_comige_sd:
5908 case Intrinsic::x86_sse2_comineq_sd:
5909 case Intrinsic::x86_sse2_ucomieq_sd:
5910 case Intrinsic::x86_sse2_ucomilt_sd:
5911 case Intrinsic::x86_sse2_ucomile_sd:
5912 case Intrinsic::x86_sse2_ucomigt_sd:
5913 case Intrinsic::x86_sse2_ucomige_sd:
5914 case Intrinsic::x86_sse2_ucomineq_sd: {
5916 ISD::CondCode CC = ISD::SETCC_INVALID;
5919 case Intrinsic::x86_sse_comieq_ss:
5920 case Intrinsic::x86_sse2_comieq_sd:
5924 case Intrinsic::x86_sse_comilt_ss:
5925 case Intrinsic::x86_sse2_comilt_sd:
5929 case Intrinsic::x86_sse_comile_ss:
5930 case Intrinsic::x86_sse2_comile_sd:
5934 case Intrinsic::x86_sse_comigt_ss:
5935 case Intrinsic::x86_sse2_comigt_sd:
5939 case Intrinsic::x86_sse_comige_ss:
5940 case Intrinsic::x86_sse2_comige_sd:
5944 case Intrinsic::x86_sse_comineq_ss:
5945 case Intrinsic::x86_sse2_comineq_sd:
5949 case Intrinsic::x86_sse_ucomieq_ss:
5950 case Intrinsic::x86_sse2_ucomieq_sd:
5951 Opc = X86ISD::UCOMI;
5954 case Intrinsic::x86_sse_ucomilt_ss:
5955 case Intrinsic::x86_sse2_ucomilt_sd:
5956 Opc = X86ISD::UCOMI;
5959 case Intrinsic::x86_sse_ucomile_ss:
5960 case Intrinsic::x86_sse2_ucomile_sd:
5961 Opc = X86ISD::UCOMI;
5964 case Intrinsic::x86_sse_ucomigt_ss:
5965 case Intrinsic::x86_sse2_ucomigt_sd:
5966 Opc = X86ISD::UCOMI;
5969 case Intrinsic::x86_sse_ucomige_ss:
5970 case Intrinsic::x86_sse2_ucomige_sd:
5971 Opc = X86ISD::UCOMI;
5974 case Intrinsic::x86_sse_ucomineq_ss:
5975 case Intrinsic::x86_sse2_ucomineq_sd:
5976 Opc = X86ISD::UCOMI;
5981 SDValue LHS = Op.getOperand(1);
5982 SDValue RHS = Op.getOperand(2);
5983 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
5984 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
5985 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5986 DAG.getConstant(X86CC, MVT::i8), Cond);
5987 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
5990 // Fix vector shift instructions where the last operand is a non-immediate
5992 case Intrinsic::x86_sse2_pslli_w:
5993 case Intrinsic::x86_sse2_pslli_d:
5994 case Intrinsic::x86_sse2_pslli_q:
5995 case Intrinsic::x86_sse2_psrli_w:
5996 case Intrinsic::x86_sse2_psrli_d:
5997 case Intrinsic::x86_sse2_psrli_q:
5998 case Intrinsic::x86_sse2_psrai_w:
5999 case Intrinsic::x86_sse2_psrai_d:
6000 case Intrinsic::x86_mmx_pslli_w:
6001 case Intrinsic::x86_mmx_pslli_d:
6002 case Intrinsic::x86_mmx_pslli_q:
6003 case Intrinsic::x86_mmx_psrli_w:
6004 case Intrinsic::x86_mmx_psrli_d:
6005 case Intrinsic::x86_mmx_psrli_q:
6006 case Intrinsic::x86_mmx_psrai_w:
6007 case Intrinsic::x86_mmx_psrai_d: {
6008 SDValue ShAmt = Op.getOperand(2);
6009 if (isa<ConstantSDNode>(ShAmt))
6012 unsigned NewIntNo = 0;
6013 MVT ShAmtVT = MVT::v4i32;
6015 case Intrinsic::x86_sse2_pslli_w:
6016 NewIntNo = Intrinsic::x86_sse2_psll_w;
6018 case Intrinsic::x86_sse2_pslli_d:
6019 NewIntNo = Intrinsic::x86_sse2_psll_d;
6021 case Intrinsic::x86_sse2_pslli_q:
6022 NewIntNo = Intrinsic::x86_sse2_psll_q;
6024 case Intrinsic::x86_sse2_psrli_w:
6025 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6027 case Intrinsic::x86_sse2_psrli_d:
6028 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6030 case Intrinsic::x86_sse2_psrli_q:
6031 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6033 case Intrinsic::x86_sse2_psrai_w:
6034 NewIntNo = Intrinsic::x86_sse2_psra_w;
6036 case Intrinsic::x86_sse2_psrai_d:
6037 NewIntNo = Intrinsic::x86_sse2_psra_d;
6040 ShAmtVT = MVT::v2i32;
6042 case Intrinsic::x86_mmx_pslli_w:
6043 NewIntNo = Intrinsic::x86_mmx_psll_w;
6045 case Intrinsic::x86_mmx_pslli_d:
6046 NewIntNo = Intrinsic::x86_mmx_psll_d;
6048 case Intrinsic::x86_mmx_pslli_q:
6049 NewIntNo = Intrinsic::x86_mmx_psll_q;
6051 case Intrinsic::x86_mmx_psrli_w:
6052 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6054 case Intrinsic::x86_mmx_psrli_d:
6055 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6057 case Intrinsic::x86_mmx_psrli_q:
6058 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6060 case Intrinsic::x86_mmx_psrai_w:
6061 NewIntNo = Intrinsic::x86_mmx_psra_w;
6063 case Intrinsic::x86_mmx_psrai_d:
6064 NewIntNo = Intrinsic::x86_mmx_psra_d;
6066 default: abort(); // Can't reach here.
6071 MVT VT = Op.getValueType();
6072 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6073 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6074 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6075 DAG.getConstant(NewIntNo, MVT::i32),
6076 Op.getOperand(1), ShAmt);
6081 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6082 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6083 DebugLoc dl = Op.getDebugLoc();
6086 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6088 DAG.getConstant(TD->getPointerSize(),
6089 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6090 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6091 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6096 // Just load the return address.
6097 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6098 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6099 RetAddrFI, NULL, 0);
6102 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6103 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6104 MFI->setFrameAddressIsTaken(true);
6105 MVT VT = Op.getValueType();
6106 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6107 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6108 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6109 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6111 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6115 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6116 SelectionDAG &DAG) {
6117 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6120 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6122 MachineFunction &MF = DAG.getMachineFunction();
6123 SDValue Chain = Op.getOperand(0);
6124 SDValue Offset = Op.getOperand(1);
6125 SDValue Handler = Op.getOperand(2);
6126 DebugLoc dl = Op.getDebugLoc();
6128 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6130 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6132 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6133 DAG.getIntPtrConstant(-TD->getPointerSize()));
6134 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6135 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6136 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6137 MF.getRegInfo().addLiveOut(StoreAddrReg);
6139 return DAG.getNode(X86ISD::EH_RETURN, dl,
6141 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6144 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6145 SelectionDAG &DAG) {
6146 SDValue Root = Op.getOperand(0);
6147 SDValue Trmp = Op.getOperand(1); // trampoline
6148 SDValue FPtr = Op.getOperand(2); // nested function
6149 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6150 DebugLoc dl = Op.getDebugLoc();
6152 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6154 const X86InstrInfo *TII =
6155 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6157 if (Subtarget->is64Bit()) {
6158 SDValue OutChains[6];
6160 // Large code-model.
6162 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6163 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6165 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6166 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6168 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6170 // Load the pointer to the nested function into R11.
6171 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6172 SDValue Addr = Trmp;
6173 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6176 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6177 DAG.getConstant(2, MVT::i64));
6178 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6180 // Load the 'nest' parameter value into R10.
6181 // R10 is specified in X86CallingConv.td
6182 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6183 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6184 DAG.getConstant(10, MVT::i64));
6185 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6186 Addr, TrmpAddr, 10);
6188 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6189 DAG.getConstant(12, MVT::i64));
6190 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6192 // Jump to the nested function.
6193 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6194 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6195 DAG.getConstant(20, MVT::i64));
6196 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6197 Addr, TrmpAddr, 20);
6199 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6200 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6201 DAG.getConstant(22, MVT::i64));
6202 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6206 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6207 return DAG.getMergeValues(Ops, 2, dl);
6209 const Function *Func =
6210 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6211 unsigned CC = Func->getCallingConv();
6216 assert(0 && "Unsupported calling convention");
6217 case CallingConv::C:
6218 case CallingConv::X86_StdCall: {
6219 // Pass 'nest' parameter in ECX.
6220 // Must be kept in sync with X86CallingConv.td
6223 // Check that ECX wasn't needed by an 'inreg' parameter.
6224 const FunctionType *FTy = Func->getFunctionType();
6225 const AttrListPtr &Attrs = Func->getAttributes();
6227 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6228 unsigned InRegCount = 0;
6231 for (FunctionType::param_iterator I = FTy->param_begin(),
6232 E = FTy->param_end(); I != E; ++I, ++Idx)
6233 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6234 // FIXME: should only count parameters that are lowered to integers.
6235 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6237 if (InRegCount > 2) {
6238 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6244 case CallingConv::X86_FastCall:
6245 case CallingConv::Fast:
6246 // Pass 'nest' parameter in EAX.
6247 // Must be kept in sync with X86CallingConv.td
6252 SDValue OutChains[4];
6255 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6256 DAG.getConstant(10, MVT::i32));
6257 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6259 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6260 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6261 OutChains[0] = DAG.getStore(Root, dl,
6262 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6265 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6266 DAG.getConstant(1, MVT::i32));
6267 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6269 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6270 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6271 DAG.getConstant(5, MVT::i32));
6272 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6273 TrmpAddr, 5, false, 1);
6275 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6276 DAG.getConstant(6, MVT::i32));
6277 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6280 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6281 return DAG.getMergeValues(Ops, 2, dl);
6285 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6287 The rounding mode is in bits 11:10 of FPSR, and has the following
6294 FLT_ROUNDS, on the other hand, expects the following:
6301 To perform the conversion, we do:
6302 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6305 MachineFunction &MF = DAG.getMachineFunction();
6306 const TargetMachine &TM = MF.getTarget();
6307 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6308 unsigned StackAlignment = TFI.getStackAlignment();
6309 MVT VT = Op.getValueType();
6310 DebugLoc dl = Op.getDebugLoc();
6312 // Save FP Control Word to stack slot
6313 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6314 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6316 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6317 DAG.getEntryNode(), StackSlot);
6319 // Load FP Control Word from stack slot
6320 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6322 // Transform as necessary
6324 DAG.getNode(ISD::SRL, dl, MVT::i16,
6325 DAG.getNode(ISD::AND, dl, MVT::i16,
6326 CWD, DAG.getConstant(0x800, MVT::i16)),
6327 DAG.getConstant(11, MVT::i8));
6329 DAG.getNode(ISD::SRL, dl, MVT::i16,
6330 DAG.getNode(ISD::AND, dl, MVT::i16,
6331 CWD, DAG.getConstant(0x400, MVT::i16)),
6332 DAG.getConstant(9, MVT::i8));
6335 DAG.getNode(ISD::AND, dl, MVT::i16,
6336 DAG.getNode(ISD::ADD, dl, MVT::i16,
6337 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6338 DAG.getConstant(1, MVT::i16)),
6339 DAG.getConstant(3, MVT::i16));
6342 return DAG.getNode((VT.getSizeInBits() < 16 ?
6343 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6346 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6347 MVT VT = Op.getValueType();
6349 unsigned NumBits = VT.getSizeInBits();
6350 DebugLoc dl = Op.getDebugLoc();
6352 Op = Op.getOperand(0);
6353 if (VT == MVT::i8) {
6354 // Zero extend to i32 since there is not an i8 bsr.
6356 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6359 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6360 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6361 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6363 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6364 SmallVector<SDValue, 4> Ops;
6366 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6367 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6368 Ops.push_back(Op.getValue(1));
6369 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6371 // Finally xor with NumBits-1.
6372 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6375 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6379 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6380 MVT VT = Op.getValueType();
6382 unsigned NumBits = VT.getSizeInBits();
6383 DebugLoc dl = Op.getDebugLoc();
6385 Op = Op.getOperand(0);
6386 if (VT == MVT::i8) {
6388 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6391 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6392 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6393 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6395 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6396 SmallVector<SDValue, 4> Ops;
6398 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6399 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6400 Ops.push_back(Op.getValue(1));
6401 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6404 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6408 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6409 MVT VT = Op.getValueType();
6410 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6411 DebugLoc dl = Op.getDebugLoc();
6413 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6414 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6415 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6416 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6417 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6419 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6420 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6421 // return AloBlo + AloBhi + AhiBlo;
6423 SDValue A = Op.getOperand(0);
6424 SDValue B = Op.getOperand(1);
6426 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6427 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6428 A, DAG.getConstant(32, MVT::i32));
6429 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6430 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6431 B, DAG.getConstant(32, MVT::i32));
6432 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6433 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6435 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6436 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6438 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6439 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6441 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6442 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6443 AloBhi, DAG.getConstant(32, MVT::i32));
6444 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6445 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6446 AhiBlo, DAG.getConstant(32, MVT::i32));
6447 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6448 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6453 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6454 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6455 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6456 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6457 // has only one use.
6458 SDNode *N = Op.getNode();
6459 SDValue LHS = N->getOperand(0);
6460 SDValue RHS = N->getOperand(1);
6461 unsigned BaseOp = 0;
6463 DebugLoc dl = Op.getDebugLoc();
6465 switch (Op.getOpcode()) {
6466 default: assert(0 && "Unknown ovf instruction!");
6468 // A subtract of one will be selected as a INC. Note that INC doesn't
6469 // set CF, so we can't do this for UADDO.
6470 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6471 if (C->getAPIntValue() == 1) {
6472 BaseOp = X86ISD::INC;
6476 BaseOp = X86ISD::ADD;
6480 BaseOp = X86ISD::ADD;
6484 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6485 // set CF, so we can't do this for USUBO.
6486 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6487 if (C->getAPIntValue() == 1) {
6488 BaseOp = X86ISD::DEC;
6492 BaseOp = X86ISD::SUB;
6496 BaseOp = X86ISD::SUB;
6500 BaseOp = X86ISD::SMUL;
6504 BaseOp = X86ISD::UMUL;
6509 // Also sets EFLAGS.
6510 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6511 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6514 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6515 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6517 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6521 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6522 MVT T = Op.getValueType();
6523 DebugLoc dl = Op.getDebugLoc();
6526 switch(T.getSimpleVT()) {
6528 assert(false && "Invalid value type!");
6529 case MVT::i8: Reg = X86::AL; size = 1; break;
6530 case MVT::i16: Reg = X86::AX; size = 2; break;
6531 case MVT::i32: Reg = X86::EAX; size = 4; break;
6533 assert(Subtarget->is64Bit() && "Node not type legal!");
6534 Reg = X86::RAX; size = 8;
6537 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6538 Op.getOperand(2), SDValue());
6539 SDValue Ops[] = { cpIn.getValue(0),
6542 DAG.getTargetConstant(size, MVT::i8),
6544 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6545 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6547 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6551 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6552 SelectionDAG &DAG) {
6553 assert(Subtarget->is64Bit() && "Result not type legalized?");
6554 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6555 SDValue TheChain = Op.getOperand(0);
6556 DebugLoc dl = Op.getDebugLoc();
6557 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6558 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6559 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6561 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6562 DAG.getConstant(32, MVT::i8));
6564 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6567 return DAG.getMergeValues(Ops, 2, dl);
6570 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6571 SDNode *Node = Op.getNode();
6572 DebugLoc dl = Node->getDebugLoc();
6573 MVT T = Node->getValueType(0);
6574 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6575 DAG.getConstant(0, T), Node->getOperand(2));
6576 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6577 cast<AtomicSDNode>(Node)->getMemoryVT(),
6578 Node->getOperand(0),
6579 Node->getOperand(1), negOp,
6580 cast<AtomicSDNode>(Node)->getSrcValue(),
6581 cast<AtomicSDNode>(Node)->getAlignment());
6584 /// LowerOperation - Provide custom lowering hooks for some operations.
6586 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6587 switch (Op.getOpcode()) {
6588 default: assert(0 && "Should not custom lower this!");
6589 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6590 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6591 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6592 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6593 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6594 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6595 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6596 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6597 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6598 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6599 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6600 case ISD::SHL_PARTS:
6601 case ISD::SRA_PARTS:
6602 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6603 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6604 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6605 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6606 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
6607 case ISD::FABS: return LowerFABS(Op, DAG);
6608 case ISD::FNEG: return LowerFNEG(Op, DAG);
6609 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6610 case ISD::SETCC: return LowerSETCC(Op, DAG);
6611 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6612 case ISD::SELECT: return LowerSELECT(Op, DAG);
6613 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6614 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6615 case ISD::CALL: return LowerCALL(Op, DAG);
6616 case ISD::RET: return LowerRET(Op, DAG);
6617 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6618 case ISD::VASTART: return LowerVASTART(Op, DAG);
6619 case ISD::VAARG: return LowerVAARG(Op, DAG);
6620 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6621 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6622 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6623 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6624 case ISD::FRAME_TO_ARGS_OFFSET:
6625 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6626 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6627 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6628 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6629 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6630 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6631 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6632 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6638 case ISD::UMULO: return LowerXALUO(Op, DAG);
6639 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6643 void X86TargetLowering::
6644 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6645 SelectionDAG &DAG, unsigned NewOp) {
6646 MVT T = Node->getValueType(0);
6647 DebugLoc dl = Node->getDebugLoc();
6648 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6650 SDValue Chain = Node->getOperand(0);
6651 SDValue In1 = Node->getOperand(1);
6652 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6653 Node->getOperand(2), DAG.getIntPtrConstant(0));
6654 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6655 Node->getOperand(2), DAG.getIntPtrConstant(1));
6656 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6657 // have a MemOperand. Pass the info through as a normal operand.
6658 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6659 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6660 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6661 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6662 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6663 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6664 Results.push_back(Result.getValue(2));
6667 /// ReplaceNodeResults - Replace a node with an illegal result type
6668 /// with a new node built out of custom code.
6669 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6670 SmallVectorImpl<SDValue>&Results,
6671 SelectionDAG &DAG) {
6672 DebugLoc dl = N->getDebugLoc();
6673 switch (N->getOpcode()) {
6675 assert(false && "Do not know how to custom type legalize this operation!");
6677 case ISD::FP_TO_SINT: {
6678 std::pair<SDValue,SDValue> Vals =
6679 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
6680 SDValue FIST = Vals.first, StackSlot = Vals.second;
6681 if (FIST.getNode() != 0) {
6682 MVT VT = N->getValueType(0);
6683 // Return a load from the stack slot.
6684 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6688 case ISD::READCYCLECOUNTER: {
6689 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6690 SDValue TheChain = N->getOperand(0);
6691 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6692 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6694 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6696 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6697 SDValue Ops[] = { eax, edx };
6698 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6699 Results.push_back(edx.getValue(1));
6702 case ISD::ATOMIC_CMP_SWAP: {
6703 MVT T = N->getValueType(0);
6704 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6705 SDValue cpInL, cpInH;
6706 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6707 DAG.getConstant(0, MVT::i32));
6708 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6709 DAG.getConstant(1, MVT::i32));
6710 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6711 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6713 SDValue swapInL, swapInH;
6714 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6715 DAG.getConstant(0, MVT::i32));
6716 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6717 DAG.getConstant(1, MVT::i32));
6718 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6720 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6721 swapInL.getValue(1));
6722 SDValue Ops[] = { swapInH.getValue(0),
6724 swapInH.getValue(1) };
6725 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6726 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6727 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6728 MVT::i32, Result.getValue(1));
6729 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6730 MVT::i32, cpOutL.getValue(2));
6731 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6732 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6733 Results.push_back(cpOutH.getValue(1));
6736 case ISD::ATOMIC_LOAD_ADD:
6737 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6739 case ISD::ATOMIC_LOAD_AND:
6740 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6742 case ISD::ATOMIC_LOAD_NAND:
6743 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6745 case ISD::ATOMIC_LOAD_OR:
6746 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6748 case ISD::ATOMIC_LOAD_SUB:
6749 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6751 case ISD::ATOMIC_LOAD_XOR:
6752 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6754 case ISD::ATOMIC_SWAP:
6755 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6760 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6762 default: return NULL;
6763 case X86ISD::BSF: return "X86ISD::BSF";
6764 case X86ISD::BSR: return "X86ISD::BSR";
6765 case X86ISD::SHLD: return "X86ISD::SHLD";
6766 case X86ISD::SHRD: return "X86ISD::SHRD";
6767 case X86ISD::FAND: return "X86ISD::FAND";
6768 case X86ISD::FOR: return "X86ISD::FOR";
6769 case X86ISD::FXOR: return "X86ISD::FXOR";
6770 case X86ISD::FSRL: return "X86ISD::FSRL";
6771 case X86ISD::FILD: return "X86ISD::FILD";
6772 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6773 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6774 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6775 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6776 case X86ISD::FLD: return "X86ISD::FLD";
6777 case X86ISD::FST: return "X86ISD::FST";
6778 case X86ISD::CALL: return "X86ISD::CALL";
6779 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6780 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6781 case X86ISD::BT: return "X86ISD::BT";
6782 case X86ISD::CMP: return "X86ISD::CMP";
6783 case X86ISD::COMI: return "X86ISD::COMI";
6784 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6785 case X86ISD::SETCC: return "X86ISD::SETCC";
6786 case X86ISD::CMOV: return "X86ISD::CMOV";
6787 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6788 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6789 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6790 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6791 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6792 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6793 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6794 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6795 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6796 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6797 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6798 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
6799 case X86ISD::FMAX: return "X86ISD::FMAX";
6800 case X86ISD::FMIN: return "X86ISD::FMIN";
6801 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6802 case X86ISD::FRCP: return "X86ISD::FRCP";
6803 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6804 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
6805 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6806 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6807 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6808 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6809 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6810 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6811 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6812 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6813 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6814 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6815 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6816 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6817 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6818 case X86ISD::VSHL: return "X86ISD::VSHL";
6819 case X86ISD::VSRL: return "X86ISD::VSRL";
6820 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6821 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6822 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6823 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6824 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6825 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6826 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6827 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6828 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6829 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6830 case X86ISD::ADD: return "X86ISD::ADD";
6831 case X86ISD::SUB: return "X86ISD::SUB";
6832 case X86ISD::SMUL: return "X86ISD::SMUL";
6833 case X86ISD::UMUL: return "X86ISD::UMUL";
6834 case X86ISD::INC: return "X86ISD::INC";
6835 case X86ISD::DEC: return "X86ISD::DEC";
6836 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
6840 // isLegalAddressingMode - Return true if the addressing mode represented
6841 // by AM is legal for this target, for a load/store of the specified type.
6842 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6843 const Type *Ty) const {
6844 // X86 supports extremely general addressing modes.
6846 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6847 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6851 // We can only fold this if we don't need an extra load.
6852 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6854 // If BaseGV requires a register, we cannot also have a BaseReg.
6855 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6859 // X86-64 only supports addr of globals in small code model.
6860 if (Subtarget->is64Bit()) {
6861 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6863 // If lower 4G is not available, then we must use rip-relative addressing.
6864 if (AM.BaseOffs || AM.Scale > 1)
6875 // These scales always work.
6880 // These scales are formed with basereg+scalereg. Only accept if there is
6885 default: // Other stuff never works.
6893 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6894 if (!Ty1->isInteger() || !Ty2->isInteger())
6896 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6897 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6898 if (NumBits1 <= NumBits2)
6900 return Subtarget->is64Bit() || NumBits1 < 64;
6903 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6904 if (!VT1.isInteger() || !VT2.isInteger())
6906 unsigned NumBits1 = VT1.getSizeInBits();
6907 unsigned NumBits2 = VT2.getSizeInBits();
6908 if (NumBits1 <= NumBits2)
6910 return Subtarget->is64Bit() || NumBits1 < 64;
6913 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
6914 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6915 return Ty1 == Type::Int32Ty && Ty2 == Type::Int64Ty && Subtarget->is64Bit();
6918 bool X86TargetLowering::isZExtFree(MVT VT1, MVT VT2) const {
6919 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6920 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
6923 bool X86TargetLowering::isNarrowingProfitable(MVT VT1, MVT VT2) const {
6924 // i16 instructions are longer (0x66 prefix) and potentially slower.
6925 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
6928 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6929 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6930 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6931 /// are assumed to be legal.
6933 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6935 // Only do shuffles on 128-bit vector types for now.
6936 if (VT.getSizeInBits() == 64)
6939 // FIXME: pshufb, blends, palignr, shifts.
6940 return (VT.getVectorNumElements() == 2 ||
6941 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6942 isMOVLMask(M, VT) ||
6943 isSHUFPMask(M, VT) ||
6944 isPSHUFDMask(M, VT) ||
6945 isPSHUFHWMask(M, VT) ||
6946 isPSHUFLWMask(M, VT) ||
6947 isUNPCKLMask(M, VT) ||
6948 isUNPCKHMask(M, VT) ||
6949 isUNPCKL_v_undef_Mask(M, VT) ||
6950 isUNPCKH_v_undef_Mask(M, VT));
6954 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
6956 unsigned NumElts = VT.getVectorNumElements();
6957 // FIXME: This collection of masks seems suspect.
6960 if (NumElts == 4 && VT.getSizeInBits() == 128) {
6961 return (isMOVLMask(Mask, VT) ||
6962 isCommutedMOVLMask(Mask, VT, true) ||
6963 isSHUFPMask(Mask, VT) ||
6964 isCommutedSHUFPMask(Mask, VT));
6969 //===----------------------------------------------------------------------===//
6970 // X86 Scheduler Hooks
6971 //===----------------------------------------------------------------------===//
6973 // private utility function
6975 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6976 MachineBasicBlock *MBB,
6984 TargetRegisterClass *RC,
6985 bool invSrc) const {
6986 // For the atomic bitwise operator, we generate
6989 // ld t1 = [bitinstr.addr]
6990 // op t2 = t1, [bitinstr.val]
6992 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6994 // fallthrough -->nextMBB
6995 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6996 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6997 MachineFunction::iterator MBBIter = MBB;
7000 /// First build the CFG
7001 MachineFunction *F = MBB->getParent();
7002 MachineBasicBlock *thisMBB = MBB;
7003 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7004 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7005 F->insert(MBBIter, newMBB);
7006 F->insert(MBBIter, nextMBB);
7008 // Move all successors to thisMBB to nextMBB
7009 nextMBB->transferSuccessors(thisMBB);
7011 // Update thisMBB to fall through to newMBB
7012 thisMBB->addSuccessor(newMBB);
7014 // newMBB jumps to itself and fall through to nextMBB
7015 newMBB->addSuccessor(nextMBB);
7016 newMBB->addSuccessor(newMBB);
7018 // Insert instructions into newMBB based on incoming instruction
7019 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7020 "unexpected number of operands");
7021 DebugLoc dl = bInstr->getDebugLoc();
7022 MachineOperand& destOper = bInstr->getOperand(0);
7023 MachineOperand* argOpers[2 + X86AddrNumOperands];
7024 int numArgs = bInstr->getNumOperands() - 1;
7025 for (int i=0; i < numArgs; ++i)
7026 argOpers[i] = &bInstr->getOperand(i+1);
7028 // x86 address has 4 operands: base, index, scale, and displacement
7029 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7030 int valArgIndx = lastAddrIndx + 1;
7032 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7033 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7034 for (int i=0; i <= lastAddrIndx; ++i)
7035 (*MIB).addOperand(*argOpers[i]);
7037 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7039 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7044 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7045 assert((argOpers[valArgIndx]->isReg() ||
7046 argOpers[valArgIndx]->isImm()) &&
7048 if (argOpers[valArgIndx]->isReg())
7049 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7051 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7053 (*MIB).addOperand(*argOpers[valArgIndx]);
7055 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7058 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7059 for (int i=0; i <= lastAddrIndx; ++i)
7060 (*MIB).addOperand(*argOpers[i]);
7062 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7063 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7065 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7069 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7071 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7075 // private utility function: 64 bit atomics on 32 bit host.
7077 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7078 MachineBasicBlock *MBB,
7083 bool invSrc) const {
7084 // For the atomic bitwise operator, we generate
7085 // thisMBB (instructions are in pairs, except cmpxchg8b)
7086 // ld t1,t2 = [bitinstr.addr]
7088 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7089 // op t5, t6 <- out1, out2, [bitinstr.val]
7090 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7091 // mov ECX, EBX <- t5, t6
7092 // mov EAX, EDX <- t1, t2
7093 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7094 // mov t3, t4 <- EAX, EDX
7096 // result in out1, out2
7097 // fallthrough -->nextMBB
7099 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7100 const unsigned LoadOpc = X86::MOV32rm;
7101 const unsigned copyOpc = X86::MOV32rr;
7102 const unsigned NotOpc = X86::NOT32r;
7103 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7104 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7105 MachineFunction::iterator MBBIter = MBB;
7108 /// First build the CFG
7109 MachineFunction *F = MBB->getParent();
7110 MachineBasicBlock *thisMBB = MBB;
7111 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7112 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7113 F->insert(MBBIter, newMBB);
7114 F->insert(MBBIter, nextMBB);
7116 // Move all successors to thisMBB to nextMBB
7117 nextMBB->transferSuccessors(thisMBB);
7119 // Update thisMBB to fall through to newMBB
7120 thisMBB->addSuccessor(newMBB);
7122 // newMBB jumps to itself and fall through to nextMBB
7123 newMBB->addSuccessor(nextMBB);
7124 newMBB->addSuccessor(newMBB);
7126 DebugLoc dl = bInstr->getDebugLoc();
7127 // Insert instructions into newMBB based on incoming instruction
7128 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7129 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7130 "unexpected number of operands");
7131 MachineOperand& dest1Oper = bInstr->getOperand(0);
7132 MachineOperand& dest2Oper = bInstr->getOperand(1);
7133 MachineOperand* argOpers[2 + X86AddrNumOperands];
7134 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7135 argOpers[i] = &bInstr->getOperand(i+2);
7137 // x86 address has 4 operands: base, index, scale, and displacement
7138 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7140 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7141 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7142 for (int i=0; i <= lastAddrIndx; ++i)
7143 (*MIB).addOperand(*argOpers[i]);
7144 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7145 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7146 // add 4 to displacement.
7147 for (int i=0; i <= lastAddrIndx-2; ++i)
7148 (*MIB).addOperand(*argOpers[i]);
7149 MachineOperand newOp3 = *(argOpers[3]);
7151 newOp3.setImm(newOp3.getImm()+4);
7153 newOp3.setOffset(newOp3.getOffset()+4);
7154 (*MIB).addOperand(newOp3);
7155 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7157 // t3/4 are defined later, at the bottom of the loop
7158 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7159 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7160 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7161 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7162 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7163 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7165 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7166 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7168 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7169 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7175 int valArgIndx = lastAddrIndx + 1;
7176 assert((argOpers[valArgIndx]->isReg() ||
7177 argOpers[valArgIndx]->isImm()) &&
7179 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7180 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7181 if (argOpers[valArgIndx]->isReg())
7182 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7184 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7185 if (regOpcL != X86::MOV32rr)
7187 (*MIB).addOperand(*argOpers[valArgIndx]);
7188 assert(argOpers[valArgIndx + 1]->isReg() ==
7189 argOpers[valArgIndx]->isReg());
7190 assert(argOpers[valArgIndx + 1]->isImm() ==
7191 argOpers[valArgIndx]->isImm());
7192 if (argOpers[valArgIndx + 1]->isReg())
7193 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7195 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7196 if (regOpcH != X86::MOV32rr)
7198 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7200 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7202 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7205 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7207 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7210 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7211 for (int i=0; i <= lastAddrIndx; ++i)
7212 (*MIB).addOperand(*argOpers[i]);
7214 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7215 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7217 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7218 MIB.addReg(X86::EAX);
7219 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7220 MIB.addReg(X86::EDX);
7223 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7225 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7229 // private utility function
7231 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7232 MachineBasicBlock *MBB,
7233 unsigned cmovOpc) const {
7234 // For the atomic min/max operator, we generate
7237 // ld t1 = [min/max.addr]
7238 // mov t2 = [min/max.val]
7240 // cmov[cond] t2 = t1
7242 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7244 // fallthrough -->nextMBB
7246 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7247 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7248 MachineFunction::iterator MBBIter = MBB;
7251 /// First build the CFG
7252 MachineFunction *F = MBB->getParent();
7253 MachineBasicBlock *thisMBB = MBB;
7254 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7255 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7256 F->insert(MBBIter, newMBB);
7257 F->insert(MBBIter, nextMBB);
7259 // Move all successors to thisMBB to nextMBB
7260 nextMBB->transferSuccessors(thisMBB);
7262 // Update thisMBB to fall through to newMBB
7263 thisMBB->addSuccessor(newMBB);
7265 // newMBB jumps to newMBB and fall through to nextMBB
7266 newMBB->addSuccessor(nextMBB);
7267 newMBB->addSuccessor(newMBB);
7269 DebugLoc dl = mInstr->getDebugLoc();
7270 // Insert instructions into newMBB based on incoming instruction
7271 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7272 "unexpected number of operands");
7273 MachineOperand& destOper = mInstr->getOperand(0);
7274 MachineOperand* argOpers[2 + X86AddrNumOperands];
7275 int numArgs = mInstr->getNumOperands() - 1;
7276 for (int i=0; i < numArgs; ++i)
7277 argOpers[i] = &mInstr->getOperand(i+1);
7279 // x86 address has 4 operands: base, index, scale, and displacement
7280 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7281 int valArgIndx = lastAddrIndx + 1;
7283 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7284 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7285 for (int i=0; i <= lastAddrIndx; ++i)
7286 (*MIB).addOperand(*argOpers[i]);
7288 // We only support register and immediate values
7289 assert((argOpers[valArgIndx]->isReg() ||
7290 argOpers[valArgIndx]->isImm()) &&
7293 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7294 if (argOpers[valArgIndx]->isReg())
7295 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7297 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7298 (*MIB).addOperand(*argOpers[valArgIndx]);
7300 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7303 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7308 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7309 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7313 // Cmp and exchange if none has modified the memory location
7314 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7315 for (int i=0; i <= lastAddrIndx; ++i)
7316 (*MIB).addOperand(*argOpers[i]);
7318 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7319 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7321 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7322 MIB.addReg(X86::EAX);
7325 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7327 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7333 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7334 MachineBasicBlock *BB) const {
7335 DebugLoc dl = MI->getDebugLoc();
7336 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7337 switch (MI->getOpcode()) {
7338 default: assert(false && "Unexpected instr type to insert");
7339 case X86::CMOV_V1I64:
7340 case X86::CMOV_FR32:
7341 case X86::CMOV_FR64:
7342 case X86::CMOV_V4F32:
7343 case X86::CMOV_V2F64:
7344 case X86::CMOV_V2I64: {
7345 // To "insert" a SELECT_CC instruction, we actually have to insert the
7346 // diamond control-flow pattern. The incoming instruction knows the
7347 // destination vreg to set, the condition code register to branch on, the
7348 // true/false values to select between, and a branch opcode to use.
7349 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7350 MachineFunction::iterator It = BB;
7356 // cmpTY ccX, r1, r2
7358 // fallthrough --> copy0MBB
7359 MachineBasicBlock *thisMBB = BB;
7360 MachineFunction *F = BB->getParent();
7361 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7362 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7364 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7365 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7366 F->insert(It, copy0MBB);
7367 F->insert(It, sinkMBB);
7368 // Update machine-CFG edges by transferring all successors of the current
7369 // block to the new block which will contain the Phi node for the select.
7370 sinkMBB->transferSuccessors(BB);
7372 // Add the true and fallthrough blocks as its successors.
7373 BB->addSuccessor(copy0MBB);
7374 BB->addSuccessor(sinkMBB);
7377 // %FalseValue = ...
7378 // # fallthrough to sinkMBB
7381 // Update machine-CFG edges
7382 BB->addSuccessor(sinkMBB);
7385 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7388 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7389 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7390 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7392 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7396 case X86::FP32_TO_INT16_IN_MEM:
7397 case X86::FP32_TO_INT32_IN_MEM:
7398 case X86::FP32_TO_INT64_IN_MEM:
7399 case X86::FP64_TO_INT16_IN_MEM:
7400 case X86::FP64_TO_INT32_IN_MEM:
7401 case X86::FP64_TO_INT64_IN_MEM:
7402 case X86::FP80_TO_INT16_IN_MEM:
7403 case X86::FP80_TO_INT32_IN_MEM:
7404 case X86::FP80_TO_INT64_IN_MEM: {
7405 // Change the floating point control register to use "round towards zero"
7406 // mode when truncating to an integer value.
7407 MachineFunction *F = BB->getParent();
7408 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7409 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7411 // Load the old value of the high byte of the control word...
7413 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7414 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7417 // Set the high part to be round to zero...
7418 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7421 // Reload the modified control word now...
7422 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7424 // Restore the memory image of control word to original value
7425 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7428 // Get the X86 opcode to use.
7430 switch (MI->getOpcode()) {
7431 default: assert(0 && "illegal opcode!");
7432 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7433 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7434 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7435 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7436 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7437 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7438 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7439 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7440 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7444 MachineOperand &Op = MI->getOperand(0);
7446 AM.BaseType = X86AddressMode::RegBase;
7447 AM.Base.Reg = Op.getReg();
7449 AM.BaseType = X86AddressMode::FrameIndexBase;
7450 AM.Base.FrameIndex = Op.getIndex();
7452 Op = MI->getOperand(1);
7454 AM.Scale = Op.getImm();
7455 Op = MI->getOperand(2);
7457 AM.IndexReg = Op.getImm();
7458 Op = MI->getOperand(3);
7459 if (Op.isGlobal()) {
7460 AM.GV = Op.getGlobal();
7462 AM.Disp = Op.getImm();
7464 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7465 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7467 // Reload the original control word now.
7468 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7470 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7473 case X86::ATOMAND32:
7474 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7475 X86::AND32ri, X86::MOV32rm,
7476 X86::LCMPXCHG32, X86::MOV32rr,
7477 X86::NOT32r, X86::EAX,
7478 X86::GR32RegisterClass);
7480 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7481 X86::OR32ri, X86::MOV32rm,
7482 X86::LCMPXCHG32, X86::MOV32rr,
7483 X86::NOT32r, X86::EAX,
7484 X86::GR32RegisterClass);
7485 case X86::ATOMXOR32:
7486 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7487 X86::XOR32ri, X86::MOV32rm,
7488 X86::LCMPXCHG32, X86::MOV32rr,
7489 X86::NOT32r, X86::EAX,
7490 X86::GR32RegisterClass);
7491 case X86::ATOMNAND32:
7492 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7493 X86::AND32ri, X86::MOV32rm,
7494 X86::LCMPXCHG32, X86::MOV32rr,
7495 X86::NOT32r, X86::EAX,
7496 X86::GR32RegisterClass, true);
7497 case X86::ATOMMIN32:
7498 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7499 case X86::ATOMMAX32:
7500 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7501 case X86::ATOMUMIN32:
7502 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7503 case X86::ATOMUMAX32:
7504 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7506 case X86::ATOMAND16:
7507 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7508 X86::AND16ri, X86::MOV16rm,
7509 X86::LCMPXCHG16, X86::MOV16rr,
7510 X86::NOT16r, X86::AX,
7511 X86::GR16RegisterClass);
7513 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7514 X86::OR16ri, X86::MOV16rm,
7515 X86::LCMPXCHG16, X86::MOV16rr,
7516 X86::NOT16r, X86::AX,
7517 X86::GR16RegisterClass);
7518 case X86::ATOMXOR16:
7519 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7520 X86::XOR16ri, X86::MOV16rm,
7521 X86::LCMPXCHG16, X86::MOV16rr,
7522 X86::NOT16r, X86::AX,
7523 X86::GR16RegisterClass);
7524 case X86::ATOMNAND16:
7525 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7526 X86::AND16ri, X86::MOV16rm,
7527 X86::LCMPXCHG16, X86::MOV16rr,
7528 X86::NOT16r, X86::AX,
7529 X86::GR16RegisterClass, true);
7530 case X86::ATOMMIN16:
7531 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7532 case X86::ATOMMAX16:
7533 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7534 case X86::ATOMUMIN16:
7535 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7536 case X86::ATOMUMAX16:
7537 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7540 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7541 X86::AND8ri, X86::MOV8rm,
7542 X86::LCMPXCHG8, X86::MOV8rr,
7543 X86::NOT8r, X86::AL,
7544 X86::GR8RegisterClass);
7546 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7547 X86::OR8ri, X86::MOV8rm,
7548 X86::LCMPXCHG8, X86::MOV8rr,
7549 X86::NOT8r, X86::AL,
7550 X86::GR8RegisterClass);
7552 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7553 X86::XOR8ri, X86::MOV8rm,
7554 X86::LCMPXCHG8, X86::MOV8rr,
7555 X86::NOT8r, X86::AL,
7556 X86::GR8RegisterClass);
7557 case X86::ATOMNAND8:
7558 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7559 X86::AND8ri, X86::MOV8rm,
7560 X86::LCMPXCHG8, X86::MOV8rr,
7561 X86::NOT8r, X86::AL,
7562 X86::GR8RegisterClass, true);
7563 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7564 // This group is for 64-bit host.
7565 case X86::ATOMAND64:
7566 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7567 X86::AND64ri32, X86::MOV64rm,
7568 X86::LCMPXCHG64, X86::MOV64rr,
7569 X86::NOT64r, X86::RAX,
7570 X86::GR64RegisterClass);
7572 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7573 X86::OR64ri32, X86::MOV64rm,
7574 X86::LCMPXCHG64, X86::MOV64rr,
7575 X86::NOT64r, X86::RAX,
7576 X86::GR64RegisterClass);
7577 case X86::ATOMXOR64:
7578 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7579 X86::XOR64ri32, X86::MOV64rm,
7580 X86::LCMPXCHG64, X86::MOV64rr,
7581 X86::NOT64r, X86::RAX,
7582 X86::GR64RegisterClass);
7583 case X86::ATOMNAND64:
7584 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7585 X86::AND64ri32, X86::MOV64rm,
7586 X86::LCMPXCHG64, X86::MOV64rr,
7587 X86::NOT64r, X86::RAX,
7588 X86::GR64RegisterClass, true);
7589 case X86::ATOMMIN64:
7590 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7591 case X86::ATOMMAX64:
7592 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7593 case X86::ATOMUMIN64:
7594 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7595 case X86::ATOMUMAX64:
7596 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7598 // This group does 64-bit operations on a 32-bit host.
7599 case X86::ATOMAND6432:
7600 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7601 X86::AND32rr, X86::AND32rr,
7602 X86::AND32ri, X86::AND32ri,
7604 case X86::ATOMOR6432:
7605 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7606 X86::OR32rr, X86::OR32rr,
7607 X86::OR32ri, X86::OR32ri,
7609 case X86::ATOMXOR6432:
7610 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7611 X86::XOR32rr, X86::XOR32rr,
7612 X86::XOR32ri, X86::XOR32ri,
7614 case X86::ATOMNAND6432:
7615 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7616 X86::AND32rr, X86::AND32rr,
7617 X86::AND32ri, X86::AND32ri,
7619 case X86::ATOMADD6432:
7620 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7621 X86::ADD32rr, X86::ADC32rr,
7622 X86::ADD32ri, X86::ADC32ri,
7624 case X86::ATOMSUB6432:
7625 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7626 X86::SUB32rr, X86::SBB32rr,
7627 X86::SUB32ri, X86::SBB32ri,
7629 case X86::ATOMSWAP6432:
7630 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7631 X86::MOV32rr, X86::MOV32rr,
7632 X86::MOV32ri, X86::MOV32ri,
7637 //===----------------------------------------------------------------------===//
7638 // X86 Optimization Hooks
7639 //===----------------------------------------------------------------------===//
7641 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7645 const SelectionDAG &DAG,
7646 unsigned Depth) const {
7647 unsigned Opc = Op.getOpcode();
7648 assert((Opc >= ISD::BUILTIN_OP_END ||
7649 Opc == ISD::INTRINSIC_WO_CHAIN ||
7650 Opc == ISD::INTRINSIC_W_CHAIN ||
7651 Opc == ISD::INTRINSIC_VOID) &&
7652 "Should use MaskedValueIsZero if you don't know whether Op"
7653 " is a target node!");
7655 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7664 // These nodes' second result is a boolean.
7665 if (Op.getResNo() == 0)
7669 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7670 Mask.getBitWidth() - 1);
7675 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7676 /// node is a GlobalAddress + offset.
7677 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7678 GlobalValue* &GA, int64_t &Offset) const{
7679 if (N->getOpcode() == X86ISD::Wrapper) {
7680 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7681 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7682 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7686 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7689 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7690 const TargetLowering &TLI) {
7693 if (TLI.isGAPlusOffset(Base, GV, Offset))
7694 return (GV->getAlignment() >= N && (Offset % N) == 0);
7695 // DAG combine handles the stack object case.
7699 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
7700 MVT EVT, LoadSDNode *&LDBase,
7701 unsigned &LastLoadedElt,
7702 SelectionDAG &DAG, MachineFrameInfo *MFI,
7703 const TargetLowering &TLI) {
7705 LastLoadedElt = -1U;
7706 for (unsigned i = 0; i < NumElems; ++i) {
7707 if (N->getMaskElt(i) < 0) {
7713 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7714 if (!Elt.getNode() ||
7715 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7718 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
7720 LDBase = cast<LoadSDNode>(Elt.getNode());
7724 if (Elt.getOpcode() == ISD::UNDEF)
7727 LoadSDNode *LD = cast<LoadSDNode>(Elt);
7728 if (!TLI.isConsecutiveLoad(LD, LDBase, EVT.getSizeInBits()/8, i, MFI))
7735 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7736 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7737 /// if the load addresses are consecutive, non-overlapping, and in the right
7738 /// order. In the case of v2i64, it will see if it can rewrite the
7739 /// shuffle to be an appropriate build vector so it can take advantage of
7740 // performBuildVectorCombine.
7741 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7742 const TargetLowering &TLI) {
7743 DebugLoc dl = N->getDebugLoc();
7744 MVT VT = N->getValueType(0);
7745 MVT EVT = VT.getVectorElementType();
7746 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7747 unsigned NumElems = VT.getVectorNumElements();
7749 if (VT.getSizeInBits() != 128)
7752 // Try to combine a vector_shuffle into a 128-bit load.
7753 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7754 LoadSDNode *LD = NULL;
7755 unsigned LastLoadedElt;
7756 if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, LD, LastLoadedElt, DAG,
7760 if (LastLoadedElt == NumElems - 1) {
7761 if (isBaseAlignmentOfN(16, LD->getBasePtr().getNode(), TLI))
7762 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7763 LD->getSrcValue(), LD->getSrcValueOffset(),
7765 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7766 LD->getSrcValue(), LD->getSrcValueOffset(),
7767 LD->isVolatile(), LD->getAlignment());
7768 } else if (NumElems == 4 && LastLoadedElt == 1) {
7769 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
7770 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7771 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7772 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
7777 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7778 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7779 const X86Subtarget *Subtarget) {
7780 DebugLoc DL = N->getDebugLoc();
7781 SDValue Cond = N->getOperand(0);
7782 // Get the LHS/RHS of the select.
7783 SDValue LHS = N->getOperand(1);
7784 SDValue RHS = N->getOperand(2);
7786 // If we have SSE[12] support, try to form min/max nodes.
7787 if (Subtarget->hasSSE2() &&
7788 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
7789 Cond.getOpcode() == ISD::SETCC) {
7790 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7792 unsigned Opcode = 0;
7793 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7796 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7799 if (!UnsafeFPMath) break;
7801 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7803 Opcode = X86ISD::FMIN;
7806 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7809 if (!UnsafeFPMath) break;
7811 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7813 Opcode = X86ISD::FMAX;
7816 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7819 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7822 if (!UnsafeFPMath) break;
7824 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7826 Opcode = X86ISD::FMIN;
7829 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7832 if (!UnsafeFPMath) break;
7834 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7836 Opcode = X86ISD::FMAX;
7842 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
7845 // If this is a select between two integer constants, try to do some
7847 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
7848 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
7849 // Don't do this for crazy integer types.
7850 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
7851 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
7852 // so that TrueC (the true value) is larger than FalseC.
7853 bool NeedsCondInvert = false;
7855 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
7856 // Efficiently invertible.
7857 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
7858 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
7859 isa<ConstantSDNode>(Cond.getOperand(1))))) {
7860 NeedsCondInvert = true;
7861 std::swap(TrueC, FalseC);
7864 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
7865 if (FalseC->getAPIntValue() == 0 &&
7866 TrueC->getAPIntValue().isPowerOf2()) {
7867 if (NeedsCondInvert) // Invert the condition if needed.
7868 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7869 DAG.getConstant(1, Cond.getValueType()));
7871 // Zero extend the condition if needed.
7872 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
7874 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7875 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
7876 DAG.getConstant(ShAmt, MVT::i8));
7879 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
7880 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
7881 if (NeedsCondInvert) // Invert the condition if needed.
7882 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7883 DAG.getConstant(1, Cond.getValueType()));
7885 // Zero extend the condition if needed.
7886 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
7887 FalseC->getValueType(0), Cond);
7888 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7889 SDValue(FalseC, 0));
7892 // Optimize cases that will turn into an LEA instruction. This requires
7893 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
7894 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
7895 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
7896 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
7898 bool isFastMultiplier = false;
7900 switch ((unsigned char)Diff) {
7902 case 1: // result = add base, cond
7903 case 2: // result = lea base( , cond*2)
7904 case 3: // result = lea base(cond, cond*2)
7905 case 4: // result = lea base( , cond*4)
7906 case 5: // result = lea base(cond, cond*4)
7907 case 8: // result = lea base( , cond*8)
7908 case 9: // result = lea base(cond, cond*8)
7909 isFastMultiplier = true;
7914 if (isFastMultiplier) {
7915 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
7916 if (NeedsCondInvert) // Invert the condition if needed.
7917 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7918 DAG.getConstant(1, Cond.getValueType()));
7920 // Zero extend the condition if needed.
7921 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
7923 // Scale the condition by the difference.
7925 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
7926 DAG.getConstant(Diff, Cond.getValueType()));
7928 // Add the base if non-zero.
7929 if (FalseC->getAPIntValue() != 0)
7930 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7931 SDValue(FalseC, 0));
7941 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
7942 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
7943 TargetLowering::DAGCombinerInfo &DCI) {
7944 DebugLoc DL = N->getDebugLoc();
7946 // If the flag operand isn't dead, don't touch this CMOV.
7947 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
7950 // If this is a select between two integer constants, try to do some
7951 // optimizations. Note that the operands are ordered the opposite of SELECT
7953 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7954 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7955 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
7956 // larger than FalseC (the false value).
7957 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
7959 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
7960 CC = X86::GetOppositeBranchCondition(CC);
7961 std::swap(TrueC, FalseC);
7964 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
7965 // This is efficient for any integer data type (including i8/i16) and
7967 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
7968 SDValue Cond = N->getOperand(3);
7969 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
7970 DAG.getConstant(CC, MVT::i8), Cond);
7972 // Zero extend the condition if needed.
7973 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
7975 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7976 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
7977 DAG.getConstant(ShAmt, MVT::i8));
7978 if (N->getNumValues() == 2) // Dead flag value?
7979 return DCI.CombineTo(N, Cond, SDValue());
7983 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
7984 // for any integer data type, including i8/i16.
7985 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
7986 SDValue Cond = N->getOperand(3);
7987 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
7988 DAG.getConstant(CC, MVT::i8), Cond);
7990 // Zero extend the condition if needed.
7991 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
7992 FalseC->getValueType(0), Cond);
7993 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7994 SDValue(FalseC, 0));
7996 if (N->getNumValues() == 2) // Dead flag value?
7997 return DCI.CombineTo(N, Cond, SDValue());
8001 // Optimize cases that will turn into an LEA instruction. This requires
8002 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8003 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8004 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8005 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8007 bool isFastMultiplier = false;
8009 switch ((unsigned char)Diff) {
8011 case 1: // result = add base, cond
8012 case 2: // result = lea base( , cond*2)
8013 case 3: // result = lea base(cond, cond*2)
8014 case 4: // result = lea base( , cond*4)
8015 case 5: // result = lea base(cond, cond*4)
8016 case 8: // result = lea base( , cond*8)
8017 case 9: // result = lea base(cond, cond*8)
8018 isFastMultiplier = true;
8023 if (isFastMultiplier) {
8024 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8025 SDValue Cond = N->getOperand(3);
8026 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8027 DAG.getConstant(CC, MVT::i8), Cond);
8028 // Zero extend the condition if needed.
8029 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8031 // Scale the condition by the difference.
8033 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8034 DAG.getConstant(Diff, Cond.getValueType()));
8036 // Add the base if non-zero.
8037 if (FalseC->getAPIntValue() != 0)
8038 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8039 SDValue(FalseC, 0));
8040 if (N->getNumValues() == 2) // Dead flag value?
8041 return DCI.CombineTo(N, Cond, SDValue());
8051 /// PerformMulCombine - Optimize a single multiply with constant into two
8052 /// in order to implement it with two cheaper instructions, e.g.
8053 /// LEA + SHL, LEA + LEA.
8054 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8055 TargetLowering::DAGCombinerInfo &DCI) {
8056 if (DAG.getMachineFunction().
8057 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8060 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8063 MVT VT = N->getValueType(0);
8067 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8070 uint64_t MulAmt = C->getZExtValue();
8071 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8074 uint64_t MulAmt1 = 0;
8075 uint64_t MulAmt2 = 0;
8076 if ((MulAmt % 9) == 0) {
8078 MulAmt2 = MulAmt / 9;
8079 } else if ((MulAmt % 5) == 0) {
8081 MulAmt2 = MulAmt / 5;
8082 } else if ((MulAmt % 3) == 0) {
8084 MulAmt2 = MulAmt / 3;
8087 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8088 DebugLoc DL = N->getDebugLoc();
8090 if (isPowerOf2_64(MulAmt2) &&
8091 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8092 // If second multiplifer is pow2, issue it first. We want the multiply by
8093 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8095 std::swap(MulAmt1, MulAmt2);
8098 if (isPowerOf2_64(MulAmt1))
8099 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8100 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8102 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8103 DAG.getConstant(MulAmt1, VT));
8105 if (isPowerOf2_64(MulAmt2))
8106 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8107 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8109 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8110 DAG.getConstant(MulAmt2, VT));
8112 // Do not add new nodes to DAG combiner worklist.
8113 DCI.CombineTo(N, NewMul, false);
8119 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8121 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8122 const X86Subtarget *Subtarget) {
8123 // On X86 with SSE2 support, we can transform this to a vector shift if
8124 // all elements are shifted by the same amount. We can't do this in legalize
8125 // because the a constant vector is typically transformed to a constant pool
8126 // so we have no knowledge of the shift amount.
8127 if (!Subtarget->hasSSE2())
8130 MVT VT = N->getValueType(0);
8131 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8134 SDValue ShAmtOp = N->getOperand(1);
8135 MVT EltVT = VT.getVectorElementType();
8136 DebugLoc DL = N->getDebugLoc();
8138 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8139 unsigned NumElts = VT.getVectorNumElements();
8141 for (; i != NumElts; ++i) {
8142 SDValue Arg = ShAmtOp.getOperand(i);
8143 if (Arg.getOpcode() == ISD::UNDEF) continue;
8147 for (; i != NumElts; ++i) {
8148 SDValue Arg = ShAmtOp.getOperand(i);
8149 if (Arg.getOpcode() == ISD::UNDEF) continue;
8150 if (Arg != BaseShAmt) {
8154 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8155 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8156 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8157 DAG.getIntPtrConstant(0));
8161 if (EltVT.bitsGT(MVT::i32))
8162 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8163 else if (EltVT.bitsLT(MVT::i32))
8164 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8166 // The shift amount is identical so we can do a vector shift.
8167 SDValue ValOp = N->getOperand(0);
8168 switch (N->getOpcode()) {
8170 assert(0 && "Unknown shift opcode!");
8173 if (VT == MVT::v2i64)
8174 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8175 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8177 if (VT == MVT::v4i32)
8178 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8179 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8181 if (VT == MVT::v8i16)
8182 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8183 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8187 if (VT == MVT::v4i32)
8188 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8189 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8191 if (VT == MVT::v8i16)
8192 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8193 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8197 if (VT == MVT::v2i64)
8198 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8199 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8201 if (VT == MVT::v4i32)
8202 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8203 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8205 if (VT == MVT::v8i16)
8206 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8207 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8214 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8215 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8216 const X86Subtarget *Subtarget) {
8217 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8218 // the FP state in cases where an emms may be missing.
8219 // A preferable solution to the general problem is to figure out the right
8220 // places to insert EMMS. This qualifies as a quick hack.
8222 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8223 StoreSDNode *St = cast<StoreSDNode>(N);
8224 MVT VT = St->getValue().getValueType();
8225 if (VT.getSizeInBits() != 64)
8228 const Function *F = DAG.getMachineFunction().getFunction();
8229 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
8230 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
8231 && Subtarget->hasSSE2();
8232 if ((VT.isVector() ||
8233 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8234 isa<LoadSDNode>(St->getValue()) &&
8235 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8236 St->getChain().hasOneUse() && !St->isVolatile()) {
8237 SDNode* LdVal = St->getValue().getNode();
8239 int TokenFactorIndex = -1;
8240 SmallVector<SDValue, 8> Ops;
8241 SDNode* ChainVal = St->getChain().getNode();
8242 // Must be a store of a load. We currently handle two cases: the load
8243 // is a direct child, and it's under an intervening TokenFactor. It is
8244 // possible to dig deeper under nested TokenFactors.
8245 if (ChainVal == LdVal)
8246 Ld = cast<LoadSDNode>(St->getChain());
8247 else if (St->getValue().hasOneUse() &&
8248 ChainVal->getOpcode() == ISD::TokenFactor) {
8249 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8250 if (ChainVal->getOperand(i).getNode() == LdVal) {
8251 TokenFactorIndex = i;
8252 Ld = cast<LoadSDNode>(St->getValue());
8254 Ops.push_back(ChainVal->getOperand(i));
8258 if (!Ld || !ISD::isNormalLoad(Ld))
8261 // If this is not the MMX case, i.e. we are just turning i64 load/store
8262 // into f64 load/store, avoid the transformation if there are multiple
8263 // uses of the loaded value.
8264 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8267 DebugLoc LdDL = Ld->getDebugLoc();
8268 DebugLoc StDL = N->getDebugLoc();
8269 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8270 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8272 if (Subtarget->is64Bit() || F64IsLegal) {
8273 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8274 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8275 Ld->getBasePtr(), Ld->getSrcValue(),
8276 Ld->getSrcValueOffset(), Ld->isVolatile(),
8277 Ld->getAlignment());
8278 SDValue NewChain = NewLd.getValue(1);
8279 if (TokenFactorIndex != -1) {
8280 Ops.push_back(NewChain);
8281 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8284 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8285 St->getSrcValue(), St->getSrcValueOffset(),
8286 St->isVolatile(), St->getAlignment());
8289 // Otherwise, lower to two pairs of 32-bit loads / stores.
8290 SDValue LoAddr = Ld->getBasePtr();
8291 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8292 DAG.getConstant(4, MVT::i32));
8294 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8295 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8296 Ld->isVolatile(), Ld->getAlignment());
8297 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8298 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8300 MinAlign(Ld->getAlignment(), 4));
8302 SDValue NewChain = LoLd.getValue(1);
8303 if (TokenFactorIndex != -1) {
8304 Ops.push_back(LoLd);
8305 Ops.push_back(HiLd);
8306 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8310 LoAddr = St->getBasePtr();
8311 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8312 DAG.getConstant(4, MVT::i32));
8314 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8315 St->getSrcValue(), St->getSrcValueOffset(),
8316 St->isVolatile(), St->getAlignment());
8317 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8319 St->getSrcValueOffset() + 4,
8321 MinAlign(St->getAlignment(), 4));
8322 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8327 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8328 /// X86ISD::FXOR nodes.
8329 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8330 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8331 // F[X]OR(0.0, x) -> x
8332 // F[X]OR(x, 0.0) -> x
8333 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8334 if (C->getValueAPF().isPosZero())
8335 return N->getOperand(1);
8336 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8337 if (C->getValueAPF().isPosZero())
8338 return N->getOperand(0);
8342 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8343 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8344 // FAND(0.0, x) -> 0.0
8345 // FAND(x, 0.0) -> 0.0
8346 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8347 if (C->getValueAPF().isPosZero())
8348 return N->getOperand(0);
8349 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8350 if (C->getValueAPF().isPosZero())
8351 return N->getOperand(1);
8355 static SDValue PerformBTCombine(SDNode *N,
8357 TargetLowering::DAGCombinerInfo &DCI) {
8358 // BT ignores high bits in the bit index operand.
8359 SDValue Op1 = N->getOperand(1);
8360 if (Op1.hasOneUse()) {
8361 unsigned BitWidth = Op1.getValueSizeInBits();
8362 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8363 APInt KnownZero, KnownOne;
8364 TargetLowering::TargetLoweringOpt TLO(DAG);
8365 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8366 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8367 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8368 DCI.CommitTargetLoweringOpt(TLO);
8373 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
8374 SDValue Op = N->getOperand(0);
8375 if (Op.getOpcode() == ISD::BIT_CONVERT)
8376 Op = Op.getOperand(0);
8377 MVT VT = N->getValueType(0), OpVT = Op.getValueType();
8378 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
8379 VT.getVectorElementType().getSizeInBits() ==
8380 OpVT.getVectorElementType().getSizeInBits()) {
8381 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
8386 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8387 DAGCombinerInfo &DCI) const {
8388 SelectionDAG &DAG = DCI.DAG;
8389 switch (N->getOpcode()) {
8391 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8392 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8393 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
8394 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
8397 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8398 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8400 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8401 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8402 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8403 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
8409 //===----------------------------------------------------------------------===//
8410 // X86 Inline Assembly Support
8411 //===----------------------------------------------------------------------===//
8413 /// getConstraintType - Given a constraint letter, return the type of
8414 /// constraint it is for this target.
8415 X86TargetLowering::ConstraintType
8416 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8417 if (Constraint.size() == 1) {
8418 switch (Constraint[0]) {
8430 return C_RegisterClass;
8438 return TargetLowering::getConstraintType(Constraint);
8441 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8442 /// with another that has more specific requirements based on the type of the
8443 /// corresponding operand.
8444 const char *X86TargetLowering::
8445 LowerXConstraint(MVT ConstraintVT) const {
8446 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8447 // 'f' like normal targets.
8448 if (ConstraintVT.isFloatingPoint()) {
8449 if (Subtarget->hasSSE2())
8451 if (Subtarget->hasSSE1())
8455 return TargetLowering::LowerXConstraint(ConstraintVT);
8458 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8459 /// vector. If it is invalid, don't add anything to Ops.
8460 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8463 std::vector<SDValue>&Ops,
8464 SelectionDAG &DAG) const {
8465 SDValue Result(0, 0);
8467 switch (Constraint) {
8470 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8471 if (C->getZExtValue() <= 31) {
8472 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8478 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8479 if (C->getZExtValue() <= 63) {
8480 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8486 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8487 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
8488 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8494 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8495 if (C->getZExtValue() <= 255) {
8496 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8502 // 32-bit signed value
8503 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8504 const ConstantInt *CI = C->getConstantIntValue();
8505 if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8506 // Widen to 64 bits here to get it sign extended.
8507 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8510 // FIXME gcc accepts some relocatable values here too, but only in certain
8511 // memory models; it's complicated.
8516 // 32-bit unsigned value
8517 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8518 const ConstantInt *CI = C->getConstantIntValue();
8519 if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8520 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8524 // FIXME gcc accepts some relocatable values here too, but only in certain
8525 // memory models; it's complicated.
8529 // Literal immediates are always ok.
8530 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8531 // Widen to 64 bits here to get it sign extended.
8532 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8536 // If we are in non-pic codegen mode, we allow the address of a global (with
8537 // an optional displacement) to be used with 'i'.
8538 GlobalAddressSDNode *GA = 0;
8541 // Match either (GA), (GA+C), (GA+C1+C2), etc.
8543 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
8544 Offset += GA->getOffset();
8546 } else if (Op.getOpcode() == ISD::ADD) {
8547 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8548 Offset += C->getZExtValue();
8549 Op = Op.getOperand(0);
8552 } else if (Op.getOpcode() == ISD::SUB) {
8553 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8554 Offset += -C->getZExtValue();
8555 Op = Op.getOperand(0);
8560 // Otherwise, this isn't something we can handle, reject it.
8565 Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(), Offset, DAG);
8567 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8574 if (Result.getNode()) {
8575 Ops.push_back(Result);
8578 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8582 std::vector<unsigned> X86TargetLowering::
8583 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8585 if (Constraint.size() == 1) {
8586 // FIXME: not handling fp-stack yet!
8587 switch (Constraint[0]) { // GCC X86 Constraint Letters
8588 default: break; // Unknown constraint letter
8589 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8592 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8593 else if (VT == MVT::i16)
8594 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8595 else if (VT == MVT::i8)
8596 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8597 else if (VT == MVT::i64)
8598 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8603 return std::vector<unsigned>();
8606 std::pair<unsigned, const TargetRegisterClass*>
8607 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8609 // First, see if this is a constraint that directly corresponds to an LLVM
8611 if (Constraint.size() == 1) {
8612 // GCC Constraint Letters
8613 switch (Constraint[0]) {
8615 case 'r': // GENERAL_REGS
8616 case 'R': // LEGACY_REGS
8617 case 'l': // INDEX_REGS
8619 return std::make_pair(0U, X86::GR8RegisterClass);
8621 return std::make_pair(0U, X86::GR16RegisterClass);
8622 if (VT == MVT::i32 || !Subtarget->is64Bit())
8623 return std::make_pair(0U, X86::GR32RegisterClass);
8624 return std::make_pair(0U, X86::GR64RegisterClass);
8625 case 'f': // FP Stack registers.
8626 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8627 // value to the correct fpstack register class.
8628 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8629 return std::make_pair(0U, X86::RFP32RegisterClass);
8630 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8631 return std::make_pair(0U, X86::RFP64RegisterClass);
8632 return std::make_pair(0U, X86::RFP80RegisterClass);
8633 case 'y': // MMX_REGS if MMX allowed.
8634 if (!Subtarget->hasMMX()) break;
8635 return std::make_pair(0U, X86::VR64RegisterClass);
8636 case 'Y': // SSE_REGS if SSE2 allowed
8637 if (!Subtarget->hasSSE2()) break;
8639 case 'x': // SSE_REGS if SSE1 allowed
8640 if (!Subtarget->hasSSE1()) break;
8642 switch (VT.getSimpleVT()) {
8644 // Scalar SSE types.
8647 return std::make_pair(0U, X86::FR32RegisterClass);
8650 return std::make_pair(0U, X86::FR64RegisterClass);
8658 return std::make_pair(0U, X86::VR128RegisterClass);
8664 // Use the default implementation in TargetLowering to convert the register
8665 // constraint into a member of a register class.
8666 std::pair<unsigned, const TargetRegisterClass*> Res;
8667 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8669 // Not found as a standard register?
8670 if (Res.second == 0) {
8671 // GCC calls "st(0)" just plain "st".
8672 if (StringsEqualNoCase("{st}", Constraint)) {
8673 Res.first = X86::ST0;
8674 Res.second = X86::RFP80RegisterClass;
8676 // 'A' means EAX + EDX.
8677 if (Constraint == "A") {
8678 Res.first = X86::EAX;
8679 Res.second = X86::GRADRegisterClass;
8684 // Otherwise, check to see if this is a register class of the wrong value
8685 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8686 // turn into {ax},{dx}.
8687 if (Res.second->hasType(VT))
8688 return Res; // Correct type already, nothing to do.
8690 // All of the single-register GCC register classes map their values onto
8691 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8692 // really want an 8-bit or 32-bit register, map to the appropriate register
8693 // class and return the appropriate register.
8694 if (Res.second == X86::GR16RegisterClass) {
8695 if (VT == MVT::i8) {
8696 unsigned DestReg = 0;
8697 switch (Res.first) {
8699 case X86::AX: DestReg = X86::AL; break;
8700 case X86::DX: DestReg = X86::DL; break;
8701 case X86::CX: DestReg = X86::CL; break;
8702 case X86::BX: DestReg = X86::BL; break;
8705 Res.first = DestReg;
8706 Res.second = X86::GR8RegisterClass;
8708 } else if (VT == MVT::i32) {
8709 unsigned DestReg = 0;
8710 switch (Res.first) {
8712 case X86::AX: DestReg = X86::EAX; break;
8713 case X86::DX: DestReg = X86::EDX; break;
8714 case X86::CX: DestReg = X86::ECX; break;
8715 case X86::BX: DestReg = X86::EBX; break;
8716 case X86::SI: DestReg = X86::ESI; break;
8717 case X86::DI: DestReg = X86::EDI; break;
8718 case X86::BP: DestReg = X86::EBP; break;
8719 case X86::SP: DestReg = X86::ESP; break;
8722 Res.first = DestReg;
8723 Res.second = X86::GR32RegisterClass;
8725 } else if (VT == MVT::i64) {
8726 unsigned DestReg = 0;
8727 switch (Res.first) {
8729 case X86::AX: DestReg = X86::RAX; break;
8730 case X86::DX: DestReg = X86::RDX; break;
8731 case X86::CX: DestReg = X86::RCX; break;
8732 case X86::BX: DestReg = X86::RBX; break;
8733 case X86::SI: DestReg = X86::RSI; break;
8734 case X86::DI: DestReg = X86::RDI; break;
8735 case X86::BP: DestReg = X86::RBP; break;
8736 case X86::SP: DestReg = X86::RSP; break;
8739 Res.first = DestReg;
8740 Res.second = X86::GR64RegisterClass;
8743 } else if (Res.second == X86::FR32RegisterClass ||
8744 Res.second == X86::FR64RegisterClass ||
8745 Res.second == X86::VR128RegisterClass) {
8746 // Handle references to XMM physical registers that got mapped into the
8747 // wrong class. This can happen with constraints like {xmm0} where the
8748 // target independent register mapper will just pick the first match it can
8749 // find, ignoring the required type.
8751 Res.second = X86::FR32RegisterClass;
8752 else if (VT == MVT::f64)
8753 Res.second = X86::FR64RegisterClass;
8754 else if (X86::VR128RegisterClass->hasType(VT))
8755 Res.second = X86::VR128RegisterClass;
8761 //===----------------------------------------------------------------------===//
8762 // X86 Widen vector type
8763 //===----------------------------------------------------------------------===//
8765 /// getWidenVectorType: given a vector type, returns the type to widen
8766 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8767 /// If there is no vector type that we want to widen to, returns MVT::Other
8768 /// When and where to widen is target dependent based on the cost of
8769 /// scalarizing vs using the wider vector type.
8771 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8772 assert(VT.isVector());
8773 if (isTypeLegal(VT))
8776 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8777 // type based on element type. This would speed up our search (though
8778 // it may not be worth it since the size of the list is relatively
8780 MVT EltVT = VT.getVectorElementType();
8781 unsigned NElts = VT.getVectorNumElements();
8783 // On X86, it make sense to widen any vector wider than 1
8787 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8788 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8789 MVT SVT = (MVT::SimpleValueType)nVT;
8791 if (isTypeLegal(SVT) &&
8792 SVT.getVectorElementType() == EltVT &&
8793 SVT.getVectorNumElements() > NElts)