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 "X86TargetObjectFile.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalAlias.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Function.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/LLVMContext.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/ADT/VectorExtras.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/raw_ostream.h"
49 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
51 // Disable16Bit - 16-bit operations typically have a larger encoding than
52 // corresponding 32-bit instructions, and 16-bit code is slow on some
53 // processors. This is an experimental flag to disable 16-bit operations
54 // (which forces them to be Legalized to 32-bit operations).
56 Disable16Bit("disable-16bit", cl::Hidden,
57 cl::desc("Disable use of 16-bit instructions"));
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
63 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
64 switch (TM.getSubtarget<X86Subtarget>().TargetType) {
65 default: llvm_unreachable("unknown subtarget type");
66 case X86Subtarget::isDarwin:
67 if (TM.getSubtarget<X86Subtarget>().is64Bit())
68 return new X8664_MachoTargetObjectFile();
69 return new X8632_MachoTargetObjectFile();
70 case X86Subtarget::isELF:
71 return new TargetLoweringObjectFileELF();
72 case X86Subtarget::isMingw:
73 case X86Subtarget::isCygwin:
74 case X86Subtarget::isWindows:
75 return new TargetLoweringObjectFileCOFF();
80 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
81 : TargetLowering(TM, createTLOF(TM)) {
82 Subtarget = &TM.getSubtarget<X86Subtarget>();
83 X86ScalarSSEf64 = Subtarget->hasSSE2();
84 X86ScalarSSEf32 = Subtarget->hasSSE1();
85 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
87 RegInfo = TM.getRegisterInfo();
90 // Set up the TargetLowering object.
92 // X86 is weird, it always uses i8 for shift amounts and setcc results.
93 setShiftAmountType(MVT::i8);
94 setBooleanContents(ZeroOrOneBooleanContent);
95 setSchedulingPreference(SchedulingForRegPressure);
96 setStackPointerRegisterToSaveRestore(X86StackPtr);
98 if (Subtarget->isTargetDarwin()) {
99 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
100 setUseUnderscoreSetJmp(false);
101 setUseUnderscoreLongJmp(false);
102 } else if (Subtarget->isTargetMingw()) {
103 // MS runtime is weird: it exports _setjmp, but longjmp!
104 setUseUnderscoreSetJmp(true);
105 setUseUnderscoreLongJmp(false);
107 setUseUnderscoreSetJmp(true);
108 setUseUnderscoreLongJmp(true);
111 // Set up the register classes.
112 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
114 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
115 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
116 if (Subtarget->is64Bit())
117 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
119 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
121 // We don't accept any truncstore of integer registers.
122 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
124 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
125 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
127 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
128 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
129 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
131 // SETOEQ and SETUNE require checking two conditions.
132 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
133 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
134 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
135 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
136 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
137 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
139 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
141 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
142 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
143 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
145 if (Subtarget->is64Bit()) {
146 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
147 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
148 } else if (!UseSoftFloat) {
149 if (X86ScalarSSEf64) {
150 // We have an impenetrably clever algorithm for ui64->double only.
151 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
153 // We have an algorithm for SSE2, and we turn this into a 64-bit
154 // FILD for other targets.
155 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
158 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
160 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
161 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
164 // SSE has no i16 to fp conversion, only i32
165 if (X86ScalarSSEf32) {
166 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
167 // f32 and f64 cases are Legal, f80 case is not
168 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
170 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
171 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
174 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
175 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
178 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
179 // are Legal, f80 is custom lowered.
180 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
181 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
183 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
185 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
186 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
188 if (X86ScalarSSEf32) {
189 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
190 // f32 and f64 cases are Legal, f80 case is not
191 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
193 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
194 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
197 // Handle FP_TO_UINT by promoting the destination to a larger signed
199 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
200 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
201 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
203 if (Subtarget->is64Bit()) {
204 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
205 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
206 } else if (!UseSoftFloat) {
207 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
208 // Expand FP_TO_UINT into a select.
209 // FIXME: We would like to use a Custom expander here eventually to do
210 // the optimal thing for SSE vs. the default expansion in the legalizer.
211 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
213 // With SSE3 we can use fisttpll to convert to a signed i64; without
214 // SSE, we're stuck with a fistpll.
215 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
218 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
219 if (!X86ScalarSSEf64) {
220 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
221 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
224 // Scalar integer divide and remainder are lowered to use operations that
225 // produce two results, to match the available instructions. This exposes
226 // the two-result form to trivial CSE, which is able to combine x/y and x%y
227 // into a single instruction.
229 // Scalar integer multiply-high is also lowered to use two-result
230 // operations, to match the available instructions. However, plain multiply
231 // (low) operations are left as Legal, as there are single-result
232 // instructions for this in x86. Using the two-result multiply instructions
233 // when both high and low results are needed must be arranged by dagcombine.
234 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
235 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
236 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
237 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
238 setOperationAction(ISD::SREM , MVT::i8 , Expand);
239 setOperationAction(ISD::UREM , MVT::i8 , Expand);
240 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
241 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
242 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
243 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
244 setOperationAction(ISD::SREM , MVT::i16 , Expand);
245 setOperationAction(ISD::UREM , MVT::i16 , Expand);
246 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
247 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
248 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
249 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
250 setOperationAction(ISD::SREM , MVT::i32 , Expand);
251 setOperationAction(ISD::UREM , MVT::i32 , Expand);
252 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
253 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
254 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
255 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
256 setOperationAction(ISD::SREM , MVT::i64 , Expand);
257 setOperationAction(ISD::UREM , MVT::i64 , Expand);
259 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
260 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
261 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
262 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
263 if (Subtarget->is64Bit())
264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
267 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
268 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
269 setOperationAction(ISD::FREM , MVT::f32 , Expand);
270 setOperationAction(ISD::FREM , MVT::f64 , Expand);
271 setOperationAction(ISD::FREM , MVT::f80 , Expand);
272 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
274 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
275 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
276 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
277 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
279 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
280 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
282 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
283 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
285 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
286 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
287 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
288 if (Subtarget->is64Bit()) {
289 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
290 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
291 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
294 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
295 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
297 // These should be promoted to a larger select which is supported.
298 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
299 // X86 wants to expand cmov itself.
300 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
302 setOperationAction(ISD::SELECT , MVT::i16 , Expand);
304 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
305 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
306 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
307 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
308 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
309 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
311 setOperationAction(ISD::SETCC , MVT::i16 , Expand);
313 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
314 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
315 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
316 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
317 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
318 if (Subtarget->is64Bit()) {
319 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
320 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
322 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
325 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
326 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
327 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
328 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
329 if (Subtarget->is64Bit())
330 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
331 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
332 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
335 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
336 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
337 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
338 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
340 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
341 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
342 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
343 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
344 if (Subtarget->is64Bit()) {
345 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
346 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
347 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
350 if (Subtarget->hasSSE1())
351 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
353 if (!Subtarget->hasSSE2())
354 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
356 // Expand certain atomics
357 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
358 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
359 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
360 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
362 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
363 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
364 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
365 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
367 if (!Subtarget->is64Bit()) {
368 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
369 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
370 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
371 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
372 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
373 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
374 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
377 // FIXME - use subtarget debug flags
378 if (!Subtarget->isTargetDarwin() &&
379 !Subtarget->isTargetELF() &&
380 !Subtarget->isTargetCygMing()) {
381 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
384 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
385 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
386 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
387 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
388 if (Subtarget->is64Bit()) {
389 setExceptionPointerRegister(X86::RAX);
390 setExceptionSelectorRegister(X86::RDX);
392 setExceptionPointerRegister(X86::EAX);
393 setExceptionSelectorRegister(X86::EDX);
395 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
396 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
398 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
400 setOperationAction(ISD::TRAP, MVT::Other, Legal);
402 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
403 setOperationAction(ISD::VASTART , MVT::Other, Custom);
404 setOperationAction(ISD::VAEND , MVT::Other, Expand);
405 if (Subtarget->is64Bit()) {
406 setOperationAction(ISD::VAARG , MVT::Other, Custom);
407 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
409 setOperationAction(ISD::VAARG , MVT::Other, Expand);
410 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
413 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
414 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
415 if (Subtarget->is64Bit())
416 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
417 if (Subtarget->isTargetCygMing())
418 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
420 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
422 if (!UseSoftFloat && X86ScalarSSEf64) {
423 // f32 and f64 use SSE.
424 // Set up the FP register classes.
425 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
426 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
428 // Use ANDPD to simulate FABS.
429 setOperationAction(ISD::FABS , MVT::f64, Custom);
430 setOperationAction(ISD::FABS , MVT::f32, Custom);
432 // Use XORP to simulate FNEG.
433 setOperationAction(ISD::FNEG , MVT::f64, Custom);
434 setOperationAction(ISD::FNEG , MVT::f32, Custom);
436 // Use ANDPD and ORPD to simulate FCOPYSIGN.
437 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
438 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
440 // We don't support sin/cos/fmod
441 setOperationAction(ISD::FSIN , MVT::f64, Expand);
442 setOperationAction(ISD::FCOS , MVT::f64, Expand);
443 setOperationAction(ISD::FSIN , MVT::f32, Expand);
444 setOperationAction(ISD::FCOS , MVT::f32, Expand);
446 // Expand FP immediates into loads from the stack, except for the special
448 addLegalFPImmediate(APFloat(+0.0)); // xorpd
449 addLegalFPImmediate(APFloat(+0.0f)); // xorps
450 } else if (!UseSoftFloat && X86ScalarSSEf32) {
451 // Use SSE for f32, x87 for f64.
452 // Set up the FP register classes.
453 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
454 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
456 // Use ANDPS to simulate FABS.
457 setOperationAction(ISD::FABS , MVT::f32, Custom);
459 // Use XORP to simulate FNEG.
460 setOperationAction(ISD::FNEG , MVT::f32, Custom);
462 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
464 // Use ANDPS and ORPS to simulate FCOPYSIGN.
465 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
466 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
468 // We don't support sin/cos/fmod
469 setOperationAction(ISD::FSIN , MVT::f32, Expand);
470 setOperationAction(ISD::FCOS , MVT::f32, Expand);
472 // Special cases we handle for FP constants.
473 addLegalFPImmediate(APFloat(+0.0f)); // xorps
474 addLegalFPImmediate(APFloat(+0.0)); // FLD0
475 addLegalFPImmediate(APFloat(+1.0)); // FLD1
476 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
477 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
480 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
481 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
483 } else if (!UseSoftFloat) {
484 // f32 and f64 in x87.
485 // Set up the FP register classes.
486 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
487 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
489 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
490 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
491 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
492 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
495 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
496 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
498 addLegalFPImmediate(APFloat(+0.0)); // FLD0
499 addLegalFPImmediate(APFloat(+1.0)); // FLD1
500 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
501 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
502 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
503 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
504 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
505 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
508 // Long double always uses X87.
510 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
511 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
512 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
515 APFloat TmpFlt(+0.0);
516 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
518 addLegalFPImmediate(TmpFlt); // FLD0
520 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
521 APFloat TmpFlt2(+1.0);
522 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
524 addLegalFPImmediate(TmpFlt2); // FLD1
525 TmpFlt2.changeSign();
526 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
530 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
531 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
535 // Always use a library call for pow.
536 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
537 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
538 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
540 setOperationAction(ISD::FLOG, MVT::f80, Expand);
541 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
542 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
543 setOperationAction(ISD::FEXP, MVT::f80, Expand);
544 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
546 // First set operation action for all vector types to either promote
547 // (for widening) or expand (for scalarization). Then we will selectively
548 // turn on ones that can be effectively codegen'd.
549 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
550 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
551 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
566 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
567 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
600 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
603 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
604 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
605 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
606 setTruncStoreAction((MVT::SimpleValueType)VT,
607 (MVT::SimpleValueType)InnerVT, Expand);
608 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
609 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
610 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
613 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
614 // with -msoft-float, disable use of MMX as well.
615 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
616 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
617 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
618 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
619 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
620 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
622 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
623 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
624 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
625 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
627 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
628 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
629 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
630 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
632 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
633 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
635 setOperationAction(ISD::AND, MVT::v8i8, Promote);
636 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
637 setOperationAction(ISD::AND, MVT::v4i16, Promote);
638 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
639 setOperationAction(ISD::AND, MVT::v2i32, Promote);
640 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
641 setOperationAction(ISD::AND, MVT::v1i64, Legal);
643 setOperationAction(ISD::OR, MVT::v8i8, Promote);
644 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
645 setOperationAction(ISD::OR, MVT::v4i16, Promote);
646 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
647 setOperationAction(ISD::OR, MVT::v2i32, Promote);
648 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
649 setOperationAction(ISD::OR, MVT::v1i64, Legal);
651 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
652 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
653 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
654 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
655 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
656 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
657 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
659 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
660 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
661 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
662 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
663 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
664 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
665 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
666 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
667 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
669 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
670 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
671 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
672 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
673 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
675 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
676 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
677 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
678 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
680 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
681 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
682 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
683 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
685 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
687 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
688 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
689 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
690 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
691 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
692 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
693 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
696 if (!UseSoftFloat && Subtarget->hasSSE1()) {
697 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
699 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
700 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
701 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
702 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
703 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
704 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
705 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
706 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
707 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
708 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
709 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
710 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
713 if (!UseSoftFloat && Subtarget->hasSSE2()) {
714 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
716 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
717 // registers cannot be used even for integer operations.
718 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
719 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
720 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
721 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
723 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
724 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
725 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
726 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
727 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
728 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
729 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
730 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
731 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
732 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
733 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
734 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
735 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
736 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
737 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
738 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
740 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
741 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
742 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
743 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
745 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
746 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
747 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
748 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
749 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
751 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
752 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
753 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
754 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
755 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
757 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
758 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
759 EVT VT = (MVT::SimpleValueType)i;
760 // Do not attempt to custom lower non-power-of-2 vectors
761 if (!isPowerOf2_32(VT.getVectorNumElements()))
763 // Do not attempt to custom lower non-128-bit vectors
764 if (!VT.is128BitVector())
766 setOperationAction(ISD::BUILD_VECTOR,
767 VT.getSimpleVT().SimpleTy, Custom);
768 setOperationAction(ISD::VECTOR_SHUFFLE,
769 VT.getSimpleVT().SimpleTy, Custom);
770 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
771 VT.getSimpleVT().SimpleTy, Custom);
774 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
775 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
776 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
777 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
778 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
779 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
781 if (Subtarget->is64Bit()) {
782 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
783 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
786 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
787 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
788 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
791 // Do not attempt to promote non-128-bit vectors
792 if (!VT.is128BitVector()) {
795 setOperationAction(ISD::AND, SVT, Promote);
796 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
797 setOperationAction(ISD::OR, SVT, Promote);
798 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
799 setOperationAction(ISD::XOR, SVT, Promote);
800 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
801 setOperationAction(ISD::LOAD, SVT, Promote);
802 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
803 setOperationAction(ISD::SELECT, SVT, Promote);
804 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
807 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
809 // Custom lower v2i64 and v2f64 selects.
810 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
811 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
812 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
813 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
815 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
816 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
817 if (!DisableMMX && Subtarget->hasMMX()) {
818 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
819 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
823 if (Subtarget->hasSSE41()) {
824 // FIXME: Do we need to handle scalar-to-vector here?
825 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
827 // i8 and i16 vectors are custom , because the source register and source
828 // source memory operand types are not the same width. f32 vectors are
829 // custom since the immediate controlling the insert encodes additional
831 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
833 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
834 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
836 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
837 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
838 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
839 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
841 if (Subtarget->is64Bit()) {
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
843 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
847 if (Subtarget->hasSSE42()) {
848 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
851 if (!UseSoftFloat && Subtarget->hasAVX()) {
852 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
853 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
854 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
855 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
857 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
858 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
859 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
860 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
861 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
862 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
863 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
864 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
865 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
866 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
867 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
868 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
869 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
870 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
871 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
873 // Operations to consider commented out -v16i16 v32i8
874 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
875 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
876 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
877 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
878 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
879 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
880 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
881 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
882 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
883 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
884 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
885 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
886 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
887 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
889 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
890 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
891 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
892 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
894 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
895 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
896 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
898 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
900 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
901 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
902 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
903 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
904 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
908 // Not sure we want to do this since there are no 256-bit integer
911 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
912 // This includes 256-bit vectors
913 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
914 EVT VT = (MVT::SimpleValueType)i;
916 // Do not attempt to custom lower non-power-of-2 vectors
917 if (!isPowerOf2_32(VT.getVectorNumElements()))
920 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
921 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
922 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
925 if (Subtarget->is64Bit()) {
926 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
927 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
932 // Not sure we want to do this since there are no 256-bit integer
935 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
936 // Including 256-bit vectors
937 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
938 EVT VT = (MVT::SimpleValueType)i;
940 if (!VT.is256BitVector()) {
943 setOperationAction(ISD::AND, VT, Promote);
944 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
945 setOperationAction(ISD::OR, VT, Promote);
946 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
947 setOperationAction(ISD::XOR, VT, Promote);
948 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
949 setOperationAction(ISD::LOAD, VT, Promote);
950 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
951 setOperationAction(ISD::SELECT, VT, Promote);
952 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
955 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
959 // We want to custom lower some of our intrinsics.
960 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
962 // Add/Sub/Mul with overflow operations are custom lowered.
963 setOperationAction(ISD::SADDO, MVT::i32, Custom);
964 setOperationAction(ISD::SADDO, MVT::i64, Custom);
965 setOperationAction(ISD::UADDO, MVT::i32, Custom);
966 setOperationAction(ISD::UADDO, MVT::i64, Custom);
967 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
968 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
969 setOperationAction(ISD::USUBO, MVT::i32, Custom);
970 setOperationAction(ISD::USUBO, MVT::i64, Custom);
971 setOperationAction(ISD::SMULO, MVT::i32, Custom);
972 setOperationAction(ISD::SMULO, MVT::i64, Custom);
974 if (!Subtarget->is64Bit()) {
975 // These libcalls are not available in 32-bit.
976 setLibcallName(RTLIB::SHL_I128, 0);
977 setLibcallName(RTLIB::SRL_I128, 0);
978 setLibcallName(RTLIB::SRA_I128, 0);
981 // We have target-specific dag combine patterns for the following nodes:
982 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
983 setTargetDAGCombine(ISD::BUILD_VECTOR);
984 setTargetDAGCombine(ISD::SELECT);
985 setTargetDAGCombine(ISD::SHL);
986 setTargetDAGCombine(ISD::SRA);
987 setTargetDAGCombine(ISD::SRL);
988 setTargetDAGCombine(ISD::OR);
989 setTargetDAGCombine(ISD::STORE);
990 setTargetDAGCombine(ISD::MEMBARRIER);
991 setTargetDAGCombine(ISD::ZERO_EXTEND);
992 if (Subtarget->is64Bit())
993 setTargetDAGCombine(ISD::MUL);
995 computeRegisterProperties();
997 // Divide and reminder operations have no vector equivalent and can
998 // trap. Do a custom widening for these operations in which we never
999 // generate more divides/remainder than the original vector width.
1000 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1001 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
1002 if (!isTypeLegal((MVT::SimpleValueType)VT)) {
1003 setOperationAction(ISD::SDIV, (MVT::SimpleValueType) VT, Custom);
1004 setOperationAction(ISD::UDIV, (MVT::SimpleValueType) VT, Custom);
1005 setOperationAction(ISD::SREM, (MVT::SimpleValueType) VT, Custom);
1006 setOperationAction(ISD::UREM, (MVT::SimpleValueType) VT, Custom);
1010 // FIXME: These should be based on subtarget info. Plus, the values should
1011 // be smaller when we are in optimizing for size mode.
1012 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1013 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
1014 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1015 setPrefLoopAlignment(16);
1016 benefitFromCodePlacementOpt = true;
1020 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1025 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1026 /// the desired ByVal argument alignment.
1027 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1030 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1031 if (VTy->getBitWidth() == 128)
1033 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1034 unsigned EltAlign = 0;
1035 getMaxByValAlign(ATy->getElementType(), EltAlign);
1036 if (EltAlign > MaxAlign)
1037 MaxAlign = EltAlign;
1038 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1039 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1040 unsigned EltAlign = 0;
1041 getMaxByValAlign(STy->getElementType(i), EltAlign);
1042 if (EltAlign > MaxAlign)
1043 MaxAlign = EltAlign;
1051 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1052 /// function arguments in the caller parameter area. For X86, aggregates
1053 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1054 /// are at 4-byte boundaries.
1055 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1056 if (Subtarget->is64Bit()) {
1057 // Max of 8 and alignment of type.
1058 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1065 if (Subtarget->hasSSE1())
1066 getMaxByValAlign(Ty, Align);
1070 /// getOptimalMemOpType - Returns the target specific optimal type for load
1071 /// and store operations as a result of memset, memcpy, and memmove
1072 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1075 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1076 bool isSrcConst, bool isSrcStr,
1077 SelectionDAG &DAG) const {
1078 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1079 // linux. This is because the stack realignment code can't handle certain
1080 // cases like PR2962. This should be removed when PR2962 is fixed.
1081 const Function *F = DAG.getMachineFunction().getFunction();
1082 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1083 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1084 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1086 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1089 if (Subtarget->is64Bit() && Size >= 8)
1094 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1095 /// current function. The returned value is a member of the
1096 /// MachineJumpTableInfo::JTEntryKind enum.
1097 unsigned X86TargetLowering::getJumpTableEncoding() const {
1098 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1100 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1101 Subtarget->isPICStyleGOT())
1102 return MachineJumpTableInfo::EK_GPRel32BlockAddress;
1104 // Otherwise, use the normal jump table encoding heuristics.
1105 return TargetLowering::getJumpTableEncoding();
1108 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1110 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1111 SelectionDAG &DAG) const {
1112 if (!Subtarget->is64Bit())
1113 // This doesn't have DebugLoc associated with it, but is not really the
1114 // same as a Register.
1115 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1120 /// getFunctionAlignment - Return the Log2 alignment of this function.
1121 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1122 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1125 //===----------------------------------------------------------------------===//
1126 // Return Value Calling Convention Implementation
1127 //===----------------------------------------------------------------------===//
1129 #include "X86GenCallingConv.inc"
1132 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1133 const SmallVectorImpl<EVT> &OutTys,
1134 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1135 SelectionDAG &DAG) {
1136 SmallVector<CCValAssign, 16> RVLocs;
1137 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1138 RVLocs, *DAG.getContext());
1139 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1143 X86TargetLowering::LowerReturn(SDValue Chain,
1144 CallingConv::ID CallConv, bool isVarArg,
1145 const SmallVectorImpl<ISD::OutputArg> &Outs,
1146 DebugLoc dl, SelectionDAG &DAG) {
1148 SmallVector<CCValAssign, 16> RVLocs;
1149 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1150 RVLocs, *DAG.getContext());
1151 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1153 // If this is the first return lowered for this function, add the regs to the
1154 // liveout set for the function.
1155 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1156 for (unsigned i = 0; i != RVLocs.size(); ++i)
1157 if (RVLocs[i].isRegLoc())
1158 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1163 SmallVector<SDValue, 6> RetOps;
1164 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1165 // Operand #1 = Bytes To Pop
1166 RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1168 // Copy the result values into the output registers.
1169 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1170 CCValAssign &VA = RVLocs[i];
1171 assert(VA.isRegLoc() && "Can only return in registers!");
1172 SDValue ValToCopy = Outs[i].Val;
1174 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1175 // the RET instruction and handled by the FP Stackifier.
1176 if (VA.getLocReg() == X86::ST0 ||
1177 VA.getLocReg() == X86::ST1) {
1178 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1179 // change the value to the FP stack register class.
1180 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1181 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1182 RetOps.push_back(ValToCopy);
1183 // Don't emit a copytoreg.
1187 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1188 // which is returned in RAX / RDX.
1189 if (Subtarget->is64Bit()) {
1190 EVT ValVT = ValToCopy.getValueType();
1191 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1192 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1193 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1194 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1198 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1199 Flag = Chain.getValue(1);
1202 // The x86-64 ABI for returning structs by value requires that we copy
1203 // the sret argument into %rax for the return. We saved the argument into
1204 // a virtual register in the entry block, so now we copy the value out
1206 if (Subtarget->is64Bit() &&
1207 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1208 MachineFunction &MF = DAG.getMachineFunction();
1209 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1210 unsigned Reg = FuncInfo->getSRetReturnReg();
1212 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1213 FuncInfo->setSRetReturnReg(Reg);
1215 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1217 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1218 Flag = Chain.getValue(1);
1220 // RAX now acts like a return value.
1221 MF.getRegInfo().addLiveOut(X86::RAX);
1224 RetOps[0] = Chain; // Update chain.
1226 // Add the flag if we have it.
1228 RetOps.push_back(Flag);
1230 return DAG.getNode(X86ISD::RET_FLAG, dl,
1231 MVT::Other, &RetOps[0], RetOps.size());
1234 /// LowerCallResult - Lower the result values of a call into the
1235 /// appropriate copies out of appropriate physical registers.
1238 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1239 CallingConv::ID CallConv, bool isVarArg,
1240 const SmallVectorImpl<ISD::InputArg> &Ins,
1241 DebugLoc dl, SelectionDAG &DAG,
1242 SmallVectorImpl<SDValue> &InVals) {
1244 // Assign locations to each value returned by this call.
1245 SmallVector<CCValAssign, 16> RVLocs;
1246 bool Is64Bit = Subtarget->is64Bit();
1247 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1248 RVLocs, *DAG.getContext());
1249 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1251 // Copy all of the result registers out of their specified physreg.
1252 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1253 CCValAssign &VA = RVLocs[i];
1254 EVT CopyVT = VA.getValVT();
1256 // If this is x86-64, and we disabled SSE, we can't return FP values
1257 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1258 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1259 llvm_report_error("SSE register return with SSE disabled");
1262 // If this is a call to a function that returns an fp value on the floating
1263 // point stack, but where we prefer to use the value in xmm registers, copy
1264 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1265 if ((VA.getLocReg() == X86::ST0 ||
1266 VA.getLocReg() == X86::ST1) &&
1267 isScalarFPTypeInSSEReg(VA.getValVT())) {
1272 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1273 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1274 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1275 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1276 MVT::v2i64, InFlag).getValue(1);
1277 Val = Chain.getValue(0);
1278 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1279 Val, DAG.getConstant(0, MVT::i64));
1281 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1282 MVT::i64, InFlag).getValue(1);
1283 Val = Chain.getValue(0);
1285 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1287 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1288 CopyVT, InFlag).getValue(1);
1289 Val = Chain.getValue(0);
1291 InFlag = Chain.getValue(2);
1293 if (CopyVT != VA.getValVT()) {
1294 // Round the F80 the right size, which also moves to the appropriate xmm
1296 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1297 // This truncation won't change the value.
1298 DAG.getIntPtrConstant(1));
1301 InVals.push_back(Val);
1308 //===----------------------------------------------------------------------===//
1309 // C & StdCall & Fast Calling Convention implementation
1310 //===----------------------------------------------------------------------===//
1311 // StdCall calling convention seems to be standard for many Windows' API
1312 // routines and around. It differs from C calling convention just a little:
1313 // callee should clean up the stack, not caller. Symbols should be also
1314 // decorated in some fancy way :) It doesn't support any vector arguments.
1315 // For info on fast calling convention see Fast Calling Convention (tail call)
1316 // implementation LowerX86_32FastCCCallTo.
1318 /// CallIsStructReturn - Determines whether a call uses struct return
1320 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1324 return Outs[0].Flags.isSRet();
1327 /// ArgsAreStructReturn - Determines whether a function uses struct
1328 /// return semantics.
1330 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1334 return Ins[0].Flags.isSRet();
1337 /// IsCalleePop - Determines whether the callee is required to pop its
1338 /// own arguments. Callee pop is necessary to support tail calls.
1339 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1343 switch (CallingConv) {
1346 case CallingConv::X86_StdCall:
1347 return !Subtarget->is64Bit();
1348 case CallingConv::X86_FastCall:
1349 return !Subtarget->is64Bit();
1350 case CallingConv::Fast:
1351 return PerformTailCallOpt;
1355 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1356 /// given CallingConvention value.
1357 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1358 if (Subtarget->is64Bit()) {
1359 if (Subtarget->isTargetWin64())
1360 return CC_X86_Win64_C;
1365 if (CC == CallingConv::X86_FastCall)
1366 return CC_X86_32_FastCall;
1367 else if (CC == CallingConv::Fast)
1368 return CC_X86_32_FastCC;
1373 /// NameDecorationForCallConv - Selects the appropriate decoration to
1374 /// apply to a MachineFunction containing a given calling convention.
1376 X86TargetLowering::NameDecorationForCallConv(CallingConv::ID CallConv) {
1377 if (CallConv == CallingConv::X86_FastCall)
1379 else if (CallConv == CallingConv::X86_StdCall)
1385 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1386 /// by "Src" to address "Dst" with size and alignment information specified by
1387 /// the specific parameter attribute. The copy will be passed as a byval
1388 /// function parameter.
1390 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1391 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1393 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1394 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1395 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1399 X86TargetLowering::LowerMemArgument(SDValue Chain,
1400 CallingConv::ID CallConv,
1401 const SmallVectorImpl<ISD::InputArg> &Ins,
1402 DebugLoc dl, SelectionDAG &DAG,
1403 const CCValAssign &VA,
1404 MachineFrameInfo *MFI,
1407 // Create the nodes corresponding to a load from this parameter slot.
1408 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1409 bool AlwaysUseMutable = (CallConv==CallingConv::Fast) && PerformTailCallOpt;
1410 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1413 // If value is passed by pointer we have address passed instead of the value
1415 if (VA.getLocInfo() == CCValAssign::Indirect)
1416 ValVT = VA.getLocVT();
1418 ValVT = VA.getValVT();
1420 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1421 // changed with more analysis.
1422 // In case of tail call optimization mark all arguments mutable. Since they
1423 // could be overwritten by lowering of arguments in case of a tail call.
1424 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1425 VA.getLocMemOffset(), isImmutable, false);
1426 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1427 if (Flags.isByVal())
1429 return DAG.getLoad(ValVT, dl, Chain, FIN,
1430 PseudoSourceValue::getFixedStack(FI), 0);
1434 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1435 CallingConv::ID CallConv,
1437 const SmallVectorImpl<ISD::InputArg> &Ins,
1440 SmallVectorImpl<SDValue> &InVals) {
1442 MachineFunction &MF = DAG.getMachineFunction();
1443 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1445 const Function* Fn = MF.getFunction();
1446 if (Fn->hasExternalLinkage() &&
1447 Subtarget->isTargetCygMing() &&
1448 Fn->getName() == "main")
1449 FuncInfo->setForceFramePointer(true);
1451 // Decorate the function name.
1452 FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1454 MachineFrameInfo *MFI = MF.getFrameInfo();
1455 bool Is64Bit = Subtarget->is64Bit();
1456 bool IsWin64 = Subtarget->isTargetWin64();
1458 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1459 "Var args not supported with calling convention fastcc");
1461 // Assign locations to all of the incoming arguments.
1462 SmallVector<CCValAssign, 16> ArgLocs;
1463 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1464 ArgLocs, *DAG.getContext());
1465 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1467 unsigned LastVal = ~0U;
1469 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1470 CCValAssign &VA = ArgLocs[i];
1471 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1473 assert(VA.getValNo() != LastVal &&
1474 "Don't support value assigned to multiple locs yet");
1475 LastVal = VA.getValNo();
1477 if (VA.isRegLoc()) {
1478 EVT RegVT = VA.getLocVT();
1479 TargetRegisterClass *RC = NULL;
1480 if (RegVT == MVT::i32)
1481 RC = X86::GR32RegisterClass;
1482 else if (Is64Bit && RegVT == MVT::i64)
1483 RC = X86::GR64RegisterClass;
1484 else if (RegVT == MVT::f32)
1485 RC = X86::FR32RegisterClass;
1486 else if (RegVT == MVT::f64)
1487 RC = X86::FR64RegisterClass;
1488 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1489 RC = X86::VR128RegisterClass;
1490 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1491 RC = X86::VR64RegisterClass;
1493 llvm_unreachable("Unknown argument type!");
1495 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1496 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1498 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1499 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1501 if (VA.getLocInfo() == CCValAssign::SExt)
1502 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1503 DAG.getValueType(VA.getValVT()));
1504 else if (VA.getLocInfo() == CCValAssign::ZExt)
1505 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1506 DAG.getValueType(VA.getValVT()));
1507 else if (VA.getLocInfo() == CCValAssign::BCvt)
1508 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1510 if (VA.isExtInLoc()) {
1511 // Handle MMX values passed in XMM regs.
1512 if (RegVT.isVector()) {
1513 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1514 ArgValue, DAG.getConstant(0, MVT::i64));
1515 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1517 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1520 assert(VA.isMemLoc());
1521 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1524 // If value is passed via pointer - do a load.
1525 if (VA.getLocInfo() == CCValAssign::Indirect)
1526 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1528 InVals.push_back(ArgValue);
1531 // The x86-64 ABI for returning structs by value requires that we copy
1532 // the sret argument into %rax for the return. Save the argument into
1533 // a virtual register so that we can access it from the return points.
1534 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1535 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1536 unsigned Reg = FuncInfo->getSRetReturnReg();
1538 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1539 FuncInfo->setSRetReturnReg(Reg);
1541 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1542 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1545 unsigned StackSize = CCInfo.getNextStackOffset();
1546 // align stack specially for tail calls
1547 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1548 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1550 // If the function takes variable number of arguments, make a frame index for
1551 // the start of the first vararg value... for expansion of llvm.va_start.
1553 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1554 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1557 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1559 // FIXME: We should really autogenerate these arrays
1560 static const unsigned GPR64ArgRegsWin64[] = {
1561 X86::RCX, X86::RDX, X86::R8, X86::R9
1563 static const unsigned XMMArgRegsWin64[] = {
1564 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1566 static const unsigned GPR64ArgRegs64Bit[] = {
1567 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1569 static const unsigned XMMArgRegs64Bit[] = {
1570 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1571 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1573 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1576 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1577 GPR64ArgRegs = GPR64ArgRegsWin64;
1578 XMMArgRegs = XMMArgRegsWin64;
1580 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1581 GPR64ArgRegs = GPR64ArgRegs64Bit;
1582 XMMArgRegs = XMMArgRegs64Bit;
1584 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1586 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1589 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1590 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1591 "SSE register cannot be used when SSE is disabled!");
1592 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1593 "SSE register cannot be used when SSE is disabled!");
1594 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1595 // Kernel mode asks for SSE to be disabled, so don't push them
1597 TotalNumXMMRegs = 0;
1599 // For X86-64, if there are vararg parameters that are passed via
1600 // registers, then we must store them to their spots on the stack so they
1601 // may be loaded by deferencing the result of va_next.
1602 VarArgsGPOffset = NumIntRegs * 8;
1603 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1604 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1605 TotalNumXMMRegs * 16, 16,
1608 // Store the integer parameter registers.
1609 SmallVector<SDValue, 8> MemOps;
1610 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1611 unsigned Offset = VarArgsGPOffset;
1612 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1613 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1614 DAG.getIntPtrConstant(Offset));
1615 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1616 X86::GR64RegisterClass);
1617 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1619 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1620 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1622 MemOps.push_back(Store);
1626 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1627 // Now store the XMM (fp + vector) parameter registers.
1628 SmallVector<SDValue, 11> SaveXMMOps;
1629 SaveXMMOps.push_back(Chain);
1631 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1632 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1633 SaveXMMOps.push_back(ALVal);
1635 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1636 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1638 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1639 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1640 X86::VR128RegisterClass);
1641 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1642 SaveXMMOps.push_back(Val);
1644 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1646 &SaveXMMOps[0], SaveXMMOps.size()));
1649 if (!MemOps.empty())
1650 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1651 &MemOps[0], MemOps.size());
1655 // Some CCs need callee pop.
1656 if (IsCalleePop(isVarArg, CallConv)) {
1657 BytesToPopOnReturn = StackSize; // Callee pops everything.
1658 BytesCallerReserves = 0;
1660 BytesToPopOnReturn = 0; // Callee pops nothing.
1661 // If this is an sret function, the return should pop the hidden pointer.
1662 if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1663 BytesToPopOnReturn = 4;
1664 BytesCallerReserves = StackSize;
1668 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1669 if (CallConv == CallingConv::X86_FastCall)
1670 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1673 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1679 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1680 SDValue StackPtr, SDValue Arg,
1681 DebugLoc dl, SelectionDAG &DAG,
1682 const CCValAssign &VA,
1683 ISD::ArgFlagsTy Flags) {
1684 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1685 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1686 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1687 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1688 if (Flags.isByVal()) {
1689 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1691 return DAG.getStore(Chain, dl, Arg, PtrOff,
1692 PseudoSourceValue::getStack(), LocMemOffset);
1695 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1696 /// optimization is performed and it is required.
1698 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1699 SDValue &OutRetAddr,
1705 if (!IsTailCall || FPDiff==0) return Chain;
1707 // Adjust the Return address stack slot.
1708 EVT VT = getPointerTy();
1709 OutRetAddr = getReturnAddressFrameIndex(DAG);
1711 // Load the "old" Return address.
1712 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1713 return SDValue(OutRetAddr.getNode(), 1);
1716 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1717 /// optimization is performed and it is required (FPDiff!=0).
1719 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1720 SDValue Chain, SDValue RetAddrFrIdx,
1721 bool Is64Bit, int FPDiff, DebugLoc dl) {
1722 // Store the return address to the appropriate stack slot.
1723 if (!FPDiff) return Chain;
1724 // Calculate the new stack slot for the return address.
1725 int SlotSize = Is64Bit ? 8 : 4;
1726 int NewReturnAddrFI =
1727 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize,
1729 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1730 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1731 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1732 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1737 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1738 CallingConv::ID CallConv, bool isVarArg,
1740 const SmallVectorImpl<ISD::OutputArg> &Outs,
1741 const SmallVectorImpl<ISD::InputArg> &Ins,
1742 DebugLoc dl, SelectionDAG &DAG,
1743 SmallVectorImpl<SDValue> &InVals) {
1745 MachineFunction &MF = DAG.getMachineFunction();
1746 bool Is64Bit = Subtarget->is64Bit();
1747 bool IsStructRet = CallIsStructReturn(Outs);
1749 assert((!isTailCall ||
1750 (CallConv == CallingConv::Fast && PerformTailCallOpt)) &&
1751 "IsEligibleForTailCallOptimization missed a case!");
1752 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1753 "Var args not supported with calling convention fastcc");
1755 // Analyze operands of the call, assigning locations to each operand.
1756 SmallVector<CCValAssign, 16> ArgLocs;
1757 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1758 ArgLocs, *DAG.getContext());
1759 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1761 // Get a count of how many bytes are to be pushed on the stack.
1762 unsigned NumBytes = CCInfo.getNextStackOffset();
1763 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1764 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1768 // Lower arguments at fp - stackoffset + fpdiff.
1769 unsigned NumBytesCallerPushed =
1770 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1771 FPDiff = NumBytesCallerPushed - NumBytes;
1773 // Set the delta of movement of the returnaddr stackslot.
1774 // But only set if delta is greater than previous delta.
1775 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1776 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1779 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1781 SDValue RetAddrFrIdx;
1782 // Load return adress for tail calls.
1783 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1786 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1787 SmallVector<SDValue, 8> MemOpChains;
1790 // Walk the register/memloc assignments, inserting copies/loads. In the case
1791 // of tail call optimization arguments are handle later.
1792 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1793 CCValAssign &VA = ArgLocs[i];
1794 EVT RegVT = VA.getLocVT();
1795 SDValue Arg = Outs[i].Val;
1796 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1797 bool isByVal = Flags.isByVal();
1799 // Promote the value if needed.
1800 switch (VA.getLocInfo()) {
1801 default: llvm_unreachable("Unknown loc info!");
1802 case CCValAssign::Full: break;
1803 case CCValAssign::SExt:
1804 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1806 case CCValAssign::ZExt:
1807 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1809 case CCValAssign::AExt:
1810 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1811 // Special case: passing MMX values in XMM registers.
1812 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1813 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1814 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1816 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1818 case CCValAssign::BCvt:
1819 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1821 case CCValAssign::Indirect: {
1822 // Store the argument.
1823 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1824 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1825 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1826 PseudoSourceValue::getFixedStack(FI), 0);
1832 if (VA.isRegLoc()) {
1833 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1835 if (!isTailCall || (isTailCall && isByVal)) {
1836 assert(VA.isMemLoc());
1837 if (StackPtr.getNode() == 0)
1838 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1840 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1841 dl, DAG, VA, Flags));
1846 if (!MemOpChains.empty())
1847 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1848 &MemOpChains[0], MemOpChains.size());
1850 // Build a sequence of copy-to-reg nodes chained together with token chain
1851 // and flag operands which copy the outgoing args into registers.
1853 // Tail call byval lowering might overwrite argument registers so in case of
1854 // tail call optimization the copies to registers are lowered later.
1856 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1857 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1858 RegsToPass[i].second, InFlag);
1859 InFlag = Chain.getValue(1);
1863 if (Subtarget->isPICStyleGOT()) {
1864 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1867 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1868 DAG.getNode(X86ISD::GlobalBaseReg,
1869 DebugLoc::getUnknownLoc(),
1872 InFlag = Chain.getValue(1);
1874 // If we are tail calling and generating PIC/GOT style code load the
1875 // address of the callee into ECX. The value in ecx is used as target of
1876 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1877 // for tail calls on PIC/GOT architectures. Normally we would just put the
1878 // address of GOT into ebx and then call target@PLT. But for tail calls
1879 // ebx would be restored (since ebx is callee saved) before jumping to the
1882 // Note: The actual moving to ECX is done further down.
1883 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1884 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1885 !G->getGlobal()->hasProtectedVisibility())
1886 Callee = LowerGlobalAddress(Callee, DAG);
1887 else if (isa<ExternalSymbolSDNode>(Callee))
1888 Callee = LowerExternalSymbol(Callee, DAG);
1892 if (Is64Bit && isVarArg) {
1893 // From AMD64 ABI document:
1894 // For calls that may call functions that use varargs or stdargs
1895 // (prototype-less calls or calls to functions containing ellipsis (...) in
1896 // the declaration) %al is used as hidden argument to specify the number
1897 // of SSE registers used. The contents of %al do not need to match exactly
1898 // the number of registers, but must be an ubound on the number of SSE
1899 // registers used and is in the range 0 - 8 inclusive.
1901 // FIXME: Verify this on Win64
1902 // Count the number of XMM registers allocated.
1903 static const unsigned XMMArgRegs[] = {
1904 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1905 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1907 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1908 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1909 && "SSE registers cannot be used when SSE is disabled");
1911 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1912 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1913 InFlag = Chain.getValue(1);
1917 // For tail calls lower the arguments to the 'real' stack slot.
1919 // Force all the incoming stack arguments to be loaded from the stack
1920 // before any new outgoing arguments are stored to the stack, because the
1921 // outgoing stack slots may alias the incoming argument stack slots, and
1922 // the alias isn't otherwise explicit. This is slightly more conservative
1923 // than necessary, because it means that each store effectively depends
1924 // on every argument instead of just those arguments it would clobber.
1925 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1927 SmallVector<SDValue, 8> MemOpChains2;
1930 // Do not flag preceeding copytoreg stuff together with the following stuff.
1932 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1933 CCValAssign &VA = ArgLocs[i];
1934 if (!VA.isRegLoc()) {
1935 assert(VA.isMemLoc());
1936 SDValue Arg = Outs[i].Val;
1937 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1938 // Create frame index.
1939 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1940 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1941 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
1942 FIN = DAG.getFrameIndex(FI, getPointerTy());
1944 if (Flags.isByVal()) {
1945 // Copy relative to framepointer.
1946 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1947 if (StackPtr.getNode() == 0)
1948 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1950 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1952 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1956 // Store relative to framepointer.
1957 MemOpChains2.push_back(
1958 DAG.getStore(ArgChain, dl, Arg, FIN,
1959 PseudoSourceValue::getFixedStack(FI), 0));
1964 if (!MemOpChains2.empty())
1965 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1966 &MemOpChains2[0], MemOpChains2.size());
1968 // Copy arguments to their registers.
1969 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1970 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1971 RegsToPass[i].second, InFlag);
1972 InFlag = Chain.getValue(1);
1976 // Store the return address to the appropriate stack slot.
1977 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1981 bool WasGlobalOrExternal = false;
1982 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
1983 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
1984 // In the 64-bit large code model, we have to make all calls
1985 // through a register, since the call instruction's 32-bit
1986 // pc-relative offset may not be large enough to hold the whole
1988 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1989 WasGlobalOrExternal = true;
1990 // If the callee is a GlobalAddress node (quite common, every direct call
1991 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
1994 // We should use extra load for direct calls to dllimported functions in
1996 GlobalValue *GV = G->getGlobal();
1997 if (!GV->hasDLLImportLinkage()) {
1998 unsigned char OpFlags = 0;
2000 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2001 // external symbols most go through the PLT in PIC mode. If the symbol
2002 // has hidden or protected visibility, or if it is static or local, then
2003 // we don't need to use the PLT - we can directly call it.
2004 if (Subtarget->isTargetELF() &&
2005 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2006 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2007 OpFlags = X86II::MO_PLT;
2008 } else if (Subtarget->isPICStyleStubAny() &&
2009 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2010 Subtarget->getDarwinVers() < 9) {
2011 // PC-relative references to external symbols should go through $stub,
2012 // unless we're building with the leopard linker or later, which
2013 // automatically synthesizes these stubs.
2014 OpFlags = X86II::MO_DARWIN_STUB;
2017 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2018 G->getOffset(), OpFlags);
2020 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2021 WasGlobalOrExternal = true;
2022 unsigned char OpFlags = 0;
2024 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2025 // symbols should go through the PLT.
2026 if (Subtarget->isTargetELF() &&
2027 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2028 OpFlags = X86II::MO_PLT;
2029 } else if (Subtarget->isPICStyleStubAny() &&
2030 Subtarget->getDarwinVers() < 9) {
2031 // PC-relative references to external symbols should go through $stub,
2032 // unless we're building with the leopard linker or later, which
2033 // automatically synthesizes these stubs.
2034 OpFlags = X86II::MO_DARWIN_STUB;
2037 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2041 if (isTailCall && !WasGlobalOrExternal) {
2042 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
2044 Chain = DAG.getCopyToReg(Chain, dl,
2045 DAG.getRegister(Opc, getPointerTy()),
2047 Callee = DAG.getRegister(Opc, getPointerTy());
2048 // Add register as live out.
2049 MF.getRegInfo().addLiveOut(Opc);
2052 // Returns a chain & a flag for retval copy to use.
2053 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2054 SmallVector<SDValue, 8> Ops;
2057 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2058 DAG.getIntPtrConstant(0, true), InFlag);
2059 InFlag = Chain.getValue(1);
2062 Ops.push_back(Chain);
2063 Ops.push_back(Callee);
2066 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2068 // Add argument registers to the end of the list so that they are known live
2070 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2071 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2072 RegsToPass[i].second.getValueType()));
2074 // Add an implicit use GOT pointer in EBX.
2075 if (!isTailCall && Subtarget->isPICStyleGOT())
2076 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2078 // Add an implicit use of AL for x86 vararg functions.
2079 if (Is64Bit && isVarArg)
2080 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2082 if (InFlag.getNode())
2083 Ops.push_back(InFlag);
2086 // If this is the first return lowered for this function, add the regs
2087 // to the liveout set for the function.
2088 if (MF.getRegInfo().liveout_empty()) {
2089 SmallVector<CCValAssign, 16> RVLocs;
2090 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2092 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2093 for (unsigned i = 0; i != RVLocs.size(); ++i)
2094 if (RVLocs[i].isRegLoc())
2095 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2098 assert(((Callee.getOpcode() == ISD::Register &&
2099 (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2100 cast<RegisterSDNode>(Callee)->getReg() == X86::R11)) ||
2101 Callee.getOpcode() == ISD::TargetExternalSymbol ||
2102 Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2103 "Expecting a global address, external symbol, or scratch register");
2105 return DAG.getNode(X86ISD::TC_RETURN, dl,
2106 NodeTys, &Ops[0], Ops.size());
2109 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2110 InFlag = Chain.getValue(1);
2112 // Create the CALLSEQ_END node.
2113 unsigned NumBytesForCalleeToPush;
2114 if (IsCalleePop(isVarArg, CallConv))
2115 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2116 else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2117 // If this is is a call to a struct-return function, the callee
2118 // pops the hidden struct pointer, so we have to push it back.
2119 // This is common for Darwin/X86, Linux & Mingw32 targets.
2120 NumBytesForCalleeToPush = 4;
2122 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2124 // Returns a flag for retval copy to use.
2125 Chain = DAG.getCALLSEQ_END(Chain,
2126 DAG.getIntPtrConstant(NumBytes, true),
2127 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2130 InFlag = Chain.getValue(1);
2132 // Handle result values, copying them out of physregs into vregs that we
2134 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2135 Ins, dl, DAG, InVals);
2139 //===----------------------------------------------------------------------===//
2140 // Fast Calling Convention (tail call) implementation
2141 //===----------------------------------------------------------------------===//
2143 // Like std call, callee cleans arguments, convention except that ECX is
2144 // reserved for storing the tail called function address. Only 2 registers are
2145 // free for argument passing (inreg). Tail call optimization is performed
2147 // * tailcallopt is enabled
2148 // * caller/callee are fastcc
2149 // On X86_64 architecture with GOT-style position independent code only local
2150 // (within module) calls are supported at the moment.
2151 // To keep the stack aligned according to platform abi the function
2152 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2153 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2154 // If a tail called function callee has more arguments than the caller the
2155 // caller needs to make sure that there is room to move the RETADDR to. This is
2156 // achieved by reserving an area the size of the argument delta right after the
2157 // original REtADDR, but before the saved framepointer or the spilled registers
2158 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2170 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2171 /// for a 16 byte align requirement.
2172 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2173 SelectionDAG& DAG) {
2174 MachineFunction &MF = DAG.getMachineFunction();
2175 const TargetMachine &TM = MF.getTarget();
2176 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2177 unsigned StackAlignment = TFI.getStackAlignment();
2178 uint64_t AlignMask = StackAlignment - 1;
2179 int64_t Offset = StackSize;
2180 uint64_t SlotSize = TD->getPointerSize();
2181 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2182 // Number smaller than 12 so just add the difference.
2183 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2185 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2186 Offset = ((~AlignMask) & Offset) + StackAlignment +
2187 (StackAlignment-SlotSize);
2192 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2193 /// for tail call optimization. Targets which want to do tail call
2194 /// optimization should implement this function.
2196 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2197 CallingConv::ID CalleeCC,
2199 const SmallVectorImpl<ISD::InputArg> &Ins,
2200 SelectionDAG& DAG) const {
2201 MachineFunction &MF = DAG.getMachineFunction();
2202 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2203 return CalleeCC == CallingConv::Fast && CallerCC == CalleeCC;
2207 X86TargetLowering::createFastISel(MachineFunction &mf,
2208 MachineModuleInfo *mmo,
2210 DenseMap<const Value *, unsigned> &vm,
2211 DenseMap<const BasicBlock *,
2212 MachineBasicBlock *> &bm,
2213 DenseMap<const AllocaInst *, int> &am
2215 , SmallSet<Instruction*, 8> &cil
2218 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2226 //===----------------------------------------------------------------------===//
2227 // Other Lowering Hooks
2228 //===----------------------------------------------------------------------===//
2231 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2232 MachineFunction &MF = DAG.getMachineFunction();
2233 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2234 int ReturnAddrIndex = FuncInfo->getRAIndex();
2236 if (ReturnAddrIndex == 0) {
2237 // Set up a frame object for the return address.
2238 uint64_t SlotSize = TD->getPointerSize();
2239 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2241 FuncInfo->setRAIndex(ReturnAddrIndex);
2244 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2248 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2249 bool hasSymbolicDisplacement) {
2250 // Offset should fit into 32 bit immediate field.
2251 if (!isInt32(Offset))
2254 // If we don't have a symbolic displacement - we don't have any extra
2256 if (!hasSymbolicDisplacement)
2259 // FIXME: Some tweaks might be needed for medium code model.
2260 if (M != CodeModel::Small && M != CodeModel::Kernel)
2263 // For small code model we assume that latest object is 16MB before end of 31
2264 // bits boundary. We may also accept pretty large negative constants knowing
2265 // that all objects are in the positive half of address space.
2266 if (M == CodeModel::Small && Offset < 16*1024*1024)
2269 // For kernel code model we know that all object resist in the negative half
2270 // of 32bits address space. We may not accept negative offsets, since they may
2271 // be just off and we may accept pretty large positive ones.
2272 if (M == CodeModel::Kernel && Offset > 0)
2278 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2279 /// specific condition code, returning the condition code and the LHS/RHS of the
2280 /// comparison to make.
2281 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2282 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2284 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2285 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2286 // X > -1 -> X == 0, jump !sign.
2287 RHS = DAG.getConstant(0, RHS.getValueType());
2288 return X86::COND_NS;
2289 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2290 // X < 0 -> X == 0, jump on sign.
2292 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2294 RHS = DAG.getConstant(0, RHS.getValueType());
2295 return X86::COND_LE;
2299 switch (SetCCOpcode) {
2300 default: llvm_unreachable("Invalid integer condition!");
2301 case ISD::SETEQ: return X86::COND_E;
2302 case ISD::SETGT: return X86::COND_G;
2303 case ISD::SETGE: return X86::COND_GE;
2304 case ISD::SETLT: return X86::COND_L;
2305 case ISD::SETLE: return X86::COND_LE;
2306 case ISD::SETNE: return X86::COND_NE;
2307 case ISD::SETULT: return X86::COND_B;
2308 case ISD::SETUGT: return X86::COND_A;
2309 case ISD::SETULE: return X86::COND_BE;
2310 case ISD::SETUGE: return X86::COND_AE;
2314 // First determine if it is required or is profitable to flip the operands.
2316 // If LHS is a foldable load, but RHS is not, flip the condition.
2317 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2318 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2319 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2320 std::swap(LHS, RHS);
2323 switch (SetCCOpcode) {
2329 std::swap(LHS, RHS);
2333 // On a floating point condition, the flags are set as follows:
2335 // 0 | 0 | 0 | X > Y
2336 // 0 | 0 | 1 | X < Y
2337 // 1 | 0 | 0 | X == Y
2338 // 1 | 1 | 1 | unordered
2339 switch (SetCCOpcode) {
2340 default: llvm_unreachable("Condcode should be pre-legalized away");
2342 case ISD::SETEQ: return X86::COND_E;
2343 case ISD::SETOLT: // flipped
2345 case ISD::SETGT: return X86::COND_A;
2346 case ISD::SETOLE: // flipped
2348 case ISD::SETGE: return X86::COND_AE;
2349 case ISD::SETUGT: // flipped
2351 case ISD::SETLT: return X86::COND_B;
2352 case ISD::SETUGE: // flipped
2354 case ISD::SETLE: return X86::COND_BE;
2356 case ISD::SETNE: return X86::COND_NE;
2357 case ISD::SETUO: return X86::COND_P;
2358 case ISD::SETO: return X86::COND_NP;
2360 case ISD::SETUNE: return X86::COND_INVALID;
2364 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2365 /// code. Current x86 isa includes the following FP cmov instructions:
2366 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2367 static bool hasFPCMov(unsigned X86CC) {
2383 /// isFPImmLegal - Returns true if the target can instruction select the
2384 /// specified FP immediate natively. If false, the legalizer will
2385 /// materialize the FP immediate as a load from a constant pool.
2386 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2387 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2388 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2394 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2395 /// the specified range (L, H].
2396 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2397 return (Val < 0) || (Val >= Low && Val < Hi);
2400 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2401 /// specified value.
2402 static bool isUndefOrEqual(int Val, int CmpVal) {
2403 if (Val < 0 || Val == CmpVal)
2408 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2409 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2410 /// the second operand.
2411 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2412 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2413 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2414 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2415 return (Mask[0] < 2 && Mask[1] < 2);
2419 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2420 SmallVector<int, 8> M;
2422 return ::isPSHUFDMask(M, N->getValueType(0));
2425 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2426 /// is suitable for input to PSHUFHW.
2427 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2428 if (VT != MVT::v8i16)
2431 // Lower quadword copied in order or undef.
2432 for (int i = 0; i != 4; ++i)
2433 if (Mask[i] >= 0 && Mask[i] != i)
2436 // Upper quadword shuffled.
2437 for (int i = 4; i != 8; ++i)
2438 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2444 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2445 SmallVector<int, 8> M;
2447 return ::isPSHUFHWMask(M, N->getValueType(0));
2450 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2451 /// is suitable for input to PSHUFLW.
2452 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2453 if (VT != MVT::v8i16)
2456 // Upper quadword copied in order.
2457 for (int i = 4; i != 8; ++i)
2458 if (Mask[i] >= 0 && Mask[i] != i)
2461 // Lower quadword shuffled.
2462 for (int i = 0; i != 4; ++i)
2469 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2470 SmallVector<int, 8> M;
2472 return ::isPSHUFLWMask(M, N->getValueType(0));
2475 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2476 /// is suitable for input to PALIGNR.
2477 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2479 int i, e = VT.getVectorNumElements();
2481 // Do not handle v2i64 / v2f64 shuffles with palignr.
2482 if (e < 4 || !hasSSSE3)
2485 for (i = 0; i != e; ++i)
2489 // All undef, not a palignr.
2493 // Determine if it's ok to perform a palignr with only the LHS, since we
2494 // don't have access to the actual shuffle elements to see if RHS is undef.
2495 bool Unary = Mask[i] < (int)e;
2496 bool NeedsUnary = false;
2498 int s = Mask[i] - i;
2500 // Check the rest of the elements to see if they are consecutive.
2501 for (++i; i != e; ++i) {
2506 Unary = Unary && (m < (int)e);
2507 NeedsUnary = NeedsUnary || (m < s);
2509 if (NeedsUnary && !Unary)
2511 if (Unary && m != ((s+i) & (e-1)))
2513 if (!Unary && m != (s+i))
2519 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2520 SmallVector<int, 8> M;
2522 return ::isPALIGNRMask(M, N->getValueType(0), true);
2525 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2526 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2527 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2528 int NumElems = VT.getVectorNumElements();
2529 if (NumElems != 2 && NumElems != 4)
2532 int Half = NumElems / 2;
2533 for (int i = 0; i < Half; ++i)
2534 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2536 for (int i = Half; i < NumElems; ++i)
2537 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2543 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2544 SmallVector<int, 8> M;
2546 return ::isSHUFPMask(M, N->getValueType(0));
2549 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2550 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2551 /// half elements to come from vector 1 (which would equal the dest.) and
2552 /// the upper half to come from vector 2.
2553 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2554 int NumElems = VT.getVectorNumElements();
2556 if (NumElems != 2 && NumElems != 4)
2559 int Half = NumElems / 2;
2560 for (int i = 0; i < Half; ++i)
2561 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2563 for (int i = Half; i < NumElems; ++i)
2564 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2569 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2570 SmallVector<int, 8> M;
2572 return isCommutedSHUFPMask(M, N->getValueType(0));
2575 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2576 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2577 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2578 if (N->getValueType(0).getVectorNumElements() != 4)
2581 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2582 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2583 isUndefOrEqual(N->getMaskElt(1), 7) &&
2584 isUndefOrEqual(N->getMaskElt(2), 2) &&
2585 isUndefOrEqual(N->getMaskElt(3), 3);
2588 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2589 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2591 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2592 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2597 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2598 isUndefOrEqual(N->getMaskElt(1), 3) &&
2599 isUndefOrEqual(N->getMaskElt(2), 2) &&
2600 isUndefOrEqual(N->getMaskElt(3), 3);
2603 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2604 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2605 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2606 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2608 if (NumElems != 2 && NumElems != 4)
2611 for (unsigned i = 0; i < NumElems/2; ++i)
2612 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2615 for (unsigned i = NumElems/2; i < NumElems; ++i)
2616 if (!isUndefOrEqual(N->getMaskElt(i), i))
2622 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2623 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2624 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2625 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2627 if (NumElems != 2 && NumElems != 4)
2630 for (unsigned i = 0; i < NumElems/2; ++i)
2631 if (!isUndefOrEqual(N->getMaskElt(i), i))
2634 for (unsigned i = 0; i < NumElems/2; ++i)
2635 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2641 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2642 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2643 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2644 bool V2IsSplat = false) {
2645 int NumElts = VT.getVectorNumElements();
2646 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2649 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2651 int BitI1 = Mask[i+1];
2652 if (!isUndefOrEqual(BitI, j))
2655 if (!isUndefOrEqual(BitI1, NumElts))
2658 if (!isUndefOrEqual(BitI1, j + NumElts))
2665 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2666 SmallVector<int, 8> M;
2668 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2671 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2672 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2673 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2674 bool V2IsSplat = false) {
2675 int NumElts = VT.getVectorNumElements();
2676 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2679 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2681 int BitI1 = Mask[i+1];
2682 if (!isUndefOrEqual(BitI, j + NumElts/2))
2685 if (isUndefOrEqual(BitI1, NumElts))
2688 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2695 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2696 SmallVector<int, 8> M;
2698 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2701 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2702 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2704 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2705 int NumElems = VT.getVectorNumElements();
2706 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2709 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2711 int BitI1 = Mask[i+1];
2712 if (!isUndefOrEqual(BitI, j))
2714 if (!isUndefOrEqual(BitI1, j))
2720 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2721 SmallVector<int, 8> M;
2723 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2726 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2727 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2729 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2730 int NumElems = VT.getVectorNumElements();
2731 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2734 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2736 int BitI1 = Mask[i+1];
2737 if (!isUndefOrEqual(BitI, j))
2739 if (!isUndefOrEqual(BitI1, j))
2745 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2746 SmallVector<int, 8> M;
2748 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2751 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2752 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2753 /// MOVSD, and MOVD, i.e. setting the lowest element.
2754 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2755 if (VT.getVectorElementType().getSizeInBits() < 32)
2758 int NumElts = VT.getVectorNumElements();
2760 if (!isUndefOrEqual(Mask[0], NumElts))
2763 for (int i = 1; i < NumElts; ++i)
2764 if (!isUndefOrEqual(Mask[i], i))
2770 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2771 SmallVector<int, 8> M;
2773 return ::isMOVLMask(M, N->getValueType(0));
2776 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2777 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2778 /// element of vector 2 and the other elements to come from vector 1 in order.
2779 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2780 bool V2IsSplat = false, bool V2IsUndef = false) {
2781 int NumOps = VT.getVectorNumElements();
2782 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2785 if (!isUndefOrEqual(Mask[0], 0))
2788 for (int i = 1; i < NumOps; ++i)
2789 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2790 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2791 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2797 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2798 bool V2IsUndef = false) {
2799 SmallVector<int, 8> M;
2801 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2804 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2805 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2806 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2807 if (N->getValueType(0).getVectorNumElements() != 4)
2810 // Expect 1, 1, 3, 3
2811 for (unsigned i = 0; i < 2; ++i) {
2812 int Elt = N->getMaskElt(i);
2813 if (Elt >= 0 && Elt != 1)
2818 for (unsigned i = 2; i < 4; ++i) {
2819 int Elt = N->getMaskElt(i);
2820 if (Elt >= 0 && Elt != 3)
2825 // Don't use movshdup if it can be done with a shufps.
2826 // FIXME: verify that matching u, u, 3, 3 is what we want.
2830 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2831 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2832 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2833 if (N->getValueType(0).getVectorNumElements() != 4)
2836 // Expect 0, 0, 2, 2
2837 for (unsigned i = 0; i < 2; ++i)
2838 if (N->getMaskElt(i) > 0)
2842 for (unsigned i = 2; i < 4; ++i) {
2843 int Elt = N->getMaskElt(i);
2844 if (Elt >= 0 && Elt != 2)
2849 // Don't use movsldup if it can be done with a shufps.
2853 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2854 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2855 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2856 int e = N->getValueType(0).getVectorNumElements() / 2;
2858 for (int i = 0; i < e; ++i)
2859 if (!isUndefOrEqual(N->getMaskElt(i), i))
2861 for (int i = 0; i < e; ++i)
2862 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2867 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2868 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
2869 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2870 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2871 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2873 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2875 for (int i = 0; i < NumOperands; ++i) {
2876 int Val = SVOp->getMaskElt(NumOperands-i-1);
2877 if (Val < 0) Val = 0;
2878 if (Val >= NumOperands) Val -= NumOperands;
2880 if (i != NumOperands - 1)
2886 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2887 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
2888 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2889 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2891 // 8 nodes, but we only care about the last 4.
2892 for (unsigned i = 7; i >= 4; --i) {
2893 int Val = SVOp->getMaskElt(i);
2902 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2903 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
2904 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2905 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2907 // 8 nodes, but we only care about the first 4.
2908 for (int i = 3; i >= 0; --i) {
2909 int Val = SVOp->getMaskElt(i);
2918 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
2919 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
2920 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
2921 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2922 EVT VVT = N->getValueType(0);
2923 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
2927 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
2928 Val = SVOp->getMaskElt(i);
2932 return (Val - i) * EltSize;
2935 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2937 bool X86::isZeroNode(SDValue Elt) {
2938 return ((isa<ConstantSDNode>(Elt) &&
2939 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2940 (isa<ConstantFPSDNode>(Elt) &&
2941 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2944 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2945 /// their permute mask.
2946 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2947 SelectionDAG &DAG) {
2948 EVT VT = SVOp->getValueType(0);
2949 unsigned NumElems = VT.getVectorNumElements();
2950 SmallVector<int, 8> MaskVec;
2952 for (unsigned i = 0; i != NumElems; ++i) {
2953 int idx = SVOp->getMaskElt(i);
2955 MaskVec.push_back(idx);
2956 else if (idx < (int)NumElems)
2957 MaskVec.push_back(idx + NumElems);
2959 MaskVec.push_back(idx - NumElems);
2961 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2962 SVOp->getOperand(0), &MaskVec[0]);
2965 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2966 /// the two vector operands have swapped position.
2967 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
2968 unsigned NumElems = VT.getVectorNumElements();
2969 for (unsigned i = 0; i != NumElems; ++i) {
2973 else if (idx < (int)NumElems)
2974 Mask[i] = idx + NumElems;
2976 Mask[i] = idx - NumElems;
2980 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2981 /// match movhlps. The lower half elements should come from upper half of
2982 /// V1 (and in order), and the upper half elements should come from the upper
2983 /// half of V2 (and in order).
2984 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2985 if (Op->getValueType(0).getVectorNumElements() != 4)
2987 for (unsigned i = 0, e = 2; i != e; ++i)
2988 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2990 for (unsigned i = 2; i != 4; ++i)
2991 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2996 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2997 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2999 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3000 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3002 N = N->getOperand(0).getNode();
3003 if (!ISD::isNON_EXTLoad(N))
3006 *LD = cast<LoadSDNode>(N);
3010 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3011 /// match movlp{s|d}. The lower half elements should come from lower half of
3012 /// V1 (and in order), and the upper half elements should come from the upper
3013 /// half of V2 (and in order). And since V1 will become the source of the
3014 /// MOVLP, it must be either a vector load or a scalar load to vector.
3015 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3016 ShuffleVectorSDNode *Op) {
3017 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3019 // Is V2 is a vector load, don't do this transformation. We will try to use
3020 // load folding shufps op.
3021 if (ISD::isNON_EXTLoad(V2))
3024 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3026 if (NumElems != 2 && NumElems != 4)
3028 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3029 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3031 for (unsigned i = NumElems/2; i != NumElems; ++i)
3032 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3037 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3039 static bool isSplatVector(SDNode *N) {
3040 if (N->getOpcode() != ISD::BUILD_VECTOR)
3043 SDValue SplatValue = N->getOperand(0);
3044 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3045 if (N->getOperand(i) != SplatValue)
3050 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3051 /// to an zero vector.
3052 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3053 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3054 SDValue V1 = N->getOperand(0);
3055 SDValue V2 = N->getOperand(1);
3056 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3057 for (unsigned i = 0; i != NumElems; ++i) {
3058 int Idx = N->getMaskElt(i);
3059 if (Idx >= (int)NumElems) {
3060 unsigned Opc = V2.getOpcode();
3061 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3063 if (Opc != ISD::BUILD_VECTOR ||
3064 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3066 } else if (Idx >= 0) {
3067 unsigned Opc = V1.getOpcode();
3068 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3070 if (Opc != ISD::BUILD_VECTOR ||
3071 !X86::isZeroNode(V1.getOperand(Idx)))
3078 /// getZeroVector - Returns a vector of specified type with all zero elements.
3080 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3082 assert(VT.isVector() && "Expected a vector type");
3084 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3085 // type. This ensures they get CSE'd.
3087 if (VT.getSizeInBits() == 64) { // MMX
3088 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3089 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3090 } else if (HasSSE2) { // SSE2
3091 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3092 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3094 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3095 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3097 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3100 /// getOnesVector - Returns a vector of specified type with all bits set.
3102 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3103 assert(VT.isVector() && "Expected a vector type");
3105 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3106 // type. This ensures they get CSE'd.
3107 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3109 if (VT.getSizeInBits() == 64) // MMX
3110 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3112 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3113 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3117 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3118 /// that point to V2 points to its first element.
3119 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3120 EVT VT = SVOp->getValueType(0);
3121 unsigned NumElems = VT.getVectorNumElements();
3123 bool Changed = false;
3124 SmallVector<int, 8> MaskVec;
3125 SVOp->getMask(MaskVec);
3127 for (unsigned i = 0; i != NumElems; ++i) {
3128 if (MaskVec[i] > (int)NumElems) {
3129 MaskVec[i] = NumElems;
3134 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3135 SVOp->getOperand(1), &MaskVec[0]);
3136 return SDValue(SVOp, 0);
3139 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3140 /// operation of specified width.
3141 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3143 unsigned NumElems = VT.getVectorNumElements();
3144 SmallVector<int, 8> Mask;
3145 Mask.push_back(NumElems);
3146 for (unsigned i = 1; i != NumElems; ++i)
3148 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3151 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3152 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3154 unsigned NumElems = VT.getVectorNumElements();
3155 SmallVector<int, 8> Mask;
3156 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3158 Mask.push_back(i + NumElems);
3160 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3163 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3164 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3166 unsigned NumElems = VT.getVectorNumElements();
3167 unsigned Half = NumElems/2;
3168 SmallVector<int, 8> Mask;
3169 for (unsigned i = 0; i != Half; ++i) {
3170 Mask.push_back(i + Half);
3171 Mask.push_back(i + NumElems + Half);
3173 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3176 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3177 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3179 if (SV->getValueType(0).getVectorNumElements() <= 4)
3180 return SDValue(SV, 0);
3182 EVT PVT = MVT::v4f32;
3183 EVT VT = SV->getValueType(0);
3184 DebugLoc dl = SV->getDebugLoc();
3185 SDValue V1 = SV->getOperand(0);
3186 int NumElems = VT.getVectorNumElements();
3187 int EltNo = SV->getSplatIndex();
3189 // unpack elements to the correct location
3190 while (NumElems > 4) {
3191 if (EltNo < NumElems/2) {
3192 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3194 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3195 EltNo -= NumElems/2;
3200 // Perform the splat.
3201 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3202 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3203 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3204 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3207 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3208 /// vector of zero or undef vector. This produces a shuffle where the low
3209 /// element of V2 is swizzled into the zero/undef vector, landing at element
3210 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3211 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3212 bool isZero, bool HasSSE2,
3213 SelectionDAG &DAG) {
3214 EVT VT = V2.getValueType();
3216 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3217 unsigned NumElems = VT.getVectorNumElements();
3218 SmallVector<int, 16> MaskVec;
3219 for (unsigned i = 0; i != NumElems; ++i)
3220 // If this is the insertion idx, put the low elt of V2 here.
3221 MaskVec.push_back(i == Idx ? NumElems : i);
3222 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3225 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3226 /// a shuffle that is zero.
3228 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3229 bool Low, SelectionDAG &DAG) {
3230 unsigned NumZeros = 0;
3231 for (int i = 0; i < NumElems; ++i) {
3232 unsigned Index = Low ? i : NumElems-i-1;
3233 int Idx = SVOp->getMaskElt(Index);
3238 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3239 if (Elt.getNode() && X86::isZeroNode(Elt))
3247 /// isVectorShift - Returns true if the shuffle can be implemented as a
3248 /// logical left or right shift of a vector.
3249 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3250 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3251 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3252 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3255 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3258 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3262 bool SeenV1 = false;
3263 bool SeenV2 = false;
3264 for (int i = NumZeros; i < NumElems; ++i) {
3265 int Val = isLeft ? (i - NumZeros) : i;
3266 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3278 if (SeenV1 && SeenV2)
3281 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3287 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3289 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3290 unsigned NumNonZero, unsigned NumZero,
3291 SelectionDAG &DAG, TargetLowering &TLI) {
3295 DebugLoc dl = Op.getDebugLoc();
3298 for (unsigned i = 0; i < 16; ++i) {
3299 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3300 if (ThisIsNonZero && First) {
3302 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3304 V = DAG.getUNDEF(MVT::v8i16);
3309 SDValue ThisElt(0, 0), LastElt(0, 0);
3310 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3311 if (LastIsNonZero) {
3312 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3313 MVT::i16, Op.getOperand(i-1));
3315 if (ThisIsNonZero) {
3316 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3317 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3318 ThisElt, DAG.getConstant(8, MVT::i8));
3320 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3324 if (ThisElt.getNode())
3325 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3326 DAG.getIntPtrConstant(i/2));
3330 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3333 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3335 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3336 unsigned NumNonZero, unsigned NumZero,
3337 SelectionDAG &DAG, TargetLowering &TLI) {
3341 DebugLoc dl = Op.getDebugLoc();
3344 for (unsigned i = 0; i < 8; ++i) {
3345 bool isNonZero = (NonZeros & (1 << i)) != 0;
3349 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3351 V = DAG.getUNDEF(MVT::v8i16);
3354 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3355 MVT::v8i16, V, Op.getOperand(i),
3356 DAG.getIntPtrConstant(i));
3363 /// getVShift - Return a vector logical shift node.
3365 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3366 unsigned NumBits, SelectionDAG &DAG,
3367 const TargetLowering &TLI, DebugLoc dl) {
3368 bool isMMX = VT.getSizeInBits() == 64;
3369 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3370 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3371 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3372 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3373 DAG.getNode(Opc, dl, ShVT, SrcOp,
3374 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3378 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3379 SelectionDAG &DAG) {
3381 // Check if the scalar load can be widened into a vector load. And if
3382 // the address is "base + cst" see if the cst can be "absorbed" into
3383 // the shuffle mask.
3384 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3385 SDValue Ptr = LD->getBasePtr();
3386 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3388 EVT PVT = LD->getValueType(0);
3389 if (PVT != MVT::i32 && PVT != MVT::f32)
3394 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3395 FI = FINode->getIndex();
3397 } else if (Ptr.getOpcode() == ISD::ADD &&
3398 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3399 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3400 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3401 Offset = Ptr.getConstantOperandVal(1);
3402 Ptr = Ptr.getOperand(0);
3407 SDValue Chain = LD->getChain();
3408 // Make sure the stack object alignment is at least 16.
3409 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3410 if (DAG.InferPtrAlignment(Ptr) < 16) {
3411 if (MFI->isFixedObjectIndex(FI)) {
3412 // Can't change the alignment. FIXME: It's possible to compute
3413 // the exact stack offset and reference FI + adjust offset instead.
3414 // If someone *really* cares about this. That's the way to implement it.
3417 MFI->setObjectAlignment(FI, 16);
3421 // (Offset % 16) must be multiple of 4. Then address is then
3422 // Ptr + (Offset & ~15).
3425 if ((Offset % 16) & 3)
3427 int64_t StartOffset = Offset & ~15;
3429 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3430 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3432 int EltNo = (Offset - StartOffset) >> 2;
3433 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3434 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3435 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0);
3436 // Canonicalize it to a v4i32 shuffle.
3437 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3438 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3439 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3440 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3447 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3448 DebugLoc dl = Op.getDebugLoc();
3449 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3450 if (ISD::isBuildVectorAllZeros(Op.getNode())
3451 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3452 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3453 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3454 // eliminated on x86-32 hosts.
3455 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3458 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3459 return getOnesVector(Op.getValueType(), DAG, dl);
3460 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3463 EVT VT = Op.getValueType();
3464 EVT ExtVT = VT.getVectorElementType();
3465 unsigned EVTBits = ExtVT.getSizeInBits();
3467 unsigned NumElems = Op.getNumOperands();
3468 unsigned NumZero = 0;
3469 unsigned NumNonZero = 0;
3470 unsigned NonZeros = 0;
3471 bool IsAllConstants = true;
3472 SmallSet<SDValue, 8> Values;
3473 for (unsigned i = 0; i < NumElems; ++i) {
3474 SDValue Elt = Op.getOperand(i);
3475 if (Elt.getOpcode() == ISD::UNDEF)
3478 if (Elt.getOpcode() != ISD::Constant &&
3479 Elt.getOpcode() != ISD::ConstantFP)
3480 IsAllConstants = false;
3481 if (X86::isZeroNode(Elt))
3484 NonZeros |= (1 << i);
3489 if (NumNonZero == 0) {
3490 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3491 return DAG.getUNDEF(VT);
3494 // Special case for single non-zero, non-undef, element.
3495 if (NumNonZero == 1) {
3496 unsigned Idx = CountTrailingZeros_32(NonZeros);
3497 SDValue Item = Op.getOperand(Idx);
3499 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3500 // the value are obviously zero, truncate the value to i32 and do the
3501 // insertion that way. Only do this if the value is non-constant or if the
3502 // value is a constant being inserted into element 0. It is cheaper to do
3503 // a constant pool load than it is to do a movd + shuffle.
3504 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3505 (!IsAllConstants || Idx == 0)) {
3506 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3507 // Handle MMX and SSE both.
3508 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3509 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3511 // Truncate the value (which may itself be a constant) to i32, and
3512 // convert it to a vector with movd (S2V+shuffle to zero extend).
3513 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3514 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3515 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3516 Subtarget->hasSSE2(), DAG);
3518 // Now we have our 32-bit value zero extended in the low element of
3519 // a vector. If Idx != 0, swizzle it into place.
3521 SmallVector<int, 4> Mask;
3522 Mask.push_back(Idx);
3523 for (unsigned i = 1; i != VecElts; ++i)
3525 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3526 DAG.getUNDEF(Item.getValueType()),
3529 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3533 // If we have a constant or non-constant insertion into the low element of
3534 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3535 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3536 // depending on what the source datatype is.
3539 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3540 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3541 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3542 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3543 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3544 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3546 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3547 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3548 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3549 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3550 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3551 Subtarget->hasSSE2(), DAG);
3552 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3556 // Is it a vector logical left shift?
3557 if (NumElems == 2 && Idx == 1 &&
3558 X86::isZeroNode(Op.getOperand(0)) &&
3559 !X86::isZeroNode(Op.getOperand(1))) {
3560 unsigned NumBits = VT.getSizeInBits();
3561 return getVShift(true, VT,
3562 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3563 VT, Op.getOperand(1)),
3564 NumBits/2, DAG, *this, dl);
3567 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3570 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3571 // is a non-constant being inserted into an element other than the low one,
3572 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3573 // movd/movss) to move this into the low element, then shuffle it into
3575 if (EVTBits == 32) {
3576 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3578 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3579 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3580 Subtarget->hasSSE2(), DAG);
3581 SmallVector<int, 8> MaskVec;
3582 for (unsigned i = 0; i < NumElems; i++)
3583 MaskVec.push_back(i == Idx ? 0 : 1);
3584 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3588 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3589 if (Values.size() == 1) {
3590 if (EVTBits == 32) {
3591 // Instead of a shuffle like this:
3592 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3593 // Check if it's possible to issue this instead.
3594 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3595 unsigned Idx = CountTrailingZeros_32(NonZeros);
3596 SDValue Item = Op.getOperand(Idx);
3597 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3598 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3603 // A vector full of immediates; various special cases are already
3604 // handled, so this is best done with a single constant-pool load.
3608 // Let legalizer expand 2-wide build_vectors.
3609 if (EVTBits == 64) {
3610 if (NumNonZero == 1) {
3611 // One half is zero or undef.
3612 unsigned Idx = CountTrailingZeros_32(NonZeros);
3613 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3614 Op.getOperand(Idx));
3615 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3616 Subtarget->hasSSE2(), DAG);
3621 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3622 if (EVTBits == 8 && NumElems == 16) {
3623 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3625 if (V.getNode()) return V;
3628 if (EVTBits == 16 && NumElems == 8) {
3629 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3631 if (V.getNode()) return V;
3634 // If element VT is == 32 bits, turn it into a number of shuffles.
3635 SmallVector<SDValue, 8> V;
3637 if (NumElems == 4 && NumZero > 0) {
3638 for (unsigned i = 0; i < 4; ++i) {
3639 bool isZero = !(NonZeros & (1 << i));
3641 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3643 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3646 for (unsigned i = 0; i < 2; ++i) {
3647 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3650 V[i] = V[i*2]; // Must be a zero vector.
3653 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3656 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3659 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3664 SmallVector<int, 8> MaskVec;
3665 bool Reverse = (NonZeros & 0x3) == 2;
3666 for (unsigned i = 0; i < 2; ++i)
3667 MaskVec.push_back(Reverse ? 1-i : i);
3668 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3669 for (unsigned i = 0; i < 2; ++i)
3670 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3671 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3674 if (Values.size() > 2) {
3675 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3676 // values to be inserted is equal to the number of elements, in which case
3677 // use the unpack code below in the hopes of matching the consecutive elts
3678 // load merge pattern for shuffles.
3679 // FIXME: We could probably just check that here directly.
3680 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3681 getSubtarget()->hasSSE41()) {
3682 V[0] = DAG.getUNDEF(VT);
3683 for (unsigned i = 0; i < NumElems; ++i)
3684 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3685 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3686 Op.getOperand(i), DAG.getIntPtrConstant(i));
3689 // Expand into a number of unpckl*.
3691 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3692 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3693 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3694 for (unsigned i = 0; i < NumElems; ++i)
3695 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3697 while (NumElems != 0) {
3698 for (unsigned i = 0; i < NumElems; ++i)
3699 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3709 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3710 // We support concatenate two MMX registers and place them in a MMX
3711 // register. This is better than doing a stack convert.
3712 DebugLoc dl = Op.getDebugLoc();
3713 EVT ResVT = Op.getValueType();
3714 assert(Op.getNumOperands() == 2);
3715 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3716 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3718 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3719 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3720 InVec = Op.getOperand(1);
3721 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3722 unsigned NumElts = ResVT.getVectorNumElements();
3723 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3724 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3725 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3727 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3728 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3729 Mask[0] = 0; Mask[1] = 2;
3730 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3732 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3735 // v8i16 shuffles - Prefer shuffles in the following order:
3736 // 1. [all] pshuflw, pshufhw, optional move
3737 // 2. [ssse3] 1 x pshufb
3738 // 3. [ssse3] 2 x pshufb + 1 x por
3739 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3741 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3742 SelectionDAG &DAG, X86TargetLowering &TLI) {
3743 SDValue V1 = SVOp->getOperand(0);
3744 SDValue V2 = SVOp->getOperand(1);
3745 DebugLoc dl = SVOp->getDebugLoc();
3746 SmallVector<int, 8> MaskVals;
3748 // Determine if more than 1 of the words in each of the low and high quadwords
3749 // of the result come from the same quadword of one of the two inputs. Undef
3750 // mask values count as coming from any quadword, for better codegen.
3751 SmallVector<unsigned, 4> LoQuad(4);
3752 SmallVector<unsigned, 4> HiQuad(4);
3753 BitVector InputQuads(4);
3754 for (unsigned i = 0; i < 8; ++i) {
3755 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3756 int EltIdx = SVOp->getMaskElt(i);
3757 MaskVals.push_back(EltIdx);
3766 InputQuads.set(EltIdx / 4);
3769 int BestLoQuad = -1;
3770 unsigned MaxQuad = 1;
3771 for (unsigned i = 0; i < 4; ++i) {
3772 if (LoQuad[i] > MaxQuad) {
3774 MaxQuad = LoQuad[i];
3778 int BestHiQuad = -1;
3780 for (unsigned i = 0; i < 4; ++i) {
3781 if (HiQuad[i] > MaxQuad) {
3783 MaxQuad = HiQuad[i];
3787 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3788 // of the two input vectors, shuffle them into one input vector so only a
3789 // single pshufb instruction is necessary. If There are more than 2 input
3790 // quads, disable the next transformation since it does not help SSSE3.
3791 bool V1Used = InputQuads[0] || InputQuads[1];
3792 bool V2Used = InputQuads[2] || InputQuads[3];
3793 if (TLI.getSubtarget()->hasSSSE3()) {
3794 if (InputQuads.count() == 2 && V1Used && V2Used) {
3795 BestLoQuad = InputQuads.find_first();
3796 BestHiQuad = InputQuads.find_next(BestLoQuad);
3798 if (InputQuads.count() > 2) {
3804 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3805 // the shuffle mask. If a quad is scored as -1, that means that it contains
3806 // words from all 4 input quadwords.
3808 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3809 SmallVector<int, 8> MaskV;
3810 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3811 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3812 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3813 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3814 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3815 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3817 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3818 // source words for the shuffle, to aid later transformations.
3819 bool AllWordsInNewV = true;
3820 bool InOrder[2] = { true, true };
3821 for (unsigned i = 0; i != 8; ++i) {
3822 int idx = MaskVals[i];
3824 InOrder[i/4] = false;
3825 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3827 AllWordsInNewV = false;
3831 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3832 if (AllWordsInNewV) {
3833 for (int i = 0; i != 8; ++i) {
3834 int idx = MaskVals[i];
3837 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3838 if ((idx != i) && idx < 4)
3840 if ((idx != i) && idx > 3)
3849 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3850 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3851 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3852 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3853 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3857 // If we have SSSE3, and all words of the result are from 1 input vector,
3858 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3859 // is present, fall back to case 4.
3860 if (TLI.getSubtarget()->hasSSSE3()) {
3861 SmallVector<SDValue,16> pshufbMask;
3863 // If we have elements from both input vectors, set the high bit of the
3864 // shuffle mask element to zero out elements that come from V2 in the V1
3865 // mask, and elements that come from V1 in the V2 mask, so that the two
3866 // results can be OR'd together.
3867 bool TwoInputs = V1Used && V2Used;
3868 for (unsigned i = 0; i != 8; ++i) {
3869 int EltIdx = MaskVals[i] * 2;
3870 if (TwoInputs && (EltIdx >= 16)) {
3871 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3872 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3875 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3876 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3878 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3879 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3880 DAG.getNode(ISD::BUILD_VECTOR, dl,
3881 MVT::v16i8, &pshufbMask[0], 16));
3883 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3885 // Calculate the shuffle mask for the second input, shuffle it, and
3886 // OR it with the first shuffled input.
3888 for (unsigned i = 0; i != 8; ++i) {
3889 int EltIdx = MaskVals[i] * 2;
3891 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3892 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3895 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3896 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3898 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3899 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3900 DAG.getNode(ISD::BUILD_VECTOR, dl,
3901 MVT::v16i8, &pshufbMask[0], 16));
3902 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3903 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3906 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3907 // and update MaskVals with new element order.
3908 BitVector InOrder(8);
3909 if (BestLoQuad >= 0) {
3910 SmallVector<int, 8> MaskV;
3911 for (int i = 0; i != 4; ++i) {
3912 int idx = MaskVals[i];
3914 MaskV.push_back(-1);
3916 } else if ((idx / 4) == BestLoQuad) {
3917 MaskV.push_back(idx & 3);
3920 MaskV.push_back(-1);
3923 for (unsigned i = 4; i != 8; ++i)
3925 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3929 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3930 // and update MaskVals with the new element order.
3931 if (BestHiQuad >= 0) {
3932 SmallVector<int, 8> MaskV;
3933 for (unsigned i = 0; i != 4; ++i)
3935 for (unsigned i = 4; i != 8; ++i) {
3936 int idx = MaskVals[i];
3938 MaskV.push_back(-1);
3940 } else if ((idx / 4) == BestHiQuad) {
3941 MaskV.push_back((idx & 3) + 4);
3944 MaskV.push_back(-1);
3947 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3951 // In case BestHi & BestLo were both -1, which means each quadword has a word
3952 // from each of the four input quadwords, calculate the InOrder bitvector now
3953 // before falling through to the insert/extract cleanup.
3954 if (BestLoQuad == -1 && BestHiQuad == -1) {
3956 for (int i = 0; i != 8; ++i)
3957 if (MaskVals[i] < 0 || MaskVals[i] == i)
3961 // The other elements are put in the right place using pextrw and pinsrw.
3962 for (unsigned i = 0; i != 8; ++i) {
3965 int EltIdx = MaskVals[i];
3968 SDValue ExtOp = (EltIdx < 8)
3969 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3970 DAG.getIntPtrConstant(EltIdx))
3971 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3972 DAG.getIntPtrConstant(EltIdx - 8));
3973 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3974 DAG.getIntPtrConstant(i));
3979 // v16i8 shuffles - Prefer shuffles in the following order:
3980 // 1. [ssse3] 1 x pshufb
3981 // 2. [ssse3] 2 x pshufb + 1 x por
3982 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3984 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3985 SelectionDAG &DAG, X86TargetLowering &TLI) {
3986 SDValue V1 = SVOp->getOperand(0);
3987 SDValue V2 = SVOp->getOperand(1);
3988 DebugLoc dl = SVOp->getDebugLoc();
3989 SmallVector<int, 16> MaskVals;
3990 SVOp->getMask(MaskVals);
3992 // If we have SSSE3, case 1 is generated when all result bytes come from
3993 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3994 // present, fall back to case 3.
3995 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3998 for (unsigned i = 0; i < 16; ++i) {
3999 int EltIdx = MaskVals[i];
4008 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4009 if (TLI.getSubtarget()->hasSSSE3()) {
4010 SmallVector<SDValue,16> pshufbMask;
4012 // If all result elements are from one input vector, then only translate
4013 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4015 // Otherwise, we have elements from both input vectors, and must zero out
4016 // elements that come from V2 in the first mask, and V1 in the second mask
4017 // so that we can OR them together.
4018 bool TwoInputs = !(V1Only || V2Only);
4019 for (unsigned i = 0; i != 16; ++i) {
4020 int EltIdx = MaskVals[i];
4021 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4022 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4025 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4027 // If all the elements are from V2, assign it to V1 and return after
4028 // building the first pshufb.
4031 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4032 DAG.getNode(ISD::BUILD_VECTOR, dl,
4033 MVT::v16i8, &pshufbMask[0], 16));
4037 // Calculate the shuffle mask for the second input, shuffle it, and
4038 // OR it with the first shuffled input.
4040 for (unsigned i = 0; i != 16; ++i) {
4041 int EltIdx = MaskVals[i];
4043 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4046 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4048 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4049 DAG.getNode(ISD::BUILD_VECTOR, dl,
4050 MVT::v16i8, &pshufbMask[0], 16));
4051 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4054 // No SSSE3 - Calculate in place words and then fix all out of place words
4055 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4056 // the 16 different words that comprise the two doublequadword input vectors.
4057 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4058 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4059 SDValue NewV = V2Only ? V2 : V1;
4060 for (int i = 0; i != 8; ++i) {
4061 int Elt0 = MaskVals[i*2];
4062 int Elt1 = MaskVals[i*2+1];
4064 // This word of the result is all undef, skip it.
4065 if (Elt0 < 0 && Elt1 < 0)
4068 // This word of the result is already in the correct place, skip it.
4069 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4071 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4074 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4075 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4078 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4079 // using a single extract together, load it and store it.
4080 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4081 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4082 DAG.getIntPtrConstant(Elt1 / 2));
4083 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4084 DAG.getIntPtrConstant(i));
4088 // If Elt1 is defined, extract it from the appropriate source. If the
4089 // source byte is not also odd, shift the extracted word left 8 bits
4090 // otherwise clear the bottom 8 bits if we need to do an or.
4092 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4093 DAG.getIntPtrConstant(Elt1 / 2));
4094 if ((Elt1 & 1) == 0)
4095 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4096 DAG.getConstant(8, TLI.getShiftAmountTy()));
4098 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4099 DAG.getConstant(0xFF00, MVT::i16));
4101 // If Elt0 is defined, extract it from the appropriate source. If the
4102 // source byte is not also even, shift the extracted word right 8 bits. If
4103 // Elt1 was also defined, OR the extracted values together before
4104 // inserting them in the result.
4106 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4107 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4108 if ((Elt0 & 1) != 0)
4109 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4110 DAG.getConstant(8, TLI.getShiftAmountTy()));
4112 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4113 DAG.getConstant(0x00FF, MVT::i16));
4114 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4117 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4118 DAG.getIntPtrConstant(i));
4120 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4123 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4124 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4125 /// done when every pair / quad of shuffle mask elements point to elements in
4126 /// the right sequence. e.g.
4127 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4129 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4131 TargetLowering &TLI, DebugLoc dl) {
4132 EVT VT = SVOp->getValueType(0);
4133 SDValue V1 = SVOp->getOperand(0);
4134 SDValue V2 = SVOp->getOperand(1);
4135 unsigned NumElems = VT.getVectorNumElements();
4136 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4137 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4138 EVT MaskEltVT = MaskVT.getVectorElementType();
4140 switch (VT.getSimpleVT().SimpleTy) {
4141 default: assert(false && "Unexpected!");
4142 case MVT::v4f32: NewVT = MVT::v2f64; break;
4143 case MVT::v4i32: NewVT = MVT::v2i64; break;
4144 case MVT::v8i16: NewVT = MVT::v4i32; break;
4145 case MVT::v16i8: NewVT = MVT::v4i32; break;
4148 if (NewWidth == 2) {
4154 int Scale = NumElems / NewWidth;
4155 SmallVector<int, 8> MaskVec;
4156 for (unsigned i = 0; i < NumElems; i += Scale) {
4158 for (int j = 0; j < Scale; ++j) {
4159 int EltIdx = SVOp->getMaskElt(i+j);
4163 StartIdx = EltIdx - (EltIdx % Scale);
4164 if (EltIdx != StartIdx + j)
4168 MaskVec.push_back(-1);
4170 MaskVec.push_back(StartIdx / Scale);
4173 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4174 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4175 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4178 /// getVZextMovL - Return a zero-extending vector move low node.
4180 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4181 SDValue SrcOp, SelectionDAG &DAG,
4182 const X86Subtarget *Subtarget, DebugLoc dl) {
4183 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4184 LoadSDNode *LD = NULL;
4185 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4186 LD = dyn_cast<LoadSDNode>(SrcOp);
4188 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4190 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4191 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4192 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4193 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4194 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4196 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4197 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4198 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4199 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4207 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4208 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4209 DAG.getNode(ISD::BIT_CONVERT, dl,
4213 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4216 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4217 SDValue V1 = SVOp->getOperand(0);
4218 SDValue V2 = SVOp->getOperand(1);
4219 DebugLoc dl = SVOp->getDebugLoc();
4220 EVT VT = SVOp->getValueType(0);
4222 SmallVector<std::pair<int, int>, 8> Locs;
4224 SmallVector<int, 8> Mask1(4U, -1);
4225 SmallVector<int, 8> PermMask;
4226 SVOp->getMask(PermMask);
4230 for (unsigned i = 0; i != 4; ++i) {
4231 int Idx = PermMask[i];
4233 Locs[i] = std::make_pair(-1, -1);
4235 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4237 Locs[i] = std::make_pair(0, NumLo);
4241 Locs[i] = std::make_pair(1, NumHi);
4243 Mask1[2+NumHi] = Idx;
4249 if (NumLo <= 2 && NumHi <= 2) {
4250 // If no more than two elements come from either vector. This can be
4251 // implemented with two shuffles. First shuffle gather the elements.
4252 // The second shuffle, which takes the first shuffle as both of its
4253 // vector operands, put the elements into the right order.
4254 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4256 SmallVector<int, 8> Mask2(4U, -1);
4258 for (unsigned i = 0; i != 4; ++i) {
4259 if (Locs[i].first == -1)
4262 unsigned Idx = (i < 2) ? 0 : 4;
4263 Idx += Locs[i].first * 2 + Locs[i].second;
4268 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4269 } else if (NumLo == 3 || NumHi == 3) {
4270 // Otherwise, we must have three elements from one vector, call it X, and
4271 // one element from the other, call it Y. First, use a shufps to build an
4272 // intermediate vector with the one element from Y and the element from X
4273 // that will be in the same half in the final destination (the indexes don't
4274 // matter). Then, use a shufps to build the final vector, taking the half
4275 // containing the element from Y from the intermediate, and the other half
4278 // Normalize it so the 3 elements come from V1.
4279 CommuteVectorShuffleMask(PermMask, VT);
4283 // Find the element from V2.
4285 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4286 int Val = PermMask[HiIndex];
4293 Mask1[0] = PermMask[HiIndex];
4295 Mask1[2] = PermMask[HiIndex^1];
4297 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4300 Mask1[0] = PermMask[0];
4301 Mask1[1] = PermMask[1];
4302 Mask1[2] = HiIndex & 1 ? 6 : 4;
4303 Mask1[3] = HiIndex & 1 ? 4 : 6;
4304 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4306 Mask1[0] = HiIndex & 1 ? 2 : 0;
4307 Mask1[1] = HiIndex & 1 ? 0 : 2;
4308 Mask1[2] = PermMask[2];
4309 Mask1[3] = PermMask[3];
4314 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4318 // Break it into (shuffle shuffle_hi, shuffle_lo).
4320 SmallVector<int,8> LoMask(4U, -1);
4321 SmallVector<int,8> HiMask(4U, -1);
4323 SmallVector<int,8> *MaskPtr = &LoMask;
4324 unsigned MaskIdx = 0;
4327 for (unsigned i = 0; i != 4; ++i) {
4334 int Idx = PermMask[i];
4336 Locs[i] = std::make_pair(-1, -1);
4337 } else if (Idx < 4) {
4338 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4339 (*MaskPtr)[LoIdx] = Idx;
4342 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4343 (*MaskPtr)[HiIdx] = Idx;
4348 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4349 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4350 SmallVector<int, 8> MaskOps;
4351 for (unsigned i = 0; i != 4; ++i) {
4352 if (Locs[i].first == -1) {
4353 MaskOps.push_back(-1);
4355 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4356 MaskOps.push_back(Idx);
4359 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4363 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4364 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4365 SDValue V1 = Op.getOperand(0);
4366 SDValue V2 = Op.getOperand(1);
4367 EVT VT = Op.getValueType();
4368 DebugLoc dl = Op.getDebugLoc();
4369 unsigned NumElems = VT.getVectorNumElements();
4370 bool isMMX = VT.getSizeInBits() == 64;
4371 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4372 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4373 bool V1IsSplat = false;
4374 bool V2IsSplat = false;
4376 if (isZeroShuffle(SVOp))
4377 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4379 // Promote splats to v4f32.
4380 if (SVOp->isSplat()) {
4381 if (isMMX || NumElems < 4)
4383 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4386 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4388 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4389 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4390 if (NewOp.getNode())
4391 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4392 LowerVECTOR_SHUFFLE(NewOp, DAG));
4393 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4394 // FIXME: Figure out a cleaner way to do this.
4395 // Try to make use of movq to zero out the top part.
4396 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4397 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4398 if (NewOp.getNode()) {
4399 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4400 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4401 DAG, Subtarget, dl);
4403 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4404 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4405 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4406 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4407 DAG, Subtarget, dl);
4411 if (X86::isPSHUFDMask(SVOp))
4414 // Check if this can be converted into a logical shift.
4415 bool isLeft = false;
4418 bool isShift = getSubtarget()->hasSSE2() &&
4419 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4420 if (isShift && ShVal.hasOneUse()) {
4421 // If the shifted value has multiple uses, it may be cheaper to use
4422 // v_set0 + movlhps or movhlps, etc.
4423 EVT EltVT = VT.getVectorElementType();
4424 ShAmt *= EltVT.getSizeInBits();
4425 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4428 if (X86::isMOVLMask(SVOp)) {
4431 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4432 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4437 // FIXME: fold these into legal mask.
4438 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4439 X86::isMOVSLDUPMask(SVOp) ||
4440 X86::isMOVHLPSMask(SVOp) ||
4441 X86::isMOVLHPSMask(SVOp) ||
4442 X86::isMOVLPMask(SVOp)))
4445 if (ShouldXformToMOVHLPS(SVOp) ||
4446 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4447 return CommuteVectorShuffle(SVOp, DAG);
4450 // No better options. Use a vshl / vsrl.
4451 EVT EltVT = VT.getVectorElementType();
4452 ShAmt *= EltVT.getSizeInBits();
4453 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4456 bool Commuted = false;
4457 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4458 // 1,1,1,1 -> v8i16 though.
4459 V1IsSplat = isSplatVector(V1.getNode());
4460 V2IsSplat = isSplatVector(V2.getNode());
4462 // Canonicalize the splat or undef, if present, to be on the RHS.
4463 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4464 Op = CommuteVectorShuffle(SVOp, DAG);
4465 SVOp = cast<ShuffleVectorSDNode>(Op);
4466 V1 = SVOp->getOperand(0);
4467 V2 = SVOp->getOperand(1);
4468 std::swap(V1IsSplat, V2IsSplat);
4469 std::swap(V1IsUndef, V2IsUndef);
4473 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4474 // Shuffling low element of v1 into undef, just return v1.
4477 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4478 // the instruction selector will not match, so get a canonical MOVL with
4479 // swapped operands to undo the commute.
4480 return getMOVL(DAG, dl, VT, V2, V1);
4483 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4484 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4485 X86::isUNPCKLMask(SVOp) ||
4486 X86::isUNPCKHMask(SVOp))
4490 // Normalize mask so all entries that point to V2 points to its first
4491 // element then try to match unpck{h|l} again. If match, return a
4492 // new vector_shuffle with the corrected mask.
4493 SDValue NewMask = NormalizeMask(SVOp, DAG);
4494 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4495 if (NSVOp != SVOp) {
4496 if (X86::isUNPCKLMask(NSVOp, true)) {
4498 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4505 // Commute is back and try unpck* again.
4506 // FIXME: this seems wrong.
4507 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4508 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4509 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4510 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4511 X86::isUNPCKLMask(NewSVOp) ||
4512 X86::isUNPCKHMask(NewSVOp))
4516 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4518 // Normalize the node to match x86 shuffle ops if needed
4519 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4520 return CommuteVectorShuffle(SVOp, DAG);
4522 // Check for legal shuffle and return?
4523 SmallVector<int, 16> PermMask;
4524 SVOp->getMask(PermMask);
4525 if (isShuffleMaskLegal(PermMask, VT))
4528 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4529 if (VT == MVT::v8i16) {
4530 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4531 if (NewOp.getNode())
4535 if (VT == MVT::v16i8) {
4536 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4537 if (NewOp.getNode())
4541 // Handle all 4 wide cases with a number of shuffles except for MMX.
4542 if (NumElems == 4 && !isMMX)
4543 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4549 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4550 SelectionDAG &DAG) {
4551 EVT VT = Op.getValueType();
4552 DebugLoc dl = Op.getDebugLoc();
4553 if (VT.getSizeInBits() == 8) {
4554 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4555 Op.getOperand(0), Op.getOperand(1));
4556 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4557 DAG.getValueType(VT));
4558 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4559 } else if (VT.getSizeInBits() == 16) {
4560 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4561 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4563 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4564 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4565 DAG.getNode(ISD::BIT_CONVERT, dl,
4569 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4570 Op.getOperand(0), Op.getOperand(1));
4571 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4572 DAG.getValueType(VT));
4573 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4574 } else if (VT == MVT::f32) {
4575 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4576 // the result back to FR32 register. It's only worth matching if the
4577 // result has a single use which is a store or a bitcast to i32. And in
4578 // the case of a store, it's not worth it if the index is a constant 0,
4579 // because a MOVSSmr can be used instead, which is smaller and faster.
4580 if (!Op.hasOneUse())
4582 SDNode *User = *Op.getNode()->use_begin();
4583 if ((User->getOpcode() != ISD::STORE ||
4584 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4585 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4586 (User->getOpcode() != ISD::BIT_CONVERT ||
4587 User->getValueType(0) != MVT::i32))
4589 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4590 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4593 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4594 } else if (VT == MVT::i32) {
4595 // ExtractPS works with constant index.
4596 if (isa<ConstantSDNode>(Op.getOperand(1)))
4604 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4605 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4608 if (Subtarget->hasSSE41()) {
4609 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4614 EVT VT = Op.getValueType();
4615 DebugLoc dl = Op.getDebugLoc();
4616 // TODO: handle v16i8.
4617 if (VT.getSizeInBits() == 16) {
4618 SDValue Vec = Op.getOperand(0);
4619 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4621 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4622 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4623 DAG.getNode(ISD::BIT_CONVERT, dl,
4626 // Transform it so it match pextrw which produces a 32-bit result.
4627 EVT EltVT = MVT::i32;
4628 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4629 Op.getOperand(0), Op.getOperand(1));
4630 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4631 DAG.getValueType(VT));
4632 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4633 } else if (VT.getSizeInBits() == 32) {
4634 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4638 // SHUFPS the element to the lowest double word, then movss.
4639 int Mask[4] = { Idx, -1, -1, -1 };
4640 EVT VVT = Op.getOperand(0).getValueType();
4641 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4642 DAG.getUNDEF(VVT), Mask);
4643 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4644 DAG.getIntPtrConstant(0));
4645 } else if (VT.getSizeInBits() == 64) {
4646 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4647 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4648 // to match extract_elt for f64.
4649 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4653 // UNPCKHPD the element to the lowest double word, then movsd.
4654 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4655 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4656 int Mask[2] = { 1, -1 };
4657 EVT VVT = Op.getOperand(0).getValueType();
4658 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4659 DAG.getUNDEF(VVT), Mask);
4660 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4661 DAG.getIntPtrConstant(0));
4668 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4669 EVT VT = Op.getValueType();
4670 EVT EltVT = VT.getVectorElementType();
4671 DebugLoc dl = Op.getDebugLoc();
4673 SDValue N0 = Op.getOperand(0);
4674 SDValue N1 = Op.getOperand(1);
4675 SDValue N2 = Op.getOperand(2);
4677 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4678 isa<ConstantSDNode>(N2)) {
4679 unsigned Opc = (EltVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4681 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4683 if (N1.getValueType() != MVT::i32)
4684 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4685 if (N2.getValueType() != MVT::i32)
4686 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4687 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4688 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4689 // Bits [7:6] of the constant are the source select. This will always be
4690 // zero here. The DAG Combiner may combine an extract_elt index into these
4691 // bits. For example (insert (extract, 3), 2) could be matched by putting
4692 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4693 // Bits [5:4] of the constant are the destination select. This is the
4694 // value of the incoming immediate.
4695 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4696 // combine either bitwise AND or insert of float 0.0 to set these bits.
4697 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4698 // Create this as a scalar to vector..
4699 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4700 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4701 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4702 // PINSR* works with constant index.
4709 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4710 EVT VT = Op.getValueType();
4711 EVT EltVT = VT.getVectorElementType();
4713 if (Subtarget->hasSSE41())
4714 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4716 if (EltVT == MVT::i8)
4719 DebugLoc dl = Op.getDebugLoc();
4720 SDValue N0 = Op.getOperand(0);
4721 SDValue N1 = Op.getOperand(1);
4722 SDValue N2 = Op.getOperand(2);
4724 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4725 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4726 // as its second argument.
4727 if (N1.getValueType() != MVT::i32)
4728 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4729 if (N2.getValueType() != MVT::i32)
4730 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4731 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4737 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4738 DebugLoc dl = Op.getDebugLoc();
4739 if (Op.getValueType() == MVT::v2f32)
4740 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4741 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4742 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4743 Op.getOperand(0))));
4745 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4746 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4748 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4749 EVT VT = MVT::v2i32;
4750 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4757 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4758 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4761 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4762 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4763 // one of the above mentioned nodes. It has to be wrapped because otherwise
4764 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4765 // be used to form addressing mode. These wrapped nodes will be selected
4768 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4769 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4771 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4773 unsigned char OpFlag = 0;
4774 unsigned WrapperKind = X86ISD::Wrapper;
4775 CodeModel::Model M = getTargetMachine().getCodeModel();
4777 if (Subtarget->isPICStyleRIPRel() &&
4778 (M == CodeModel::Small || M == CodeModel::Kernel))
4779 WrapperKind = X86ISD::WrapperRIP;
4780 else if (Subtarget->isPICStyleGOT())
4781 OpFlag = X86II::MO_GOTOFF;
4782 else if (Subtarget->isPICStyleStubPIC())
4783 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4785 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4787 CP->getOffset(), OpFlag);
4788 DebugLoc DL = CP->getDebugLoc();
4789 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4790 // With PIC, the address is actually $g + Offset.
4792 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4793 DAG.getNode(X86ISD::GlobalBaseReg,
4794 DebugLoc::getUnknownLoc(), getPointerTy()),
4801 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4802 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4804 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4806 unsigned char OpFlag = 0;
4807 unsigned WrapperKind = X86ISD::Wrapper;
4808 CodeModel::Model M = getTargetMachine().getCodeModel();
4810 if (Subtarget->isPICStyleRIPRel() &&
4811 (M == CodeModel::Small || M == CodeModel::Kernel))
4812 WrapperKind = X86ISD::WrapperRIP;
4813 else if (Subtarget->isPICStyleGOT())
4814 OpFlag = X86II::MO_GOTOFF;
4815 else if (Subtarget->isPICStyleStubPIC())
4816 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4818 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4820 DebugLoc DL = JT->getDebugLoc();
4821 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4823 // With PIC, the address is actually $g + Offset.
4825 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4826 DAG.getNode(X86ISD::GlobalBaseReg,
4827 DebugLoc::getUnknownLoc(), getPointerTy()),
4835 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4836 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4838 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4840 unsigned char OpFlag = 0;
4841 unsigned WrapperKind = X86ISD::Wrapper;
4842 CodeModel::Model M = getTargetMachine().getCodeModel();
4844 if (Subtarget->isPICStyleRIPRel() &&
4845 (M == CodeModel::Small || M == CodeModel::Kernel))
4846 WrapperKind = X86ISD::WrapperRIP;
4847 else if (Subtarget->isPICStyleGOT())
4848 OpFlag = X86II::MO_GOTOFF;
4849 else if (Subtarget->isPICStyleStubPIC())
4850 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4852 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4854 DebugLoc DL = Op.getDebugLoc();
4855 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4858 // With PIC, the address is actually $g + Offset.
4859 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4860 !Subtarget->is64Bit()) {
4861 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4862 DAG.getNode(X86ISD::GlobalBaseReg,
4863 DebugLoc::getUnknownLoc(),
4872 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
4873 // Create the TargetBlockAddressAddress node.
4874 unsigned char OpFlags =
4875 Subtarget->ClassifyBlockAddressReference();
4876 CodeModel::Model M = getTargetMachine().getCodeModel();
4877 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4878 DebugLoc dl = Op.getDebugLoc();
4879 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
4880 /*isTarget=*/true, OpFlags);
4882 if (Subtarget->isPICStyleRIPRel() &&
4883 (M == CodeModel::Small || M == CodeModel::Kernel))
4884 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4886 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4888 // With PIC, the address is actually $g + Offset.
4889 if (isGlobalRelativeToPICBase(OpFlags)) {
4890 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4891 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4899 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4901 SelectionDAG &DAG) const {
4902 // Create the TargetGlobalAddress node, folding in the constant
4903 // offset if it is legal.
4904 unsigned char OpFlags =
4905 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4906 CodeModel::Model M = getTargetMachine().getCodeModel();
4908 if (OpFlags == X86II::MO_NO_FLAG &&
4909 X86::isOffsetSuitableForCodeModel(Offset, M)) {
4910 // A direct static reference to a global.
4911 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4914 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4917 if (Subtarget->isPICStyleRIPRel() &&
4918 (M == CodeModel::Small || M == CodeModel::Kernel))
4919 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4921 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4923 // With PIC, the address is actually $g + Offset.
4924 if (isGlobalRelativeToPICBase(OpFlags)) {
4925 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4926 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4930 // For globals that require a load from a stub to get the address, emit the
4932 if (isGlobalStubReference(OpFlags))
4933 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4934 PseudoSourceValue::getGOT(), 0);
4936 // If there was a non-zero offset that we didn't fold, create an explicit
4939 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4940 DAG.getConstant(Offset, getPointerTy()));
4946 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4947 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4948 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4949 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4953 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4954 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4955 unsigned char OperandFlags) {
4956 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4957 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4958 DebugLoc dl = GA->getDebugLoc();
4959 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4960 GA->getValueType(0),
4964 SDValue Ops[] = { Chain, TGA, *InFlag };
4965 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4967 SDValue Ops[] = { Chain, TGA };
4968 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4971 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
4972 MFI->setHasCalls(true);
4974 SDValue Flag = Chain.getValue(1);
4975 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4978 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4980 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4983 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4984 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4985 DAG.getNode(X86ISD::GlobalBaseReg,
4986 DebugLoc::getUnknownLoc(),
4988 InFlag = Chain.getValue(1);
4990 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
4993 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4995 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4997 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
4998 X86::RAX, X86II::MO_TLSGD);
5001 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5002 // "local exec" model.
5003 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5004 const EVT PtrVT, TLSModel::Model model,
5006 DebugLoc dl = GA->getDebugLoc();
5007 // Get the Thread Pointer
5008 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5009 DebugLoc::getUnknownLoc(), PtrVT,
5010 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5013 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5016 unsigned char OperandFlags = 0;
5017 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5019 unsigned WrapperKind = X86ISD::Wrapper;
5020 if (model == TLSModel::LocalExec) {
5021 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5022 } else if (is64Bit) {
5023 assert(model == TLSModel::InitialExec);
5024 OperandFlags = X86II::MO_GOTTPOFF;
5025 WrapperKind = X86ISD::WrapperRIP;
5027 assert(model == TLSModel::InitialExec);
5028 OperandFlags = X86II::MO_INDNTPOFF;
5031 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5033 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5034 GA->getOffset(), OperandFlags);
5035 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5037 if (model == TLSModel::InitialExec)
5038 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5039 PseudoSourceValue::getGOT(), 0);
5041 // The address of the thread local variable is the add of the thread
5042 // pointer with the offset of the variable.
5043 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5047 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5048 // TODO: implement the "local dynamic" model
5049 // TODO: implement the "initial exec"model for pic executables
5050 assert(Subtarget->isTargetELF() &&
5051 "TLS not implemented for non-ELF targets");
5052 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5053 const GlobalValue *GV = GA->getGlobal();
5055 // If GV is an alias then use the aliasee for determining
5056 // thread-localness.
5057 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5058 GV = GA->resolveAliasedGlobal(false);
5060 TLSModel::Model model = getTLSModel(GV,
5061 getTargetMachine().getRelocationModel());
5064 case TLSModel::GeneralDynamic:
5065 case TLSModel::LocalDynamic: // not implemented
5066 if (Subtarget->is64Bit())
5067 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5068 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5070 case TLSModel::InitialExec:
5071 case TLSModel::LocalExec:
5072 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5073 Subtarget->is64Bit());
5076 llvm_unreachable("Unreachable");
5081 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5082 /// take a 2 x i32 value to shift plus a shift amount.
5083 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5084 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5085 EVT VT = Op.getValueType();
5086 unsigned VTBits = VT.getSizeInBits();
5087 DebugLoc dl = Op.getDebugLoc();
5088 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5089 SDValue ShOpLo = Op.getOperand(0);
5090 SDValue ShOpHi = Op.getOperand(1);
5091 SDValue ShAmt = Op.getOperand(2);
5092 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5093 DAG.getConstant(VTBits - 1, MVT::i8))
5094 : DAG.getConstant(0, VT);
5097 if (Op.getOpcode() == ISD::SHL_PARTS) {
5098 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5099 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5101 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5102 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5105 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5106 DAG.getConstant(VTBits, MVT::i8));
5107 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
5108 AndNode, DAG.getConstant(0, MVT::i8));
5111 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5112 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5113 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5115 if (Op.getOpcode() == ISD::SHL_PARTS) {
5116 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5117 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5119 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5120 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5123 SDValue Ops[2] = { Lo, Hi };
5124 return DAG.getMergeValues(Ops, 2, dl);
5127 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5128 EVT SrcVT = Op.getOperand(0).getValueType();
5130 if (SrcVT.isVector()) {
5131 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5137 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5138 "Unknown SINT_TO_FP to lower!");
5140 // These are really Legal; return the operand so the caller accepts it as
5142 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5144 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5145 Subtarget->is64Bit()) {
5149 DebugLoc dl = Op.getDebugLoc();
5150 unsigned Size = SrcVT.getSizeInBits()/8;
5151 MachineFunction &MF = DAG.getMachineFunction();
5152 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5153 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5154 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5156 PseudoSourceValue::getFixedStack(SSFI), 0);
5157 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5160 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5162 SelectionDAG &DAG) {
5164 DebugLoc dl = Op.getDebugLoc();
5166 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5168 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5170 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5171 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5172 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5173 Tys, Ops, array_lengthof(Ops));
5176 Chain = Result.getValue(1);
5177 SDValue InFlag = Result.getValue(2);
5179 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5180 // shouldn't be necessary except that RFP cannot be live across
5181 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5182 MachineFunction &MF = DAG.getMachineFunction();
5183 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5184 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5185 Tys = DAG.getVTList(MVT::Other);
5187 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5189 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5190 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5191 PseudoSourceValue::getFixedStack(SSFI), 0);
5197 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5198 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5199 // This algorithm is not obvious. Here it is in C code, more or less:
5201 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5202 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5203 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5205 // Copy ints to xmm registers.
5206 __m128i xh = _mm_cvtsi32_si128( hi );
5207 __m128i xl = _mm_cvtsi32_si128( lo );
5209 // Combine into low half of a single xmm register.
5210 __m128i x = _mm_unpacklo_epi32( xh, xl );
5214 // Merge in appropriate exponents to give the integer bits the right
5216 x = _mm_unpacklo_epi32( x, exp );
5218 // Subtract away the biases to deal with the IEEE-754 double precision
5220 d = _mm_sub_pd( (__m128d) x, bias );
5222 // All conversions up to here are exact. The correctly rounded result is
5223 // calculated using the current rounding mode using the following
5225 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5226 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5227 // store doesn't really need to be here (except
5228 // maybe to zero the other double)
5233 DebugLoc dl = Op.getDebugLoc();
5234 LLVMContext *Context = DAG.getContext();
5236 // Build some magic constants.
5237 std::vector<Constant*> CV0;
5238 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5239 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5240 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5241 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5242 Constant *C0 = ConstantVector::get(CV0);
5243 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5245 std::vector<Constant*> CV1;
5247 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5249 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5250 Constant *C1 = ConstantVector::get(CV1);
5251 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5253 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5254 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5256 DAG.getIntPtrConstant(1)));
5257 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5258 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5260 DAG.getIntPtrConstant(0)));
5261 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5262 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5263 PseudoSourceValue::getConstantPool(), 0,
5265 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5266 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5267 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5268 PseudoSourceValue::getConstantPool(), 0,
5270 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5272 // Add the halves; easiest way is to swap them into another reg first.
5273 int ShufMask[2] = { 1, -1 };
5274 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5275 DAG.getUNDEF(MVT::v2f64), ShufMask);
5276 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5277 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5278 DAG.getIntPtrConstant(0));
5281 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5282 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5283 DebugLoc dl = Op.getDebugLoc();
5284 // FP constant to bias correct the final result.
5285 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5288 // Load the 32-bit value into an XMM register.
5289 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5290 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5292 DAG.getIntPtrConstant(0)));
5294 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5295 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5296 DAG.getIntPtrConstant(0));
5298 // Or the load with the bias.
5299 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5300 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5301 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5303 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5304 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5305 MVT::v2f64, Bias)));
5306 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5307 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5308 DAG.getIntPtrConstant(0));
5310 // Subtract the bias.
5311 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5313 // Handle final rounding.
5314 EVT DestVT = Op.getValueType();
5316 if (DestVT.bitsLT(MVT::f64)) {
5317 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5318 DAG.getIntPtrConstant(0));
5319 } else if (DestVT.bitsGT(MVT::f64)) {
5320 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5323 // Handle final rounding.
5327 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5328 SDValue N0 = Op.getOperand(0);
5329 DebugLoc dl = Op.getDebugLoc();
5331 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5332 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5333 // the optimization here.
5334 if (DAG.SignBitIsZero(N0))
5335 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5337 EVT SrcVT = N0.getValueType();
5338 if (SrcVT == MVT::i64) {
5339 // We only handle SSE2 f64 target here; caller can expand the rest.
5340 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5343 return LowerUINT_TO_FP_i64(Op, DAG);
5344 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5345 return LowerUINT_TO_FP_i32(Op, DAG);
5348 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5350 // Make a 64-bit buffer, and use it to build an FILD.
5351 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5352 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5353 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5354 getPointerTy(), StackSlot, WordOff);
5355 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5356 StackSlot, NULL, 0);
5357 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5358 OffsetSlot, NULL, 0);
5359 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5362 std::pair<SDValue,SDValue> X86TargetLowering::
5363 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5364 DebugLoc dl = Op.getDebugLoc();
5366 EVT DstTy = Op.getValueType();
5369 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5373 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5374 DstTy.getSimpleVT() >= MVT::i16 &&
5375 "Unknown FP_TO_SINT to lower!");
5377 // These are really Legal.
5378 if (DstTy == MVT::i32 &&
5379 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5380 return std::make_pair(SDValue(), SDValue());
5381 if (Subtarget->is64Bit() &&
5382 DstTy == MVT::i64 &&
5383 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5384 return std::make_pair(SDValue(), SDValue());
5386 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5388 MachineFunction &MF = DAG.getMachineFunction();
5389 unsigned MemSize = DstTy.getSizeInBits()/8;
5390 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5391 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5394 switch (DstTy.getSimpleVT().SimpleTy) {
5395 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5396 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5397 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5398 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5401 SDValue Chain = DAG.getEntryNode();
5402 SDValue Value = Op.getOperand(0);
5403 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5404 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5405 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5406 PseudoSourceValue::getFixedStack(SSFI), 0);
5407 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5409 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5411 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5412 Chain = Value.getValue(1);
5413 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5414 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5417 // Build the FP_TO_INT*_IN_MEM
5418 SDValue Ops[] = { Chain, Value, StackSlot };
5419 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5421 return std::make_pair(FIST, StackSlot);
5424 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5425 if (Op.getValueType().isVector()) {
5426 if (Op.getValueType() == MVT::v2i32 &&
5427 Op.getOperand(0).getValueType() == MVT::v2f64) {
5433 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5434 SDValue FIST = Vals.first, StackSlot = Vals.second;
5435 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5436 if (FIST.getNode() == 0) return Op;
5439 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5440 FIST, StackSlot, NULL, 0);
5443 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5444 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5445 SDValue FIST = Vals.first, StackSlot = Vals.second;
5446 assert(FIST.getNode() && "Unexpected failure");
5449 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5450 FIST, StackSlot, NULL, 0);
5453 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5454 LLVMContext *Context = DAG.getContext();
5455 DebugLoc dl = Op.getDebugLoc();
5456 EVT VT = Op.getValueType();
5459 EltVT = VT.getVectorElementType();
5460 std::vector<Constant*> CV;
5461 if (EltVT == MVT::f64) {
5462 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5466 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5472 Constant *C = ConstantVector::get(CV);
5473 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5474 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5475 PseudoSourceValue::getConstantPool(), 0,
5477 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5480 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5481 LLVMContext *Context = DAG.getContext();
5482 DebugLoc dl = Op.getDebugLoc();
5483 EVT VT = Op.getValueType();
5486 EltVT = VT.getVectorElementType();
5487 std::vector<Constant*> CV;
5488 if (EltVT == MVT::f64) {
5489 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5493 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5499 Constant *C = ConstantVector::get(CV);
5500 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5501 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5502 PseudoSourceValue::getConstantPool(), 0,
5504 if (VT.isVector()) {
5505 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5506 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5507 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5509 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5511 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5515 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5516 LLVMContext *Context = DAG.getContext();
5517 SDValue Op0 = Op.getOperand(0);
5518 SDValue Op1 = Op.getOperand(1);
5519 DebugLoc dl = Op.getDebugLoc();
5520 EVT VT = Op.getValueType();
5521 EVT SrcVT = Op1.getValueType();
5523 // If second operand is smaller, extend it first.
5524 if (SrcVT.bitsLT(VT)) {
5525 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5528 // And if it is bigger, shrink it first.
5529 if (SrcVT.bitsGT(VT)) {
5530 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5534 // At this point the operands and the result should have the same
5535 // type, and that won't be f80 since that is not custom lowered.
5537 // First get the sign bit of second operand.
5538 std::vector<Constant*> CV;
5539 if (SrcVT == MVT::f64) {
5540 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5541 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5543 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5544 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5545 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5546 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5548 Constant *C = ConstantVector::get(CV);
5549 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5550 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5551 PseudoSourceValue::getConstantPool(), 0,
5553 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5555 // Shift sign bit right or left if the two operands have different types.
5556 if (SrcVT.bitsGT(VT)) {
5557 // Op0 is MVT::f32, Op1 is MVT::f64.
5558 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5559 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5560 DAG.getConstant(32, MVT::i32));
5561 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5562 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5563 DAG.getIntPtrConstant(0));
5566 // Clear first operand sign bit.
5568 if (VT == MVT::f64) {
5569 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5570 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5572 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5573 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5574 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5575 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5577 C = ConstantVector::get(CV);
5578 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5579 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5580 PseudoSourceValue::getConstantPool(), 0,
5582 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5584 // Or the value with the sign bit.
5585 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5588 /// Emit nodes that will be selected as "test Op0,Op0", or something
5590 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5591 SelectionDAG &DAG) {
5592 DebugLoc dl = Op.getDebugLoc();
5594 // CF and OF aren't always set the way we want. Determine which
5595 // of these we need.
5596 bool NeedCF = false;
5597 bool NeedOF = false;
5599 case X86::COND_A: case X86::COND_AE:
5600 case X86::COND_B: case X86::COND_BE:
5603 case X86::COND_G: case X86::COND_GE:
5604 case X86::COND_L: case X86::COND_LE:
5605 case X86::COND_O: case X86::COND_NO:
5611 // See if we can use the EFLAGS value from the operand instead of
5612 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5613 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5614 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5615 unsigned Opcode = 0;
5616 unsigned NumOperands = 0;
5617 switch (Op.getNode()->getOpcode()) {
5619 // Due to an isel shortcoming, be conservative if this add is likely to
5620 // be selected as part of a load-modify-store instruction. When the root
5621 // node in a match is a store, isel doesn't know how to remap non-chain
5622 // non-flag uses of other nodes in the match, such as the ADD in this
5623 // case. This leads to the ADD being left around and reselected, with
5624 // the result being two adds in the output.
5625 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5626 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5627 if (UI->getOpcode() == ISD::STORE)
5629 if (ConstantSDNode *C =
5630 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5631 // An add of one will be selected as an INC.
5632 if (C->getAPIntValue() == 1) {
5633 Opcode = X86ISD::INC;
5637 // An add of negative one (subtract of one) will be selected as a DEC.
5638 if (C->getAPIntValue().isAllOnesValue()) {
5639 Opcode = X86ISD::DEC;
5644 // Otherwise use a regular EFLAGS-setting add.
5645 Opcode = X86ISD::ADD;
5649 // If the primary and result isn't used, don't bother using X86ISD::AND,
5650 // because a TEST instruction will be better.
5651 bool NonFlagUse = false;
5652 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5653 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5655 unsigned UOpNo = UI.getOperandNo();
5656 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5657 // Look pass truncate.
5658 UOpNo = User->use_begin().getOperandNo();
5659 User = *User->use_begin();
5661 if (User->getOpcode() != ISD::BRCOND &&
5662 User->getOpcode() != ISD::SETCC &&
5663 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5675 // Due to the ISEL shortcoming noted above, be conservative if this op is
5676 // likely to be selected as part of a load-modify-store instruction.
5677 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5678 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5679 if (UI->getOpcode() == ISD::STORE)
5681 // Otherwise use a regular EFLAGS-setting instruction.
5682 switch (Op.getNode()->getOpcode()) {
5683 case ISD::SUB: Opcode = X86ISD::SUB; break;
5684 case ISD::OR: Opcode = X86ISD::OR; break;
5685 case ISD::XOR: Opcode = X86ISD::XOR; break;
5686 case ISD::AND: Opcode = X86ISD::AND; break;
5687 default: llvm_unreachable("unexpected operator!");
5698 return SDValue(Op.getNode(), 1);
5704 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5705 SmallVector<SDValue, 4> Ops;
5706 for (unsigned i = 0; i != NumOperands; ++i)
5707 Ops.push_back(Op.getOperand(i));
5708 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5709 DAG.ReplaceAllUsesWith(Op, New);
5710 return SDValue(New.getNode(), 1);
5714 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5715 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5716 DAG.getConstant(0, Op.getValueType()));
5719 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5721 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5722 SelectionDAG &DAG) {
5723 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5724 if (C->getAPIntValue() == 0)
5725 return EmitTest(Op0, X86CC, DAG);
5727 DebugLoc dl = Op0.getDebugLoc();
5728 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5731 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
5732 /// if it's possible.
5733 static SDValue LowerToBT(SDValue Op0, ISD::CondCode CC,
5734 DebugLoc dl, SelectionDAG &DAG) {
5736 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5737 if (ConstantSDNode *Op010C =
5738 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5739 if (Op010C->getZExtValue() == 1) {
5740 LHS = Op0.getOperand(0);
5741 RHS = Op0.getOperand(1).getOperand(1);
5743 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5744 if (ConstantSDNode *Op000C =
5745 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5746 if (Op000C->getZExtValue() == 1) {
5747 LHS = Op0.getOperand(1);
5748 RHS = Op0.getOperand(0).getOperand(1);
5750 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5751 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5752 SDValue AndLHS = Op0.getOperand(0);
5753 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5754 LHS = AndLHS.getOperand(0);
5755 RHS = AndLHS.getOperand(1);
5759 if (LHS.getNode()) {
5760 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5761 // instruction. Since the shift amount is in-range-or-undefined, we know
5762 // that doing a bittest on the i16 value is ok. We extend to i32 because
5763 // the encoding for the i16 version is larger than the i32 version.
5764 if (LHS.getValueType() == MVT::i8)
5765 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5767 // If the operand types disagree, extend the shift amount to match. Since
5768 // BT ignores high bits (like shifts) we can use anyextend.
5769 if (LHS.getValueType() != RHS.getValueType())
5770 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5772 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5773 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5774 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5775 DAG.getConstant(Cond, MVT::i8), BT);
5781 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5782 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5783 SDValue Op0 = Op.getOperand(0);
5784 SDValue Op1 = Op.getOperand(1);
5785 DebugLoc dl = Op.getDebugLoc();
5786 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5788 // Optimize to BT if possible.
5789 // Lower (X & (1 << N)) == 0 to BT(X, N).
5790 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5791 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5792 if (Op0.getOpcode() == ISD::AND &&
5794 Op1.getOpcode() == ISD::Constant &&
5795 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5796 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5797 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
5798 if (NewSetCC.getNode())
5802 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5803 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5804 if (X86CC == X86::COND_INVALID)
5807 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5809 // Use sbb x, x to materialize carry bit into a GPR.
5810 if (X86CC == X86::COND_B)
5811 return DAG.getNode(ISD::AND, dl, MVT::i8,
5812 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
5813 DAG.getConstant(X86CC, MVT::i8), Cond),
5814 DAG.getConstant(1, MVT::i8));
5816 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5817 DAG.getConstant(X86CC, MVT::i8), Cond);
5820 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5822 SDValue Op0 = Op.getOperand(0);
5823 SDValue Op1 = Op.getOperand(1);
5824 SDValue CC = Op.getOperand(2);
5825 EVT VT = Op.getValueType();
5826 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5827 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5828 DebugLoc dl = Op.getDebugLoc();
5832 EVT VT0 = Op0.getValueType();
5833 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5834 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5837 switch (SetCCOpcode) {
5840 case ISD::SETEQ: SSECC = 0; break;
5842 case ISD::SETGT: Swap = true; // Fallthrough
5844 case ISD::SETOLT: SSECC = 1; break;
5846 case ISD::SETGE: Swap = true; // Fallthrough
5848 case ISD::SETOLE: SSECC = 2; break;
5849 case ISD::SETUO: SSECC = 3; break;
5851 case ISD::SETNE: SSECC = 4; break;
5852 case ISD::SETULE: Swap = true;
5853 case ISD::SETUGE: SSECC = 5; break;
5854 case ISD::SETULT: Swap = true;
5855 case ISD::SETUGT: SSECC = 6; break;
5856 case ISD::SETO: SSECC = 7; break;
5859 std::swap(Op0, Op1);
5861 // In the two special cases we can't handle, emit two comparisons.
5863 if (SetCCOpcode == ISD::SETUEQ) {
5865 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5866 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5867 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5869 else if (SetCCOpcode == ISD::SETONE) {
5871 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5872 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5873 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5875 llvm_unreachable("Illegal FP comparison");
5877 // Handle all other FP comparisons here.
5878 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5881 // We are handling one of the integer comparisons here. Since SSE only has
5882 // GT and EQ comparisons for integer, swapping operands and multiple
5883 // operations may be required for some comparisons.
5884 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5885 bool Swap = false, Invert = false, FlipSigns = false;
5887 switch (VT.getSimpleVT().SimpleTy) {
5890 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5892 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5894 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5895 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5898 switch (SetCCOpcode) {
5900 case ISD::SETNE: Invert = true;
5901 case ISD::SETEQ: Opc = EQOpc; break;
5902 case ISD::SETLT: Swap = true;
5903 case ISD::SETGT: Opc = GTOpc; break;
5904 case ISD::SETGE: Swap = true;
5905 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5906 case ISD::SETULT: Swap = true;
5907 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5908 case ISD::SETUGE: Swap = true;
5909 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5912 std::swap(Op0, Op1);
5914 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5915 // bits of the inputs before performing those operations.
5917 EVT EltVT = VT.getVectorElementType();
5918 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5920 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5921 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5923 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5924 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5927 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5929 // If the logical-not of the result is required, perform that now.
5931 Result = DAG.getNOT(dl, Result, VT);
5936 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5937 static bool isX86LogicalCmp(SDValue Op) {
5938 unsigned Opc = Op.getNode()->getOpcode();
5939 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5941 if (Op.getResNo() == 1 &&
5942 (Opc == X86ISD::ADD ||
5943 Opc == X86ISD::SUB ||
5944 Opc == X86ISD::SMUL ||
5945 Opc == X86ISD::UMUL ||
5946 Opc == X86ISD::INC ||
5947 Opc == X86ISD::DEC ||
5948 Opc == X86ISD::OR ||
5949 Opc == X86ISD::XOR ||
5950 Opc == X86ISD::AND))
5956 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5957 bool addTest = true;
5958 SDValue Cond = Op.getOperand(0);
5959 DebugLoc dl = Op.getDebugLoc();
5962 if (Cond.getOpcode() == ISD::SETCC) {
5963 SDValue NewCond = LowerSETCC(Cond, DAG);
5964 if (NewCond.getNode())
5968 // Look pass (and (setcc_carry (cmp ...)), 1).
5969 if (Cond.getOpcode() == ISD::AND &&
5970 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
5971 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
5972 if (C && C->getAPIntValue() == 1)
5973 Cond = Cond.getOperand(0);
5976 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5977 // setting operand in place of the X86ISD::SETCC.
5978 if (Cond.getOpcode() == X86ISD::SETCC ||
5979 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
5980 CC = Cond.getOperand(0);
5982 SDValue Cmp = Cond.getOperand(1);
5983 unsigned Opc = Cmp.getOpcode();
5984 EVT VT = Op.getValueType();
5986 bool IllegalFPCMov = false;
5987 if (VT.isFloatingPoint() && !VT.isVector() &&
5988 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5989 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5991 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5992 Opc == X86ISD::BT) { // FIXME
5999 // Look pass the truncate.
6000 if (Cond.getOpcode() == ISD::TRUNCATE)
6001 Cond = Cond.getOperand(0);
6003 // We know the result of AND is compared against zero. Try to match
6005 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6006 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6007 if (NewSetCC.getNode()) {
6008 CC = NewSetCC.getOperand(0);
6009 Cond = NewSetCC.getOperand(1);
6016 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6017 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6020 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6021 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6022 // condition is true.
6023 SDValue Ops[] = { Op.getOperand(2), Op.getOperand(1), CC, Cond };
6024 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6027 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6028 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6029 // from the AND / OR.
6030 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6031 Opc = Op.getOpcode();
6032 if (Opc != ISD::OR && Opc != ISD::AND)
6034 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6035 Op.getOperand(0).hasOneUse() &&
6036 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6037 Op.getOperand(1).hasOneUse());
6040 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6041 // 1 and that the SETCC node has a single use.
6042 static bool isXor1OfSetCC(SDValue Op) {
6043 if (Op.getOpcode() != ISD::XOR)
6045 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6046 if (N1C && N1C->getAPIntValue() == 1) {
6047 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6048 Op.getOperand(0).hasOneUse();
6053 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6054 bool addTest = true;
6055 SDValue Chain = Op.getOperand(0);
6056 SDValue Cond = Op.getOperand(1);
6057 SDValue Dest = Op.getOperand(2);
6058 DebugLoc dl = Op.getDebugLoc();
6061 if (Cond.getOpcode() == ISD::SETCC) {
6062 SDValue NewCond = LowerSETCC(Cond, DAG);
6063 if (NewCond.getNode())
6067 // FIXME: LowerXALUO doesn't handle these!!
6068 else if (Cond.getOpcode() == X86ISD::ADD ||
6069 Cond.getOpcode() == X86ISD::SUB ||
6070 Cond.getOpcode() == X86ISD::SMUL ||
6071 Cond.getOpcode() == X86ISD::UMUL)
6072 Cond = LowerXALUO(Cond, DAG);
6075 // Look pass (and (setcc_carry (cmp ...)), 1).
6076 if (Cond.getOpcode() == ISD::AND &&
6077 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6078 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6079 if (C && C->getAPIntValue() == 1)
6080 Cond = Cond.getOperand(0);
6083 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6084 // setting operand in place of the X86ISD::SETCC.
6085 if (Cond.getOpcode() == X86ISD::SETCC ||
6086 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6087 CC = Cond.getOperand(0);
6089 SDValue Cmp = Cond.getOperand(1);
6090 unsigned Opc = Cmp.getOpcode();
6091 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6092 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6096 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6100 // These can only come from an arithmetic instruction with overflow,
6101 // e.g. SADDO, UADDO.
6102 Cond = Cond.getNode()->getOperand(1);
6109 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6110 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6111 if (CondOpc == ISD::OR) {
6112 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6113 // two branches instead of an explicit OR instruction with a
6115 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6116 isX86LogicalCmp(Cmp)) {
6117 CC = Cond.getOperand(0).getOperand(0);
6118 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6119 Chain, Dest, CC, Cmp);
6120 CC = Cond.getOperand(1).getOperand(0);
6124 } else { // ISD::AND
6125 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6126 // two branches instead of an explicit AND instruction with a
6127 // separate test. However, we only do this if this block doesn't
6128 // have a fall-through edge, because this requires an explicit
6129 // jmp when the condition is false.
6130 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6131 isX86LogicalCmp(Cmp) &&
6132 Op.getNode()->hasOneUse()) {
6133 X86::CondCode CCode =
6134 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6135 CCode = X86::GetOppositeBranchCondition(CCode);
6136 CC = DAG.getConstant(CCode, MVT::i8);
6137 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6138 // Look for an unconditional branch following this conditional branch.
6139 // We need this because we need to reverse the successors in order
6140 // to implement FCMP_OEQ.
6141 if (User.getOpcode() == ISD::BR) {
6142 SDValue FalseBB = User.getOperand(1);
6144 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6145 assert(NewBR == User);
6148 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6149 Chain, Dest, CC, Cmp);
6150 X86::CondCode CCode =
6151 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6152 CCode = X86::GetOppositeBranchCondition(CCode);
6153 CC = DAG.getConstant(CCode, MVT::i8);
6159 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6160 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6161 // It should be transformed during dag combiner except when the condition
6162 // is set by a arithmetics with overflow node.
6163 X86::CondCode CCode =
6164 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6165 CCode = X86::GetOppositeBranchCondition(CCode);
6166 CC = DAG.getConstant(CCode, MVT::i8);
6167 Cond = Cond.getOperand(0).getOperand(1);
6173 // Look pass the truncate.
6174 if (Cond.getOpcode() == ISD::TRUNCATE)
6175 Cond = Cond.getOperand(0);
6177 // We know the result of AND is compared against zero. Try to match
6179 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6180 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6181 if (NewSetCC.getNode()) {
6182 CC = NewSetCC.getOperand(0);
6183 Cond = NewSetCC.getOperand(1);
6190 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6191 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6193 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6194 Chain, Dest, CC, Cond);
6198 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6199 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6200 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6201 // that the guard pages used by the OS virtual memory manager are allocated in
6202 // correct sequence.
6204 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6205 SelectionDAG &DAG) {
6206 assert(Subtarget->isTargetCygMing() &&
6207 "This should be used only on Cygwin/Mingw targets");
6208 DebugLoc dl = Op.getDebugLoc();
6211 SDValue Chain = Op.getOperand(0);
6212 SDValue Size = Op.getOperand(1);
6213 // FIXME: Ensure alignment here
6217 EVT IntPtr = getPointerTy();
6218 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6220 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
6222 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6223 Flag = Chain.getValue(1);
6225 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6226 SDValue Ops[] = { Chain,
6227 DAG.getTargetExternalSymbol("_alloca", IntPtr),
6228 DAG.getRegister(X86::EAX, IntPtr),
6229 DAG.getRegister(X86StackPtr, SPTy),
6231 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
6232 Flag = Chain.getValue(1);
6234 Chain = DAG.getCALLSEQ_END(Chain,
6235 DAG.getIntPtrConstant(0, true),
6236 DAG.getIntPtrConstant(0, true),
6239 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6241 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6242 return DAG.getMergeValues(Ops1, 2, dl);
6246 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6248 SDValue Dst, SDValue Src,
6249 SDValue Size, unsigned Align,
6251 uint64_t DstSVOff) {
6252 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6254 // If not DWORD aligned or size is more than the threshold, call the library.
6255 // The libc version is likely to be faster for these cases. It can use the
6256 // address value and run time information about the CPU.
6257 if ((Align & 3) != 0 ||
6259 ConstantSize->getZExtValue() >
6260 getSubtarget()->getMaxInlineSizeThreshold()) {
6261 SDValue InFlag(0, 0);
6263 // Check to see if there is a specialized entry-point for memory zeroing.
6264 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6266 if (const char *bzeroEntry = V &&
6267 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6268 EVT IntPtr = getPointerTy();
6269 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6270 TargetLowering::ArgListTy Args;
6271 TargetLowering::ArgListEntry Entry;
6273 Entry.Ty = IntPtrTy;
6274 Args.push_back(Entry);
6276 Args.push_back(Entry);
6277 std::pair<SDValue,SDValue> CallResult =
6278 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6279 false, false, false, false,
6280 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6281 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl,
6282 DAG.GetOrdering(Chain.getNode()));
6283 return CallResult.second;
6286 // Otherwise have the target-independent code call memset.
6290 uint64_t SizeVal = ConstantSize->getZExtValue();
6291 SDValue InFlag(0, 0);
6294 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6295 unsigned BytesLeft = 0;
6296 bool TwoRepStos = false;
6299 uint64_t Val = ValC->getZExtValue() & 255;
6301 // If the value is a constant, then we can potentially use larger sets.
6302 switch (Align & 3) {
6303 case 2: // WORD aligned
6306 Val = (Val << 8) | Val;
6308 case 0: // DWORD aligned
6311 Val = (Val << 8) | Val;
6312 Val = (Val << 16) | Val;
6313 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6316 Val = (Val << 32) | Val;
6319 default: // Byte aligned
6322 Count = DAG.getIntPtrConstant(SizeVal);
6326 if (AVT.bitsGT(MVT::i8)) {
6327 unsigned UBytes = AVT.getSizeInBits() / 8;
6328 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6329 BytesLeft = SizeVal % UBytes;
6332 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6334 InFlag = Chain.getValue(1);
6337 Count = DAG.getIntPtrConstant(SizeVal);
6338 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6339 InFlag = Chain.getValue(1);
6342 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6345 InFlag = Chain.getValue(1);
6346 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6349 InFlag = Chain.getValue(1);
6351 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6352 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6353 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6356 InFlag = Chain.getValue(1);
6358 EVT CVT = Count.getValueType();
6359 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6360 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6361 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6364 InFlag = Chain.getValue(1);
6365 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6366 SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6367 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6368 } else if (BytesLeft) {
6369 // Handle the last 1 - 7 bytes.
6370 unsigned Offset = SizeVal - BytesLeft;
6371 EVT AddrVT = Dst.getValueType();
6372 EVT SizeVT = Size.getValueType();
6374 Chain = DAG.getMemset(Chain, dl,
6375 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6376 DAG.getConstant(Offset, AddrVT)),
6378 DAG.getConstant(BytesLeft, SizeVT),
6379 Align, DstSV, DstSVOff + Offset);
6382 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6387 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6388 SDValue Chain, SDValue Dst, SDValue Src,
6389 SDValue Size, unsigned Align,
6391 const Value *DstSV, uint64_t DstSVOff,
6392 const Value *SrcSV, uint64_t SrcSVOff) {
6393 // This requires the copy size to be a constant, preferrably
6394 // within a subtarget-specific limit.
6395 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6398 uint64_t SizeVal = ConstantSize->getZExtValue();
6399 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6402 /// If not DWORD aligned, call the library.
6403 if ((Align & 3) != 0)
6408 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6411 unsigned UBytes = AVT.getSizeInBits() / 8;
6412 unsigned CountVal = SizeVal / UBytes;
6413 SDValue Count = DAG.getIntPtrConstant(CountVal);
6414 unsigned BytesLeft = SizeVal % UBytes;
6416 SDValue InFlag(0, 0);
6417 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6420 InFlag = Chain.getValue(1);
6421 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6424 InFlag = Chain.getValue(1);
6425 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6428 InFlag = Chain.getValue(1);
6430 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6431 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6432 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6433 array_lengthof(Ops));
6435 SmallVector<SDValue, 4> Results;
6436 Results.push_back(RepMovs);
6438 // Handle the last 1 - 7 bytes.
6439 unsigned Offset = SizeVal - BytesLeft;
6440 EVT DstVT = Dst.getValueType();
6441 EVT SrcVT = Src.getValueType();
6442 EVT SizeVT = Size.getValueType();
6443 Results.push_back(DAG.getMemcpy(Chain, dl,
6444 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6445 DAG.getConstant(Offset, DstVT)),
6446 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6447 DAG.getConstant(Offset, SrcVT)),
6448 DAG.getConstant(BytesLeft, SizeVT),
6449 Align, AlwaysInline,
6450 DstSV, DstSVOff + Offset,
6451 SrcSV, SrcSVOff + Offset));
6454 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6455 &Results[0], Results.size());
6458 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6459 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6460 DebugLoc dl = Op.getDebugLoc();
6462 if (!Subtarget->is64Bit()) {
6463 // vastart just stores the address of the VarArgsFrameIndex slot into the
6464 // memory location argument.
6465 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6466 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6470 // gp_offset (0 - 6 * 8)
6471 // fp_offset (48 - 48 + 8 * 16)
6472 // overflow_arg_area (point to parameters coming in memory).
6474 SmallVector<SDValue, 8> MemOps;
6475 SDValue FIN = Op.getOperand(1);
6477 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6478 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6480 MemOps.push_back(Store);
6483 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6484 FIN, DAG.getIntPtrConstant(4));
6485 Store = DAG.getStore(Op.getOperand(0), dl,
6486 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6488 MemOps.push_back(Store);
6490 // Store ptr to overflow_arg_area
6491 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6492 FIN, DAG.getIntPtrConstant(4));
6493 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6494 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6495 MemOps.push_back(Store);
6497 // Store ptr to reg_save_area.
6498 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6499 FIN, DAG.getIntPtrConstant(8));
6500 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6501 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6502 MemOps.push_back(Store);
6503 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6504 &MemOps[0], MemOps.size());
6507 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6508 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6509 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6510 SDValue Chain = Op.getOperand(0);
6511 SDValue SrcPtr = Op.getOperand(1);
6512 SDValue SrcSV = Op.getOperand(2);
6514 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6518 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6519 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6520 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6521 SDValue Chain = Op.getOperand(0);
6522 SDValue DstPtr = Op.getOperand(1);
6523 SDValue SrcPtr = Op.getOperand(2);
6524 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6525 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6526 DebugLoc dl = Op.getDebugLoc();
6528 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6529 DAG.getIntPtrConstant(24), 8, false,
6530 DstSV, 0, SrcSV, 0);
6534 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6535 DebugLoc dl = Op.getDebugLoc();
6536 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6538 default: return SDValue(); // Don't custom lower most intrinsics.
6539 // Comparison intrinsics.
6540 case Intrinsic::x86_sse_comieq_ss:
6541 case Intrinsic::x86_sse_comilt_ss:
6542 case Intrinsic::x86_sse_comile_ss:
6543 case Intrinsic::x86_sse_comigt_ss:
6544 case Intrinsic::x86_sse_comige_ss:
6545 case Intrinsic::x86_sse_comineq_ss:
6546 case Intrinsic::x86_sse_ucomieq_ss:
6547 case Intrinsic::x86_sse_ucomilt_ss:
6548 case Intrinsic::x86_sse_ucomile_ss:
6549 case Intrinsic::x86_sse_ucomigt_ss:
6550 case Intrinsic::x86_sse_ucomige_ss:
6551 case Intrinsic::x86_sse_ucomineq_ss:
6552 case Intrinsic::x86_sse2_comieq_sd:
6553 case Intrinsic::x86_sse2_comilt_sd:
6554 case Intrinsic::x86_sse2_comile_sd:
6555 case Intrinsic::x86_sse2_comigt_sd:
6556 case Intrinsic::x86_sse2_comige_sd:
6557 case Intrinsic::x86_sse2_comineq_sd:
6558 case Intrinsic::x86_sse2_ucomieq_sd:
6559 case Intrinsic::x86_sse2_ucomilt_sd:
6560 case Intrinsic::x86_sse2_ucomile_sd:
6561 case Intrinsic::x86_sse2_ucomigt_sd:
6562 case Intrinsic::x86_sse2_ucomige_sd:
6563 case Intrinsic::x86_sse2_ucomineq_sd: {
6565 ISD::CondCode CC = ISD::SETCC_INVALID;
6568 case Intrinsic::x86_sse_comieq_ss:
6569 case Intrinsic::x86_sse2_comieq_sd:
6573 case Intrinsic::x86_sse_comilt_ss:
6574 case Intrinsic::x86_sse2_comilt_sd:
6578 case Intrinsic::x86_sse_comile_ss:
6579 case Intrinsic::x86_sse2_comile_sd:
6583 case Intrinsic::x86_sse_comigt_ss:
6584 case Intrinsic::x86_sse2_comigt_sd:
6588 case Intrinsic::x86_sse_comige_ss:
6589 case Intrinsic::x86_sse2_comige_sd:
6593 case Intrinsic::x86_sse_comineq_ss:
6594 case Intrinsic::x86_sse2_comineq_sd:
6598 case Intrinsic::x86_sse_ucomieq_ss:
6599 case Intrinsic::x86_sse2_ucomieq_sd:
6600 Opc = X86ISD::UCOMI;
6603 case Intrinsic::x86_sse_ucomilt_ss:
6604 case Intrinsic::x86_sse2_ucomilt_sd:
6605 Opc = X86ISD::UCOMI;
6608 case Intrinsic::x86_sse_ucomile_ss:
6609 case Intrinsic::x86_sse2_ucomile_sd:
6610 Opc = X86ISD::UCOMI;
6613 case Intrinsic::x86_sse_ucomigt_ss:
6614 case Intrinsic::x86_sse2_ucomigt_sd:
6615 Opc = X86ISD::UCOMI;
6618 case Intrinsic::x86_sse_ucomige_ss:
6619 case Intrinsic::x86_sse2_ucomige_sd:
6620 Opc = X86ISD::UCOMI;
6623 case Intrinsic::x86_sse_ucomineq_ss:
6624 case Intrinsic::x86_sse2_ucomineq_sd:
6625 Opc = X86ISD::UCOMI;
6630 SDValue LHS = Op.getOperand(1);
6631 SDValue RHS = Op.getOperand(2);
6632 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6633 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6634 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6635 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6636 DAG.getConstant(X86CC, MVT::i8), Cond);
6637 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6639 // ptest intrinsics. The intrinsic these come from are designed to return
6640 // an integer value, not just an instruction so lower it to the ptest
6641 // pattern and a setcc for the result.
6642 case Intrinsic::x86_sse41_ptestz:
6643 case Intrinsic::x86_sse41_ptestc:
6644 case Intrinsic::x86_sse41_ptestnzc:{
6647 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6648 case Intrinsic::x86_sse41_ptestz:
6650 X86CC = X86::COND_E;
6652 case Intrinsic::x86_sse41_ptestc:
6654 X86CC = X86::COND_B;
6656 case Intrinsic::x86_sse41_ptestnzc:
6658 X86CC = X86::COND_A;
6662 SDValue LHS = Op.getOperand(1);
6663 SDValue RHS = Op.getOperand(2);
6664 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6665 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6666 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6667 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6670 // Fix vector shift instructions where the last operand is a non-immediate
6672 case Intrinsic::x86_sse2_pslli_w:
6673 case Intrinsic::x86_sse2_pslli_d:
6674 case Intrinsic::x86_sse2_pslli_q:
6675 case Intrinsic::x86_sse2_psrli_w:
6676 case Intrinsic::x86_sse2_psrli_d:
6677 case Intrinsic::x86_sse2_psrli_q:
6678 case Intrinsic::x86_sse2_psrai_w:
6679 case Intrinsic::x86_sse2_psrai_d:
6680 case Intrinsic::x86_mmx_pslli_w:
6681 case Intrinsic::x86_mmx_pslli_d:
6682 case Intrinsic::x86_mmx_pslli_q:
6683 case Intrinsic::x86_mmx_psrli_w:
6684 case Intrinsic::x86_mmx_psrli_d:
6685 case Intrinsic::x86_mmx_psrli_q:
6686 case Intrinsic::x86_mmx_psrai_w:
6687 case Intrinsic::x86_mmx_psrai_d: {
6688 SDValue ShAmt = Op.getOperand(2);
6689 if (isa<ConstantSDNode>(ShAmt))
6692 unsigned NewIntNo = 0;
6693 EVT ShAmtVT = MVT::v4i32;
6695 case Intrinsic::x86_sse2_pslli_w:
6696 NewIntNo = Intrinsic::x86_sse2_psll_w;
6698 case Intrinsic::x86_sse2_pslli_d:
6699 NewIntNo = Intrinsic::x86_sse2_psll_d;
6701 case Intrinsic::x86_sse2_pslli_q:
6702 NewIntNo = Intrinsic::x86_sse2_psll_q;
6704 case Intrinsic::x86_sse2_psrli_w:
6705 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6707 case Intrinsic::x86_sse2_psrli_d:
6708 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6710 case Intrinsic::x86_sse2_psrli_q:
6711 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6713 case Intrinsic::x86_sse2_psrai_w:
6714 NewIntNo = Intrinsic::x86_sse2_psra_w;
6716 case Intrinsic::x86_sse2_psrai_d:
6717 NewIntNo = Intrinsic::x86_sse2_psra_d;
6720 ShAmtVT = MVT::v2i32;
6722 case Intrinsic::x86_mmx_pslli_w:
6723 NewIntNo = Intrinsic::x86_mmx_psll_w;
6725 case Intrinsic::x86_mmx_pslli_d:
6726 NewIntNo = Intrinsic::x86_mmx_psll_d;
6728 case Intrinsic::x86_mmx_pslli_q:
6729 NewIntNo = Intrinsic::x86_mmx_psll_q;
6731 case Intrinsic::x86_mmx_psrli_w:
6732 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6734 case Intrinsic::x86_mmx_psrli_d:
6735 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6737 case Intrinsic::x86_mmx_psrli_q:
6738 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6740 case Intrinsic::x86_mmx_psrai_w:
6741 NewIntNo = Intrinsic::x86_mmx_psra_w;
6743 case Intrinsic::x86_mmx_psrai_d:
6744 NewIntNo = Intrinsic::x86_mmx_psra_d;
6746 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6752 // The vector shift intrinsics with scalars uses 32b shift amounts but
6753 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6757 ShOps[1] = DAG.getConstant(0, MVT::i32);
6758 if (ShAmtVT == MVT::v4i32) {
6759 ShOps[2] = DAG.getUNDEF(MVT::i32);
6760 ShOps[3] = DAG.getUNDEF(MVT::i32);
6761 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6763 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6766 EVT VT = Op.getValueType();
6767 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6768 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6769 DAG.getConstant(NewIntNo, MVT::i32),
6770 Op.getOperand(1), ShAmt);
6775 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6776 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6777 DebugLoc dl = Op.getDebugLoc();
6780 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6782 DAG.getConstant(TD->getPointerSize(),
6783 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6784 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6785 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6790 // Just load the return address.
6791 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6792 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6793 RetAddrFI, NULL, 0);
6796 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6797 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6798 MFI->setFrameAddressIsTaken(true);
6799 EVT VT = Op.getValueType();
6800 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6801 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6802 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6803 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6805 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6809 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6810 SelectionDAG &DAG) {
6811 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6814 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6816 MachineFunction &MF = DAG.getMachineFunction();
6817 SDValue Chain = Op.getOperand(0);
6818 SDValue Offset = Op.getOperand(1);
6819 SDValue Handler = Op.getOperand(2);
6820 DebugLoc dl = Op.getDebugLoc();
6822 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6824 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6826 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6827 DAG.getIntPtrConstant(-TD->getPointerSize()));
6828 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6829 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6830 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6831 MF.getRegInfo().addLiveOut(StoreAddrReg);
6833 return DAG.getNode(X86ISD::EH_RETURN, dl,
6835 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6838 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6839 SelectionDAG &DAG) {
6840 SDValue Root = Op.getOperand(0);
6841 SDValue Trmp = Op.getOperand(1); // trampoline
6842 SDValue FPtr = Op.getOperand(2); // nested function
6843 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6844 DebugLoc dl = Op.getDebugLoc();
6846 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6848 const X86InstrInfo *TII =
6849 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6851 if (Subtarget->is64Bit()) {
6852 SDValue OutChains[6];
6854 // Large code-model.
6856 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6857 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6859 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6860 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6862 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6864 // Load the pointer to the nested function into R11.
6865 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6866 SDValue Addr = Trmp;
6867 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6870 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6871 DAG.getConstant(2, MVT::i64));
6872 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6874 // Load the 'nest' parameter value into R10.
6875 // R10 is specified in X86CallingConv.td
6876 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6877 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6878 DAG.getConstant(10, MVT::i64));
6879 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6880 Addr, TrmpAddr, 10);
6882 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6883 DAG.getConstant(12, MVT::i64));
6884 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6886 // Jump to the nested function.
6887 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6888 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6889 DAG.getConstant(20, MVT::i64));
6890 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6891 Addr, TrmpAddr, 20);
6893 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6894 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6895 DAG.getConstant(22, MVT::i64));
6896 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6900 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6901 return DAG.getMergeValues(Ops, 2, dl);
6903 const Function *Func =
6904 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6905 CallingConv::ID CC = Func->getCallingConv();
6910 llvm_unreachable("Unsupported calling convention");
6911 case CallingConv::C:
6912 case CallingConv::X86_StdCall: {
6913 // Pass 'nest' parameter in ECX.
6914 // Must be kept in sync with X86CallingConv.td
6917 // Check that ECX wasn't needed by an 'inreg' parameter.
6918 const FunctionType *FTy = Func->getFunctionType();
6919 const AttrListPtr &Attrs = Func->getAttributes();
6921 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6922 unsigned InRegCount = 0;
6925 for (FunctionType::param_iterator I = FTy->param_begin(),
6926 E = FTy->param_end(); I != E; ++I, ++Idx)
6927 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6928 // FIXME: should only count parameters that are lowered to integers.
6929 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6931 if (InRegCount > 2) {
6932 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6937 case CallingConv::X86_FastCall:
6938 case CallingConv::Fast:
6939 // Pass 'nest' parameter in EAX.
6940 // Must be kept in sync with X86CallingConv.td
6945 SDValue OutChains[4];
6948 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6949 DAG.getConstant(10, MVT::i32));
6950 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6952 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6953 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6954 OutChains[0] = DAG.getStore(Root, dl,
6955 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6958 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6959 DAG.getConstant(1, MVT::i32));
6960 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6962 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6963 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6964 DAG.getConstant(5, MVT::i32));
6965 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6966 TrmpAddr, 5, false, 1);
6968 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6969 DAG.getConstant(6, MVT::i32));
6970 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6973 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6974 return DAG.getMergeValues(Ops, 2, dl);
6978 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6980 The rounding mode is in bits 11:10 of FPSR, and has the following
6987 FLT_ROUNDS, on the other hand, expects the following:
6994 To perform the conversion, we do:
6995 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6998 MachineFunction &MF = DAG.getMachineFunction();
6999 const TargetMachine &TM = MF.getTarget();
7000 const TargetFrameInfo &TFI = *TM.getFrameInfo();
7001 unsigned StackAlignment = TFI.getStackAlignment();
7002 EVT VT = Op.getValueType();
7003 DebugLoc dl = Op.getDebugLoc();
7005 // Save FP Control Word to stack slot
7006 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7007 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7009 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7010 DAG.getEntryNode(), StackSlot);
7012 // Load FP Control Word from stack slot
7013 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
7015 // Transform as necessary
7017 DAG.getNode(ISD::SRL, dl, MVT::i16,
7018 DAG.getNode(ISD::AND, dl, MVT::i16,
7019 CWD, DAG.getConstant(0x800, MVT::i16)),
7020 DAG.getConstant(11, MVT::i8));
7022 DAG.getNode(ISD::SRL, dl, MVT::i16,
7023 DAG.getNode(ISD::AND, dl, MVT::i16,
7024 CWD, DAG.getConstant(0x400, MVT::i16)),
7025 DAG.getConstant(9, MVT::i8));
7028 DAG.getNode(ISD::AND, dl, MVT::i16,
7029 DAG.getNode(ISD::ADD, dl, MVT::i16,
7030 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7031 DAG.getConstant(1, MVT::i16)),
7032 DAG.getConstant(3, MVT::i16));
7035 return DAG.getNode((VT.getSizeInBits() < 16 ?
7036 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7039 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7040 EVT VT = Op.getValueType();
7042 unsigned NumBits = VT.getSizeInBits();
7043 DebugLoc dl = Op.getDebugLoc();
7045 Op = Op.getOperand(0);
7046 if (VT == MVT::i8) {
7047 // Zero extend to i32 since there is not an i8 bsr.
7049 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7052 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7053 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7054 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7056 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7059 DAG.getConstant(NumBits+NumBits-1, OpVT),
7060 DAG.getConstant(X86::COND_E, MVT::i8),
7063 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7065 // Finally xor with NumBits-1.
7066 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7069 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7073 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7074 EVT VT = Op.getValueType();
7076 unsigned NumBits = VT.getSizeInBits();
7077 DebugLoc dl = Op.getDebugLoc();
7079 Op = Op.getOperand(0);
7080 if (VT == MVT::i8) {
7082 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7085 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7086 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7087 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7089 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7092 DAG.getConstant(NumBits, OpVT),
7093 DAG.getConstant(X86::COND_E, MVT::i8),
7096 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7099 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7103 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7104 EVT VT = Op.getValueType();
7105 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7106 DebugLoc dl = Op.getDebugLoc();
7108 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7109 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7110 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7111 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7112 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7114 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7115 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7116 // return AloBlo + AloBhi + AhiBlo;
7118 SDValue A = Op.getOperand(0);
7119 SDValue B = Op.getOperand(1);
7121 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7122 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7123 A, DAG.getConstant(32, MVT::i32));
7124 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7125 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7126 B, DAG.getConstant(32, MVT::i32));
7127 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7128 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7130 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7131 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7133 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7134 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7136 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7137 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7138 AloBhi, DAG.getConstant(32, MVT::i32));
7139 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7140 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7141 AhiBlo, DAG.getConstant(32, MVT::i32));
7142 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7143 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7148 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7149 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7150 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7151 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7152 // has only one use.
7153 SDNode *N = Op.getNode();
7154 SDValue LHS = N->getOperand(0);
7155 SDValue RHS = N->getOperand(1);
7156 unsigned BaseOp = 0;
7158 DebugLoc dl = Op.getDebugLoc();
7160 switch (Op.getOpcode()) {
7161 default: llvm_unreachable("Unknown ovf instruction!");
7163 // A subtract of one will be selected as a INC. Note that INC doesn't
7164 // set CF, so we can't do this for UADDO.
7165 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7166 if (C->getAPIntValue() == 1) {
7167 BaseOp = X86ISD::INC;
7171 BaseOp = X86ISD::ADD;
7175 BaseOp = X86ISD::ADD;
7179 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7180 // set CF, so we can't do this for USUBO.
7181 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7182 if (C->getAPIntValue() == 1) {
7183 BaseOp = X86ISD::DEC;
7187 BaseOp = X86ISD::SUB;
7191 BaseOp = X86ISD::SUB;
7195 BaseOp = X86ISD::SMUL;
7199 BaseOp = X86ISD::UMUL;
7204 // Also sets EFLAGS.
7205 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7206 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7209 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7210 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7212 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7216 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7217 EVT T = Op.getValueType();
7218 DebugLoc dl = Op.getDebugLoc();
7221 switch(T.getSimpleVT().SimpleTy) {
7223 assert(false && "Invalid value type!");
7224 case MVT::i8: Reg = X86::AL; size = 1; break;
7225 case MVT::i16: Reg = X86::AX; size = 2; break;
7226 case MVT::i32: Reg = X86::EAX; size = 4; break;
7228 assert(Subtarget->is64Bit() && "Node not type legal!");
7229 Reg = X86::RAX; size = 8;
7232 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7233 Op.getOperand(2), SDValue());
7234 SDValue Ops[] = { cpIn.getValue(0),
7237 DAG.getTargetConstant(size, MVT::i8),
7239 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7240 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7242 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7246 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7247 SelectionDAG &DAG) {
7248 assert(Subtarget->is64Bit() && "Result not type legalized?");
7249 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7250 SDValue TheChain = Op.getOperand(0);
7251 DebugLoc dl = Op.getDebugLoc();
7252 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7253 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7254 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7256 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7257 DAG.getConstant(32, MVT::i8));
7259 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7262 return DAG.getMergeValues(Ops, 2, dl);
7265 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7266 SDNode *Node = Op.getNode();
7267 DebugLoc dl = Node->getDebugLoc();
7268 EVT T = Node->getValueType(0);
7269 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7270 DAG.getConstant(0, T), Node->getOperand(2));
7271 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7272 cast<AtomicSDNode>(Node)->getMemoryVT(),
7273 Node->getOperand(0),
7274 Node->getOperand(1), negOp,
7275 cast<AtomicSDNode>(Node)->getSrcValue(),
7276 cast<AtomicSDNode>(Node)->getAlignment());
7279 /// LowerOperation - Provide custom lowering hooks for some operations.
7281 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7282 switch (Op.getOpcode()) {
7283 default: llvm_unreachable("Should not custom lower this!");
7284 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7285 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7286 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7287 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7288 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7289 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7290 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7291 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7292 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7293 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7294 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7295 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7296 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7297 case ISD::SHL_PARTS:
7298 case ISD::SRA_PARTS:
7299 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7300 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7301 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7302 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7303 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7304 case ISD::FABS: return LowerFABS(Op, DAG);
7305 case ISD::FNEG: return LowerFNEG(Op, DAG);
7306 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7307 case ISD::SETCC: return LowerSETCC(Op, DAG);
7308 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7309 case ISD::SELECT: return LowerSELECT(Op, DAG);
7310 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7311 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7312 case ISD::VASTART: return LowerVASTART(Op, DAG);
7313 case ISD::VAARG: return LowerVAARG(Op, DAG);
7314 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7315 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7316 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7317 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7318 case ISD::FRAME_TO_ARGS_OFFSET:
7319 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7320 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7321 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7322 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7323 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7324 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7325 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7326 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7332 case ISD::UMULO: return LowerXALUO(Op, DAG);
7333 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7337 void X86TargetLowering::
7338 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7339 SelectionDAG &DAG, unsigned NewOp) {
7340 EVT T = Node->getValueType(0);
7341 DebugLoc dl = Node->getDebugLoc();
7342 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7344 SDValue Chain = Node->getOperand(0);
7345 SDValue In1 = Node->getOperand(1);
7346 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7347 Node->getOperand(2), DAG.getIntPtrConstant(0));
7348 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7349 Node->getOperand(2), DAG.getIntPtrConstant(1));
7350 SDValue Ops[] = { Chain, In1, In2L, In2H };
7351 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7353 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7354 cast<MemSDNode>(Node)->getMemOperand());
7355 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7356 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7357 Results.push_back(Result.getValue(2));
7360 /// ReplaceNodeResults - Replace a node with an illegal result type
7361 /// with a new node built out of custom code.
7362 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7363 SmallVectorImpl<SDValue>&Results,
7364 SelectionDAG &DAG) {
7365 DebugLoc dl = N->getDebugLoc();
7366 switch (N->getOpcode()) {
7368 assert(false && "Do not know how to custom type legalize this operation!");
7370 case ISD::FP_TO_SINT: {
7371 std::pair<SDValue,SDValue> Vals =
7372 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7373 SDValue FIST = Vals.first, StackSlot = Vals.second;
7374 if (FIST.getNode() != 0) {
7375 EVT VT = N->getValueType(0);
7376 // Return a load from the stack slot.
7377 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7381 case ISD::READCYCLECOUNTER: {
7382 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7383 SDValue TheChain = N->getOperand(0);
7384 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7385 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7387 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7389 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7390 SDValue Ops[] = { eax, edx };
7391 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7392 Results.push_back(edx.getValue(1));
7399 EVT WidenVT = getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
7400 Results.push_back(DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements()));
7403 case ISD::ATOMIC_CMP_SWAP: {
7404 EVT T = N->getValueType(0);
7405 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7406 SDValue cpInL, cpInH;
7407 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7408 DAG.getConstant(0, MVT::i32));
7409 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7410 DAG.getConstant(1, MVT::i32));
7411 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7412 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7414 SDValue swapInL, swapInH;
7415 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7416 DAG.getConstant(0, MVT::i32));
7417 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7418 DAG.getConstant(1, MVT::i32));
7419 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7421 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7422 swapInL.getValue(1));
7423 SDValue Ops[] = { swapInH.getValue(0),
7425 swapInH.getValue(1) };
7426 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7427 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7428 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7429 MVT::i32, Result.getValue(1));
7430 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7431 MVT::i32, cpOutL.getValue(2));
7432 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7433 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7434 Results.push_back(cpOutH.getValue(1));
7437 case ISD::ATOMIC_LOAD_ADD:
7438 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7440 case ISD::ATOMIC_LOAD_AND:
7441 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7443 case ISD::ATOMIC_LOAD_NAND:
7444 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7446 case ISD::ATOMIC_LOAD_OR:
7447 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7449 case ISD::ATOMIC_LOAD_SUB:
7450 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7452 case ISD::ATOMIC_LOAD_XOR:
7453 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7455 case ISD::ATOMIC_SWAP:
7456 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7461 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7463 default: return NULL;
7464 case X86ISD::BSF: return "X86ISD::BSF";
7465 case X86ISD::BSR: return "X86ISD::BSR";
7466 case X86ISD::SHLD: return "X86ISD::SHLD";
7467 case X86ISD::SHRD: return "X86ISD::SHRD";
7468 case X86ISD::FAND: return "X86ISD::FAND";
7469 case X86ISD::FOR: return "X86ISD::FOR";
7470 case X86ISD::FXOR: return "X86ISD::FXOR";
7471 case X86ISD::FSRL: return "X86ISD::FSRL";
7472 case X86ISD::FILD: return "X86ISD::FILD";
7473 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7474 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7475 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7476 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7477 case X86ISD::FLD: return "X86ISD::FLD";
7478 case X86ISD::FST: return "X86ISD::FST";
7479 case X86ISD::CALL: return "X86ISD::CALL";
7480 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7481 case X86ISD::BT: return "X86ISD::BT";
7482 case X86ISD::CMP: return "X86ISD::CMP";
7483 case X86ISD::COMI: return "X86ISD::COMI";
7484 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7485 case X86ISD::SETCC: return "X86ISD::SETCC";
7486 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7487 case X86ISD::CMOV: return "X86ISD::CMOV";
7488 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7489 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7490 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7491 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7492 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7493 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7494 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7495 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7496 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7497 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7498 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7499 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7500 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7501 case X86ISD::FMAX: return "X86ISD::FMAX";
7502 case X86ISD::FMIN: return "X86ISD::FMIN";
7503 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7504 case X86ISD::FRCP: return "X86ISD::FRCP";
7505 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7506 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7507 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7508 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7509 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7510 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7511 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7512 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7513 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7514 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7515 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7516 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7517 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7518 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7519 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7520 case X86ISD::VSHL: return "X86ISD::VSHL";
7521 case X86ISD::VSRL: return "X86ISD::VSRL";
7522 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7523 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7524 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7525 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7526 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7527 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7528 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7529 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7530 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7531 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7532 case X86ISD::ADD: return "X86ISD::ADD";
7533 case X86ISD::SUB: return "X86ISD::SUB";
7534 case X86ISD::SMUL: return "X86ISD::SMUL";
7535 case X86ISD::UMUL: return "X86ISD::UMUL";
7536 case X86ISD::INC: return "X86ISD::INC";
7537 case X86ISD::DEC: return "X86ISD::DEC";
7538 case X86ISD::OR: return "X86ISD::OR";
7539 case X86ISD::XOR: return "X86ISD::XOR";
7540 case X86ISD::AND: return "X86ISD::AND";
7541 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7542 case X86ISD::PTEST: return "X86ISD::PTEST";
7543 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7547 // isLegalAddressingMode - Return true if the addressing mode represented
7548 // by AM is legal for this target, for a load/store of the specified type.
7549 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7550 const Type *Ty) const {
7551 // X86 supports extremely general addressing modes.
7552 CodeModel::Model M = getTargetMachine().getCodeModel();
7554 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7555 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7560 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7562 // If a reference to this global requires an extra load, we can't fold it.
7563 if (isGlobalStubReference(GVFlags))
7566 // If BaseGV requires a register for the PIC base, we cannot also have a
7567 // BaseReg specified.
7568 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7571 // If lower 4G is not available, then we must use rip-relative addressing.
7572 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7582 // These scales always work.
7587 // These scales are formed with basereg+scalereg. Only accept if there is
7592 default: // Other stuff never works.
7600 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7601 if (!Ty1->isInteger() || !Ty2->isInteger())
7603 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7604 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7605 if (NumBits1 <= NumBits2)
7607 return Subtarget->is64Bit() || NumBits1 < 64;
7610 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7611 if (!VT1.isInteger() || !VT2.isInteger())
7613 unsigned NumBits1 = VT1.getSizeInBits();
7614 unsigned NumBits2 = VT2.getSizeInBits();
7615 if (NumBits1 <= NumBits2)
7617 return Subtarget->is64Bit() || NumBits1 < 64;
7620 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7621 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7622 return Ty1->isInteger(32) && Ty2->isInteger(64) && Subtarget->is64Bit();
7625 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7626 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7627 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7630 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7631 // i16 instructions are longer (0x66 prefix) and potentially slower.
7632 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7635 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7636 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7637 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7638 /// are assumed to be legal.
7640 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7642 // Only do shuffles on 128-bit vector types for now.
7643 if (VT.getSizeInBits() == 64)
7646 // FIXME: pshufb, blends, shifts.
7647 return (VT.getVectorNumElements() == 2 ||
7648 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7649 isMOVLMask(M, VT) ||
7650 isSHUFPMask(M, VT) ||
7651 isPSHUFDMask(M, VT) ||
7652 isPSHUFHWMask(M, VT) ||
7653 isPSHUFLWMask(M, VT) ||
7654 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7655 isUNPCKLMask(M, VT) ||
7656 isUNPCKHMask(M, VT) ||
7657 isUNPCKL_v_undef_Mask(M, VT) ||
7658 isUNPCKH_v_undef_Mask(M, VT));
7662 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7664 unsigned NumElts = VT.getVectorNumElements();
7665 // FIXME: This collection of masks seems suspect.
7668 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7669 return (isMOVLMask(Mask, VT) ||
7670 isCommutedMOVLMask(Mask, VT, true) ||
7671 isSHUFPMask(Mask, VT) ||
7672 isCommutedSHUFPMask(Mask, VT));
7677 //===----------------------------------------------------------------------===//
7678 // X86 Scheduler Hooks
7679 //===----------------------------------------------------------------------===//
7681 // private utility function
7683 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7684 MachineBasicBlock *MBB,
7692 TargetRegisterClass *RC,
7693 bool invSrc) const {
7694 // For the atomic bitwise operator, we generate
7697 // ld t1 = [bitinstr.addr]
7698 // op t2 = t1, [bitinstr.val]
7700 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7702 // fallthrough -->nextMBB
7703 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7704 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7705 MachineFunction::iterator MBBIter = MBB;
7708 /// First build the CFG
7709 MachineFunction *F = MBB->getParent();
7710 MachineBasicBlock *thisMBB = MBB;
7711 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7712 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7713 F->insert(MBBIter, newMBB);
7714 F->insert(MBBIter, nextMBB);
7716 // Move all successors to thisMBB to nextMBB
7717 nextMBB->transferSuccessors(thisMBB);
7719 // Update thisMBB to fall through to newMBB
7720 thisMBB->addSuccessor(newMBB);
7722 // newMBB jumps to itself and fall through to nextMBB
7723 newMBB->addSuccessor(nextMBB);
7724 newMBB->addSuccessor(newMBB);
7726 // Insert instructions into newMBB based on incoming instruction
7727 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7728 "unexpected number of operands");
7729 DebugLoc dl = bInstr->getDebugLoc();
7730 MachineOperand& destOper = bInstr->getOperand(0);
7731 MachineOperand* argOpers[2 + X86AddrNumOperands];
7732 int numArgs = bInstr->getNumOperands() - 1;
7733 for (int i=0; i < numArgs; ++i)
7734 argOpers[i] = &bInstr->getOperand(i+1);
7736 // x86 address has 4 operands: base, index, scale, and displacement
7737 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7738 int valArgIndx = lastAddrIndx + 1;
7740 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7741 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7742 for (int i=0; i <= lastAddrIndx; ++i)
7743 (*MIB).addOperand(*argOpers[i]);
7745 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7747 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7752 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7753 assert((argOpers[valArgIndx]->isReg() ||
7754 argOpers[valArgIndx]->isImm()) &&
7756 if (argOpers[valArgIndx]->isReg())
7757 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7759 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7761 (*MIB).addOperand(*argOpers[valArgIndx]);
7763 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7766 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7767 for (int i=0; i <= lastAddrIndx; ++i)
7768 (*MIB).addOperand(*argOpers[i]);
7770 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7771 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7772 bInstr->memoperands_end());
7774 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7778 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7780 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7784 // private utility function: 64 bit atomics on 32 bit host.
7786 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7787 MachineBasicBlock *MBB,
7792 bool invSrc) const {
7793 // For the atomic bitwise operator, we generate
7794 // thisMBB (instructions are in pairs, except cmpxchg8b)
7795 // ld t1,t2 = [bitinstr.addr]
7797 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7798 // op t5, t6 <- out1, out2, [bitinstr.val]
7799 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7800 // mov ECX, EBX <- t5, t6
7801 // mov EAX, EDX <- t1, t2
7802 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7803 // mov t3, t4 <- EAX, EDX
7805 // result in out1, out2
7806 // fallthrough -->nextMBB
7808 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7809 const unsigned LoadOpc = X86::MOV32rm;
7810 const unsigned copyOpc = X86::MOV32rr;
7811 const unsigned NotOpc = X86::NOT32r;
7812 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7813 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7814 MachineFunction::iterator MBBIter = MBB;
7817 /// First build the CFG
7818 MachineFunction *F = MBB->getParent();
7819 MachineBasicBlock *thisMBB = MBB;
7820 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7821 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7822 F->insert(MBBIter, newMBB);
7823 F->insert(MBBIter, nextMBB);
7825 // Move all successors to thisMBB to nextMBB
7826 nextMBB->transferSuccessors(thisMBB);
7828 // Update thisMBB to fall through to newMBB
7829 thisMBB->addSuccessor(newMBB);
7831 // newMBB jumps to itself and fall through to nextMBB
7832 newMBB->addSuccessor(nextMBB);
7833 newMBB->addSuccessor(newMBB);
7835 DebugLoc dl = bInstr->getDebugLoc();
7836 // Insert instructions into newMBB based on incoming instruction
7837 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7838 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7839 "unexpected number of operands");
7840 MachineOperand& dest1Oper = bInstr->getOperand(0);
7841 MachineOperand& dest2Oper = bInstr->getOperand(1);
7842 MachineOperand* argOpers[2 + X86AddrNumOperands];
7843 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7844 argOpers[i] = &bInstr->getOperand(i+2);
7846 // x86 address has 5 operands: base, index, scale, displacement, and segment.
7847 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7849 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7850 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7851 for (int i=0; i <= lastAddrIndx; ++i)
7852 (*MIB).addOperand(*argOpers[i]);
7853 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7854 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7855 // add 4 to displacement.
7856 for (int i=0; i <= lastAddrIndx-2; ++i)
7857 (*MIB).addOperand(*argOpers[i]);
7858 MachineOperand newOp3 = *(argOpers[3]);
7860 newOp3.setImm(newOp3.getImm()+4);
7862 newOp3.setOffset(newOp3.getOffset()+4);
7863 (*MIB).addOperand(newOp3);
7864 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7866 // t3/4 are defined later, at the bottom of the loop
7867 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7868 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7869 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7870 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7871 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7872 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7874 // The subsequent operations should be using the destination registers of
7875 //the PHI instructions.
7877 t1 = F->getRegInfo().createVirtualRegister(RC);
7878 t2 = F->getRegInfo().createVirtualRegister(RC);
7879 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
7880 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
7882 t1 = dest1Oper.getReg();
7883 t2 = dest2Oper.getReg();
7886 int valArgIndx = lastAddrIndx + 1;
7887 assert((argOpers[valArgIndx]->isReg() ||
7888 argOpers[valArgIndx]->isImm()) &&
7890 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7891 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7892 if (argOpers[valArgIndx]->isReg())
7893 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7895 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7896 if (regOpcL != X86::MOV32rr)
7898 (*MIB).addOperand(*argOpers[valArgIndx]);
7899 assert(argOpers[valArgIndx + 1]->isReg() ==
7900 argOpers[valArgIndx]->isReg());
7901 assert(argOpers[valArgIndx + 1]->isImm() ==
7902 argOpers[valArgIndx]->isImm());
7903 if (argOpers[valArgIndx + 1]->isReg())
7904 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7906 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7907 if (regOpcH != X86::MOV32rr)
7909 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7911 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7913 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7916 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7918 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7921 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7922 for (int i=0; i <= lastAddrIndx; ++i)
7923 (*MIB).addOperand(*argOpers[i]);
7925 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7926 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7927 bInstr->memoperands_end());
7929 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7930 MIB.addReg(X86::EAX);
7931 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7932 MIB.addReg(X86::EDX);
7935 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7937 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7941 // private utility function
7943 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7944 MachineBasicBlock *MBB,
7945 unsigned cmovOpc) const {
7946 // For the atomic min/max operator, we generate
7949 // ld t1 = [min/max.addr]
7950 // mov t2 = [min/max.val]
7952 // cmov[cond] t2 = t1
7954 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7956 // fallthrough -->nextMBB
7958 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7959 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7960 MachineFunction::iterator MBBIter = MBB;
7963 /// First build the CFG
7964 MachineFunction *F = MBB->getParent();
7965 MachineBasicBlock *thisMBB = MBB;
7966 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7967 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7968 F->insert(MBBIter, newMBB);
7969 F->insert(MBBIter, nextMBB);
7971 // Move all successors of thisMBB to nextMBB
7972 nextMBB->transferSuccessors(thisMBB);
7974 // Update thisMBB to fall through to newMBB
7975 thisMBB->addSuccessor(newMBB);
7977 // newMBB jumps to newMBB and fall through to nextMBB
7978 newMBB->addSuccessor(nextMBB);
7979 newMBB->addSuccessor(newMBB);
7981 DebugLoc dl = mInstr->getDebugLoc();
7982 // Insert instructions into newMBB based on incoming instruction
7983 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7984 "unexpected number of operands");
7985 MachineOperand& destOper = mInstr->getOperand(0);
7986 MachineOperand* argOpers[2 + X86AddrNumOperands];
7987 int numArgs = mInstr->getNumOperands() - 1;
7988 for (int i=0; i < numArgs; ++i)
7989 argOpers[i] = &mInstr->getOperand(i+1);
7991 // x86 address has 4 operands: base, index, scale, and displacement
7992 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7993 int valArgIndx = lastAddrIndx + 1;
7995 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7996 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7997 for (int i=0; i <= lastAddrIndx; ++i)
7998 (*MIB).addOperand(*argOpers[i]);
8000 // We only support register and immediate values
8001 assert((argOpers[valArgIndx]->isReg() ||
8002 argOpers[valArgIndx]->isImm()) &&
8005 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8006 if (argOpers[valArgIndx]->isReg())
8007 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8009 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8010 (*MIB).addOperand(*argOpers[valArgIndx]);
8012 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8015 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8020 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8021 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8025 // Cmp and exchange if none has modified the memory location
8026 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8027 for (int i=0; i <= lastAddrIndx; ++i)
8028 (*MIB).addOperand(*argOpers[i]);
8030 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8031 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8032 mInstr->memoperands_end());
8034 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8035 MIB.addReg(X86::EAX);
8038 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
8040 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
8044 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8045 // all of this code can be replaced with that in the .td file.
8047 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8048 unsigned numArgs, bool memArg) const {
8050 MachineFunction *F = BB->getParent();
8051 DebugLoc dl = MI->getDebugLoc();
8052 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8056 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8058 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8060 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8062 for (unsigned i = 0; i < numArgs; ++i) {
8063 MachineOperand &Op = MI->getOperand(i+1);
8065 if (!(Op.isReg() && Op.isImplicit()))
8069 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8072 F->DeleteMachineInstr(MI);
8078 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8080 MachineBasicBlock *MBB) const {
8081 // Emit code to save XMM registers to the stack. The ABI says that the
8082 // number of registers to save is given in %al, so it's theoretically
8083 // possible to do an indirect jump trick to avoid saving all of them,
8084 // however this code takes a simpler approach and just executes all
8085 // of the stores if %al is non-zero. It's less code, and it's probably
8086 // easier on the hardware branch predictor, and stores aren't all that
8087 // expensive anyway.
8089 // Create the new basic blocks. One block contains all the XMM stores,
8090 // and one block is the final destination regardless of whether any
8091 // stores were performed.
8092 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8093 MachineFunction *F = MBB->getParent();
8094 MachineFunction::iterator MBBIter = MBB;
8096 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8097 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8098 F->insert(MBBIter, XMMSaveMBB);
8099 F->insert(MBBIter, EndMBB);
8102 // Move any original successors of MBB to the end block.
8103 EndMBB->transferSuccessors(MBB);
8104 // The original block will now fall through to the XMM save block.
8105 MBB->addSuccessor(XMMSaveMBB);
8106 // The XMMSaveMBB will fall through to the end block.
8107 XMMSaveMBB->addSuccessor(EndMBB);
8109 // Now add the instructions.
8110 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8111 DebugLoc DL = MI->getDebugLoc();
8113 unsigned CountReg = MI->getOperand(0).getReg();
8114 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8115 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8117 if (!Subtarget->isTargetWin64()) {
8118 // If %al is 0, branch around the XMM save block.
8119 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8120 BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
8121 MBB->addSuccessor(EndMBB);
8124 // In the XMM save block, save all the XMM argument registers.
8125 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8126 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8127 MachineMemOperand *MMO =
8128 F->getMachineMemOperand(
8129 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8130 MachineMemOperand::MOStore, Offset,
8131 /*Size=*/16, /*Align=*/16);
8132 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8133 .addFrameIndex(RegSaveFrameIndex)
8134 .addImm(/*Scale=*/1)
8135 .addReg(/*IndexReg=*/0)
8136 .addImm(/*Disp=*/Offset)
8137 .addReg(/*Segment=*/0)
8138 .addReg(MI->getOperand(i).getReg())
8139 .addMemOperand(MMO);
8142 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8148 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8149 MachineBasicBlock *BB,
8150 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8151 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8152 DebugLoc DL = MI->getDebugLoc();
8154 // To "insert" a SELECT_CC instruction, we actually have to insert the
8155 // diamond control-flow pattern. The incoming instruction knows the
8156 // destination vreg to set, the condition code register to branch on, the
8157 // true/false values to select between, and a branch opcode to use.
8158 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8159 MachineFunction::iterator It = BB;
8165 // cmpTY ccX, r1, r2
8167 // fallthrough --> copy0MBB
8168 MachineBasicBlock *thisMBB = BB;
8169 MachineFunction *F = BB->getParent();
8170 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8171 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8173 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8174 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8175 F->insert(It, copy0MBB);
8176 F->insert(It, sinkMBB);
8177 // Update machine-CFG edges by first adding all successors of the current
8178 // block to the new block which will contain the Phi node for the select.
8179 // Also inform sdisel of the edge changes.
8180 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8181 E = BB->succ_end(); I != E; ++I) {
8182 EM->insert(std::make_pair(*I, sinkMBB));
8183 sinkMBB->addSuccessor(*I);
8185 // Next, remove all successors of the current block, and add the true
8186 // and fallthrough blocks as its successors.
8187 while (!BB->succ_empty())
8188 BB->removeSuccessor(BB->succ_begin());
8189 // Add the true and fallthrough blocks as its successors.
8190 BB->addSuccessor(copy0MBB);
8191 BB->addSuccessor(sinkMBB);
8194 // %FalseValue = ...
8195 // # fallthrough to sinkMBB
8198 // Update machine-CFG edges
8199 BB->addSuccessor(sinkMBB);
8202 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8205 BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8206 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8207 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8209 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8215 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8216 MachineBasicBlock *BB,
8217 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8218 switch (MI->getOpcode()) {
8219 default: assert(false && "Unexpected instr type to insert");
8221 case X86::CMOV_V1I64:
8222 case X86::CMOV_FR32:
8223 case X86::CMOV_FR64:
8224 case X86::CMOV_V4F32:
8225 case X86::CMOV_V2F64:
8226 case X86::CMOV_V2I64:
8227 return EmitLoweredSelect(MI, BB, EM);
8229 case X86::FP32_TO_INT16_IN_MEM:
8230 case X86::FP32_TO_INT32_IN_MEM:
8231 case X86::FP32_TO_INT64_IN_MEM:
8232 case X86::FP64_TO_INT16_IN_MEM:
8233 case X86::FP64_TO_INT32_IN_MEM:
8234 case X86::FP64_TO_INT64_IN_MEM:
8235 case X86::FP80_TO_INT16_IN_MEM:
8236 case X86::FP80_TO_INT32_IN_MEM:
8237 case X86::FP80_TO_INT64_IN_MEM: {
8238 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8239 DebugLoc DL = MI->getDebugLoc();
8241 // Change the floating point control register to use "round towards zero"
8242 // mode when truncating to an integer value.
8243 MachineFunction *F = BB->getParent();
8244 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8245 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8247 // Load the old value of the high byte of the control word...
8249 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8250 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8253 // Set the high part to be round to zero...
8254 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8257 // Reload the modified control word now...
8258 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8260 // Restore the memory image of control word to original value
8261 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8264 // Get the X86 opcode to use.
8266 switch (MI->getOpcode()) {
8267 default: llvm_unreachable("illegal opcode!");
8268 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8269 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8270 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8271 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8272 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8273 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8274 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8275 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8276 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8280 MachineOperand &Op = MI->getOperand(0);
8282 AM.BaseType = X86AddressMode::RegBase;
8283 AM.Base.Reg = Op.getReg();
8285 AM.BaseType = X86AddressMode::FrameIndexBase;
8286 AM.Base.FrameIndex = Op.getIndex();
8288 Op = MI->getOperand(1);
8290 AM.Scale = Op.getImm();
8291 Op = MI->getOperand(2);
8293 AM.IndexReg = Op.getImm();
8294 Op = MI->getOperand(3);
8295 if (Op.isGlobal()) {
8296 AM.GV = Op.getGlobal();
8298 AM.Disp = Op.getImm();
8300 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8301 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8303 // Reload the original control word now.
8304 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8306 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8309 // String/text processing lowering.
8310 case X86::PCMPISTRM128REG:
8311 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8312 case X86::PCMPISTRM128MEM:
8313 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8314 case X86::PCMPESTRM128REG:
8315 return EmitPCMP(MI, BB, 5, false /* in mem */);
8316 case X86::PCMPESTRM128MEM:
8317 return EmitPCMP(MI, BB, 5, true /* in mem */);
8320 case X86::ATOMAND32:
8321 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8322 X86::AND32ri, X86::MOV32rm,
8323 X86::LCMPXCHG32, X86::MOV32rr,
8324 X86::NOT32r, X86::EAX,
8325 X86::GR32RegisterClass);
8327 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8328 X86::OR32ri, X86::MOV32rm,
8329 X86::LCMPXCHG32, X86::MOV32rr,
8330 X86::NOT32r, X86::EAX,
8331 X86::GR32RegisterClass);
8332 case X86::ATOMXOR32:
8333 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8334 X86::XOR32ri, X86::MOV32rm,
8335 X86::LCMPXCHG32, X86::MOV32rr,
8336 X86::NOT32r, X86::EAX,
8337 X86::GR32RegisterClass);
8338 case X86::ATOMNAND32:
8339 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8340 X86::AND32ri, X86::MOV32rm,
8341 X86::LCMPXCHG32, X86::MOV32rr,
8342 X86::NOT32r, X86::EAX,
8343 X86::GR32RegisterClass, true);
8344 case X86::ATOMMIN32:
8345 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8346 case X86::ATOMMAX32:
8347 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8348 case X86::ATOMUMIN32:
8349 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8350 case X86::ATOMUMAX32:
8351 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8353 case X86::ATOMAND16:
8354 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8355 X86::AND16ri, X86::MOV16rm,
8356 X86::LCMPXCHG16, X86::MOV16rr,
8357 X86::NOT16r, X86::AX,
8358 X86::GR16RegisterClass);
8360 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8361 X86::OR16ri, X86::MOV16rm,
8362 X86::LCMPXCHG16, X86::MOV16rr,
8363 X86::NOT16r, X86::AX,
8364 X86::GR16RegisterClass);
8365 case X86::ATOMXOR16:
8366 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8367 X86::XOR16ri, X86::MOV16rm,
8368 X86::LCMPXCHG16, X86::MOV16rr,
8369 X86::NOT16r, X86::AX,
8370 X86::GR16RegisterClass);
8371 case X86::ATOMNAND16:
8372 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8373 X86::AND16ri, X86::MOV16rm,
8374 X86::LCMPXCHG16, X86::MOV16rr,
8375 X86::NOT16r, X86::AX,
8376 X86::GR16RegisterClass, true);
8377 case X86::ATOMMIN16:
8378 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8379 case X86::ATOMMAX16:
8380 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8381 case X86::ATOMUMIN16:
8382 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8383 case X86::ATOMUMAX16:
8384 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8387 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8388 X86::AND8ri, X86::MOV8rm,
8389 X86::LCMPXCHG8, X86::MOV8rr,
8390 X86::NOT8r, X86::AL,
8391 X86::GR8RegisterClass);
8393 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8394 X86::OR8ri, X86::MOV8rm,
8395 X86::LCMPXCHG8, X86::MOV8rr,
8396 X86::NOT8r, X86::AL,
8397 X86::GR8RegisterClass);
8399 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8400 X86::XOR8ri, X86::MOV8rm,
8401 X86::LCMPXCHG8, X86::MOV8rr,
8402 X86::NOT8r, X86::AL,
8403 X86::GR8RegisterClass);
8404 case X86::ATOMNAND8:
8405 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8406 X86::AND8ri, X86::MOV8rm,
8407 X86::LCMPXCHG8, X86::MOV8rr,
8408 X86::NOT8r, X86::AL,
8409 X86::GR8RegisterClass, true);
8410 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8411 // This group is for 64-bit host.
8412 case X86::ATOMAND64:
8413 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8414 X86::AND64ri32, X86::MOV64rm,
8415 X86::LCMPXCHG64, X86::MOV64rr,
8416 X86::NOT64r, X86::RAX,
8417 X86::GR64RegisterClass);
8419 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8420 X86::OR64ri32, X86::MOV64rm,
8421 X86::LCMPXCHG64, X86::MOV64rr,
8422 X86::NOT64r, X86::RAX,
8423 X86::GR64RegisterClass);
8424 case X86::ATOMXOR64:
8425 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8426 X86::XOR64ri32, X86::MOV64rm,
8427 X86::LCMPXCHG64, X86::MOV64rr,
8428 X86::NOT64r, X86::RAX,
8429 X86::GR64RegisterClass);
8430 case X86::ATOMNAND64:
8431 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8432 X86::AND64ri32, X86::MOV64rm,
8433 X86::LCMPXCHG64, X86::MOV64rr,
8434 X86::NOT64r, X86::RAX,
8435 X86::GR64RegisterClass, true);
8436 case X86::ATOMMIN64:
8437 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8438 case X86::ATOMMAX64:
8439 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8440 case X86::ATOMUMIN64:
8441 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8442 case X86::ATOMUMAX64:
8443 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8445 // This group does 64-bit operations on a 32-bit host.
8446 case X86::ATOMAND6432:
8447 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8448 X86::AND32rr, X86::AND32rr,
8449 X86::AND32ri, X86::AND32ri,
8451 case X86::ATOMOR6432:
8452 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8453 X86::OR32rr, X86::OR32rr,
8454 X86::OR32ri, X86::OR32ri,
8456 case X86::ATOMXOR6432:
8457 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8458 X86::XOR32rr, X86::XOR32rr,
8459 X86::XOR32ri, X86::XOR32ri,
8461 case X86::ATOMNAND6432:
8462 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8463 X86::AND32rr, X86::AND32rr,
8464 X86::AND32ri, X86::AND32ri,
8466 case X86::ATOMADD6432:
8467 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8468 X86::ADD32rr, X86::ADC32rr,
8469 X86::ADD32ri, X86::ADC32ri,
8471 case X86::ATOMSUB6432:
8472 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8473 X86::SUB32rr, X86::SBB32rr,
8474 X86::SUB32ri, X86::SBB32ri,
8476 case X86::ATOMSWAP6432:
8477 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8478 X86::MOV32rr, X86::MOV32rr,
8479 X86::MOV32ri, X86::MOV32ri,
8481 case X86::VASTART_SAVE_XMM_REGS:
8482 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8486 //===----------------------------------------------------------------------===//
8487 // X86 Optimization Hooks
8488 //===----------------------------------------------------------------------===//
8490 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8494 const SelectionDAG &DAG,
8495 unsigned Depth) const {
8496 unsigned Opc = Op.getOpcode();
8497 assert((Opc >= ISD::BUILTIN_OP_END ||
8498 Opc == ISD::INTRINSIC_WO_CHAIN ||
8499 Opc == ISD::INTRINSIC_W_CHAIN ||
8500 Opc == ISD::INTRINSIC_VOID) &&
8501 "Should use MaskedValueIsZero if you don't know whether Op"
8502 " is a target node!");
8504 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8516 // These nodes' second result is a boolean.
8517 if (Op.getResNo() == 0)
8521 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8522 Mask.getBitWidth() - 1);
8527 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8528 /// node is a GlobalAddress + offset.
8529 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8530 GlobalValue* &GA, int64_t &Offset) const{
8531 if (N->getOpcode() == X86ISD::Wrapper) {
8532 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8533 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8534 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8538 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8541 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8542 EVT EltVT, LoadSDNode *&LDBase,
8543 unsigned &LastLoadedElt,
8544 SelectionDAG &DAG, MachineFrameInfo *MFI,
8545 const TargetLowering &TLI) {
8547 LastLoadedElt = -1U;
8548 for (unsigned i = 0; i < NumElems; ++i) {
8549 if (N->getMaskElt(i) < 0) {
8555 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8556 if (!Elt.getNode() ||
8557 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8560 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8562 LDBase = cast<LoadSDNode>(Elt.getNode());
8566 if (Elt.getOpcode() == ISD::UNDEF)
8569 LoadSDNode *LD = cast<LoadSDNode>(Elt);
8570 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
8577 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8578 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8579 /// if the load addresses are consecutive, non-overlapping, and in the right
8580 /// order. In the case of v2i64, it will see if it can rewrite the
8581 /// shuffle to be an appropriate build vector so it can take advantage of
8582 // performBuildVectorCombine.
8583 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8584 const TargetLowering &TLI) {
8585 DebugLoc dl = N->getDebugLoc();
8586 EVT VT = N->getValueType(0);
8587 EVT EltVT = VT.getVectorElementType();
8588 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8589 unsigned NumElems = VT.getVectorNumElements();
8591 if (VT.getSizeInBits() != 128)
8594 // Try to combine a vector_shuffle into a 128-bit load.
8595 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8596 LoadSDNode *LD = NULL;
8597 unsigned LastLoadedElt;
8598 if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8602 if (LastLoadedElt == NumElems - 1) {
8603 if (DAG.InferPtrAlignment(LD->getBasePtr()) >= 16)
8604 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8605 LD->getSrcValue(), LD->getSrcValueOffset(),
8607 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8608 LD->getSrcValue(), LD->getSrcValueOffset(),
8609 LD->isVolatile(), LD->getAlignment());
8610 } else if (NumElems == 4 && LastLoadedElt == 1) {
8611 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8612 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8613 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8614 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8619 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8620 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8621 const X86Subtarget *Subtarget) {
8622 DebugLoc DL = N->getDebugLoc();
8623 SDValue Cond = N->getOperand(0);
8624 // Get the LHS/RHS of the select.
8625 SDValue LHS = N->getOperand(1);
8626 SDValue RHS = N->getOperand(2);
8628 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8629 // instructions have the peculiarity that if either operand is a NaN,
8630 // they chose what we call the RHS operand (and as such are not symmetric).
8631 // It happens that this matches the semantics of the common C idiom
8632 // x<y?x:y and related forms, so we can recognize these cases.
8633 if (Subtarget->hasSSE2() &&
8634 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8635 Cond.getOpcode() == ISD::SETCC) {
8636 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8638 unsigned Opcode = 0;
8639 // Check for x CC y ? x : y.
8640 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8644 // This can be a min if we can prove that at least one of the operands
8646 if (!FiniteOnlyFPMath()) {
8647 if (DAG.isKnownNeverNaN(RHS)) {
8648 // Put the potential NaN in the RHS so that SSE will preserve it.
8649 std::swap(LHS, RHS);
8650 } else if (!DAG.isKnownNeverNaN(LHS))
8653 Opcode = X86ISD::FMIN;
8656 // This can be a min if we can prove that at least one of the operands
8658 if (!FiniteOnlyFPMath()) {
8659 if (DAG.isKnownNeverNaN(LHS)) {
8660 // Put the potential NaN in the RHS so that SSE will preserve it.
8661 std::swap(LHS, RHS);
8662 } else if (!DAG.isKnownNeverNaN(RHS))
8665 Opcode = X86ISD::FMIN;
8668 // This can be a min, but if either operand is a NaN we need it to
8669 // preserve the original LHS.
8670 std::swap(LHS, RHS);
8674 Opcode = X86ISD::FMIN;
8678 // This can be a max if we can prove that at least one of the operands
8680 if (!FiniteOnlyFPMath()) {
8681 if (DAG.isKnownNeverNaN(LHS)) {
8682 // Put the potential NaN in the RHS so that SSE will preserve it.
8683 std::swap(LHS, RHS);
8684 } else if (!DAG.isKnownNeverNaN(RHS))
8687 Opcode = X86ISD::FMAX;
8690 // This can be a max if we can prove that at least one of the operands
8692 if (!FiniteOnlyFPMath()) {
8693 if (DAG.isKnownNeverNaN(RHS)) {
8694 // Put the potential NaN in the RHS so that SSE will preserve it.
8695 std::swap(LHS, RHS);
8696 } else if (!DAG.isKnownNeverNaN(LHS))
8699 Opcode = X86ISD::FMAX;
8702 // This can be a max, but if either operand is a NaN we need it to
8703 // preserve the original LHS.
8704 std::swap(LHS, RHS);
8708 Opcode = X86ISD::FMAX;
8711 // Check for x CC y ? y : x -- a min/max with reversed arms.
8712 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8716 // This can be a min if we can prove that at least one of the operands
8718 if (!FiniteOnlyFPMath()) {
8719 if (DAG.isKnownNeverNaN(RHS)) {
8720 // Put the potential NaN in the RHS so that SSE will preserve it.
8721 std::swap(LHS, RHS);
8722 } else if (!DAG.isKnownNeverNaN(LHS))
8725 Opcode = X86ISD::FMIN;
8728 // This can be a min if we can prove that at least one of the operands
8730 if (!FiniteOnlyFPMath()) {
8731 if (DAG.isKnownNeverNaN(LHS)) {
8732 // Put the potential NaN in the RHS so that SSE will preserve it.
8733 std::swap(LHS, RHS);
8734 } else if (!DAG.isKnownNeverNaN(RHS))
8737 Opcode = X86ISD::FMIN;
8740 // This can be a min, but if either operand is a NaN we need it to
8741 // preserve the original LHS.
8742 std::swap(LHS, RHS);
8746 Opcode = X86ISD::FMIN;
8750 // This can be a max if we can prove that at least one of the operands
8752 if (!FiniteOnlyFPMath()) {
8753 if (DAG.isKnownNeverNaN(LHS)) {
8754 // Put the potential NaN in the RHS so that SSE will preserve it.
8755 std::swap(LHS, RHS);
8756 } else if (!DAG.isKnownNeverNaN(RHS))
8759 Opcode = X86ISD::FMAX;
8762 // This can be a max if we can prove that at least one of the operands
8764 if (!FiniteOnlyFPMath()) {
8765 if (DAG.isKnownNeverNaN(RHS)) {
8766 // Put the potential NaN in the RHS so that SSE will preserve it.
8767 std::swap(LHS, RHS);
8768 } else if (!DAG.isKnownNeverNaN(LHS))
8771 Opcode = X86ISD::FMAX;
8774 // This can be a max, but if either operand is a NaN we need it to
8775 // preserve the original LHS.
8776 std::swap(LHS, RHS);
8780 Opcode = X86ISD::FMAX;
8786 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8789 // If this is a select between two integer constants, try to do some
8791 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8792 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8793 // Don't do this for crazy integer types.
8794 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8795 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8796 // so that TrueC (the true value) is larger than FalseC.
8797 bool NeedsCondInvert = false;
8799 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8800 // Efficiently invertible.
8801 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8802 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8803 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8804 NeedsCondInvert = true;
8805 std::swap(TrueC, FalseC);
8808 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8809 if (FalseC->getAPIntValue() == 0 &&
8810 TrueC->getAPIntValue().isPowerOf2()) {
8811 if (NeedsCondInvert) // Invert the condition if needed.
8812 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8813 DAG.getConstant(1, Cond.getValueType()));
8815 // Zero extend the condition if needed.
8816 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8818 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8819 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8820 DAG.getConstant(ShAmt, MVT::i8));
8823 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8824 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8825 if (NeedsCondInvert) // Invert the condition if needed.
8826 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8827 DAG.getConstant(1, Cond.getValueType()));
8829 // Zero extend the condition if needed.
8830 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8831 FalseC->getValueType(0), Cond);
8832 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8833 SDValue(FalseC, 0));
8836 // Optimize cases that will turn into an LEA instruction. This requires
8837 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8838 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8839 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8840 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8842 bool isFastMultiplier = false;
8844 switch ((unsigned char)Diff) {
8846 case 1: // result = add base, cond
8847 case 2: // result = lea base( , cond*2)
8848 case 3: // result = lea base(cond, cond*2)
8849 case 4: // result = lea base( , cond*4)
8850 case 5: // result = lea base(cond, cond*4)
8851 case 8: // result = lea base( , cond*8)
8852 case 9: // result = lea base(cond, cond*8)
8853 isFastMultiplier = true;
8858 if (isFastMultiplier) {
8859 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8860 if (NeedsCondInvert) // Invert the condition if needed.
8861 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8862 DAG.getConstant(1, Cond.getValueType()));
8864 // Zero extend the condition if needed.
8865 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8867 // Scale the condition by the difference.
8869 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8870 DAG.getConstant(Diff, Cond.getValueType()));
8872 // Add the base if non-zero.
8873 if (FalseC->getAPIntValue() != 0)
8874 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8875 SDValue(FalseC, 0));
8885 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8886 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8887 TargetLowering::DAGCombinerInfo &DCI) {
8888 DebugLoc DL = N->getDebugLoc();
8890 // If the flag operand isn't dead, don't touch this CMOV.
8891 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8894 // If this is a select between two integer constants, try to do some
8895 // optimizations. Note that the operands are ordered the opposite of SELECT
8897 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8898 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8899 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8900 // larger than FalseC (the false value).
8901 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8903 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8904 CC = X86::GetOppositeBranchCondition(CC);
8905 std::swap(TrueC, FalseC);
8908 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8909 // This is efficient for any integer data type (including i8/i16) and
8911 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8912 SDValue Cond = N->getOperand(3);
8913 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8914 DAG.getConstant(CC, MVT::i8), Cond);
8916 // Zero extend the condition if needed.
8917 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8919 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8920 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8921 DAG.getConstant(ShAmt, MVT::i8));
8922 if (N->getNumValues() == 2) // Dead flag value?
8923 return DCI.CombineTo(N, Cond, SDValue());
8927 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8928 // for any integer data type, including i8/i16.
8929 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8930 SDValue Cond = N->getOperand(3);
8931 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8932 DAG.getConstant(CC, MVT::i8), Cond);
8934 // Zero extend the condition if needed.
8935 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8936 FalseC->getValueType(0), Cond);
8937 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8938 SDValue(FalseC, 0));
8940 if (N->getNumValues() == 2) // Dead flag value?
8941 return DCI.CombineTo(N, Cond, SDValue());
8945 // Optimize cases that will turn into an LEA instruction. This requires
8946 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8947 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8948 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8949 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8951 bool isFastMultiplier = false;
8953 switch ((unsigned char)Diff) {
8955 case 1: // result = add base, cond
8956 case 2: // result = lea base( , cond*2)
8957 case 3: // result = lea base(cond, cond*2)
8958 case 4: // result = lea base( , cond*4)
8959 case 5: // result = lea base(cond, cond*4)
8960 case 8: // result = lea base( , cond*8)
8961 case 9: // result = lea base(cond, cond*8)
8962 isFastMultiplier = true;
8967 if (isFastMultiplier) {
8968 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8969 SDValue Cond = N->getOperand(3);
8970 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8971 DAG.getConstant(CC, MVT::i8), Cond);
8972 // Zero extend the condition if needed.
8973 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8975 // Scale the condition by the difference.
8977 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8978 DAG.getConstant(Diff, Cond.getValueType()));
8980 // Add the base if non-zero.
8981 if (FalseC->getAPIntValue() != 0)
8982 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8983 SDValue(FalseC, 0));
8984 if (N->getNumValues() == 2) // Dead flag value?
8985 return DCI.CombineTo(N, Cond, SDValue());
8995 /// PerformMulCombine - Optimize a single multiply with constant into two
8996 /// in order to implement it with two cheaper instructions, e.g.
8997 /// LEA + SHL, LEA + LEA.
8998 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8999 TargetLowering::DAGCombinerInfo &DCI) {
9000 if (DAG.getMachineFunction().
9001 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
9004 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9007 EVT VT = N->getValueType(0);
9011 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9014 uint64_t MulAmt = C->getZExtValue();
9015 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9018 uint64_t MulAmt1 = 0;
9019 uint64_t MulAmt2 = 0;
9020 if ((MulAmt % 9) == 0) {
9022 MulAmt2 = MulAmt / 9;
9023 } else if ((MulAmt % 5) == 0) {
9025 MulAmt2 = MulAmt / 5;
9026 } else if ((MulAmt % 3) == 0) {
9028 MulAmt2 = MulAmt / 3;
9031 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9032 DebugLoc DL = N->getDebugLoc();
9034 if (isPowerOf2_64(MulAmt2) &&
9035 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9036 // If second multiplifer is pow2, issue it first. We want the multiply by
9037 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9039 std::swap(MulAmt1, MulAmt2);
9042 if (isPowerOf2_64(MulAmt1))
9043 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9044 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9046 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9047 DAG.getConstant(MulAmt1, VT));
9049 if (isPowerOf2_64(MulAmt2))
9050 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9051 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9053 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9054 DAG.getConstant(MulAmt2, VT));
9056 // Do not add new nodes to DAG combiner worklist.
9057 DCI.CombineTo(N, NewMul, false);
9062 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9063 SDValue N0 = N->getOperand(0);
9064 SDValue N1 = N->getOperand(1);
9065 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9066 EVT VT = N0.getValueType();
9068 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9069 // since the result of setcc_c is all zero's or all ones.
9070 if (N1C && N0.getOpcode() == ISD::AND &&
9071 N0.getOperand(1).getOpcode() == ISD::Constant) {
9072 SDValue N00 = N0.getOperand(0);
9073 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9074 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9075 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9076 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9077 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9078 APInt ShAmt = N1C->getAPIntValue();
9079 Mask = Mask.shl(ShAmt);
9081 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9082 N00, DAG.getConstant(Mask, VT));
9089 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9091 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9092 const X86Subtarget *Subtarget) {
9093 EVT VT = N->getValueType(0);
9094 if (!VT.isVector() && VT.isInteger() &&
9095 N->getOpcode() == ISD::SHL)
9096 return PerformSHLCombine(N, DAG);
9098 // On X86 with SSE2 support, we can transform this to a vector shift if
9099 // all elements are shifted by the same amount. We can't do this in legalize
9100 // because the a constant vector is typically transformed to a constant pool
9101 // so we have no knowledge of the shift amount.
9102 if (!Subtarget->hasSSE2())
9105 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9108 SDValue ShAmtOp = N->getOperand(1);
9109 EVT EltVT = VT.getVectorElementType();
9110 DebugLoc DL = N->getDebugLoc();
9111 SDValue BaseShAmt = SDValue();
9112 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9113 unsigned NumElts = VT.getVectorNumElements();
9115 for (; i != NumElts; ++i) {
9116 SDValue Arg = ShAmtOp.getOperand(i);
9117 if (Arg.getOpcode() == ISD::UNDEF) continue;
9121 for (; i != NumElts; ++i) {
9122 SDValue Arg = ShAmtOp.getOperand(i);
9123 if (Arg.getOpcode() == ISD::UNDEF) continue;
9124 if (Arg != BaseShAmt) {
9128 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9129 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9130 SDValue InVec = ShAmtOp.getOperand(0);
9131 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9132 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9134 for (; i != NumElts; ++i) {
9135 SDValue Arg = InVec.getOperand(i);
9136 if (Arg.getOpcode() == ISD::UNDEF) continue;
9140 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9141 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9142 unsigned SplatIdx = cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9143 if (C->getZExtValue() == SplatIdx)
9144 BaseShAmt = InVec.getOperand(1);
9147 if (BaseShAmt.getNode() == 0)
9148 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9149 DAG.getIntPtrConstant(0));
9153 // The shift amount is an i32.
9154 if (EltVT.bitsGT(MVT::i32))
9155 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9156 else if (EltVT.bitsLT(MVT::i32))
9157 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9159 // The shift amount is identical so we can do a vector shift.
9160 SDValue ValOp = N->getOperand(0);
9161 switch (N->getOpcode()) {
9163 llvm_unreachable("Unknown shift opcode!");
9166 if (VT == MVT::v2i64)
9167 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9168 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9170 if (VT == MVT::v4i32)
9171 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9172 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9174 if (VT == MVT::v8i16)
9175 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9176 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9180 if (VT == MVT::v4i32)
9181 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9182 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9184 if (VT == MVT::v8i16)
9185 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9186 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9190 if (VT == MVT::v2i64)
9191 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9192 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9194 if (VT == MVT::v4i32)
9195 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9196 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9198 if (VT == MVT::v8i16)
9199 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9200 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9207 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9208 const X86Subtarget *Subtarget) {
9209 EVT VT = N->getValueType(0);
9210 if (VT != MVT::i64 || !Subtarget->is64Bit())
9213 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9214 SDValue N0 = N->getOperand(0);
9215 SDValue N1 = N->getOperand(1);
9216 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9218 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9221 SDValue ShAmt0 = N0.getOperand(1);
9222 if (ShAmt0.getValueType() != MVT::i8)
9224 SDValue ShAmt1 = N1.getOperand(1);
9225 if (ShAmt1.getValueType() != MVT::i8)
9227 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9228 ShAmt0 = ShAmt0.getOperand(0);
9229 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9230 ShAmt1 = ShAmt1.getOperand(0);
9232 DebugLoc DL = N->getDebugLoc();
9233 unsigned Opc = X86ISD::SHLD;
9234 SDValue Op0 = N0.getOperand(0);
9235 SDValue Op1 = N1.getOperand(0);
9236 if (ShAmt0.getOpcode() == ISD::SUB) {
9238 std::swap(Op0, Op1);
9239 std::swap(ShAmt0, ShAmt1);
9242 if (ShAmt1.getOpcode() == ISD::SUB) {
9243 SDValue Sum = ShAmt1.getOperand(0);
9244 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9245 if (SumC->getSExtValue() == 64 &&
9246 ShAmt1.getOperand(1) == ShAmt0)
9247 return DAG.getNode(Opc, DL, VT,
9249 DAG.getNode(ISD::TRUNCATE, DL,
9252 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9253 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9255 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9256 return DAG.getNode(Opc, DL, VT,
9257 N0.getOperand(0), N1.getOperand(0),
9258 DAG.getNode(ISD::TRUNCATE, DL,
9265 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9266 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9267 const X86Subtarget *Subtarget) {
9268 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9269 // the FP state in cases where an emms may be missing.
9270 // A preferable solution to the general problem is to figure out the right
9271 // places to insert EMMS. This qualifies as a quick hack.
9273 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9274 StoreSDNode *St = cast<StoreSDNode>(N);
9275 EVT VT = St->getValue().getValueType();
9276 if (VT.getSizeInBits() != 64)
9279 const Function *F = DAG.getMachineFunction().getFunction();
9280 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9281 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9282 && Subtarget->hasSSE2();
9283 if ((VT.isVector() ||
9284 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9285 isa<LoadSDNode>(St->getValue()) &&
9286 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9287 St->getChain().hasOneUse() && !St->isVolatile()) {
9288 SDNode* LdVal = St->getValue().getNode();
9290 int TokenFactorIndex = -1;
9291 SmallVector<SDValue, 8> Ops;
9292 SDNode* ChainVal = St->getChain().getNode();
9293 // Must be a store of a load. We currently handle two cases: the load
9294 // is a direct child, and it's under an intervening TokenFactor. It is
9295 // possible to dig deeper under nested TokenFactors.
9296 if (ChainVal == LdVal)
9297 Ld = cast<LoadSDNode>(St->getChain());
9298 else if (St->getValue().hasOneUse() &&
9299 ChainVal->getOpcode() == ISD::TokenFactor) {
9300 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9301 if (ChainVal->getOperand(i).getNode() == LdVal) {
9302 TokenFactorIndex = i;
9303 Ld = cast<LoadSDNode>(St->getValue());
9305 Ops.push_back(ChainVal->getOperand(i));
9309 if (!Ld || !ISD::isNormalLoad(Ld))
9312 // If this is not the MMX case, i.e. we are just turning i64 load/store
9313 // into f64 load/store, avoid the transformation if there are multiple
9314 // uses of the loaded value.
9315 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9318 DebugLoc LdDL = Ld->getDebugLoc();
9319 DebugLoc StDL = N->getDebugLoc();
9320 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9321 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9323 if (Subtarget->is64Bit() || F64IsLegal) {
9324 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9325 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9326 Ld->getBasePtr(), Ld->getSrcValue(),
9327 Ld->getSrcValueOffset(), Ld->isVolatile(),
9328 Ld->getAlignment());
9329 SDValue NewChain = NewLd.getValue(1);
9330 if (TokenFactorIndex != -1) {
9331 Ops.push_back(NewChain);
9332 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9335 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9336 St->getSrcValue(), St->getSrcValueOffset(),
9337 St->isVolatile(), St->getAlignment());
9340 // Otherwise, lower to two pairs of 32-bit loads / stores.
9341 SDValue LoAddr = Ld->getBasePtr();
9342 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9343 DAG.getConstant(4, MVT::i32));
9345 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9346 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9347 Ld->isVolatile(), Ld->getAlignment());
9348 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9349 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9351 MinAlign(Ld->getAlignment(), 4));
9353 SDValue NewChain = LoLd.getValue(1);
9354 if (TokenFactorIndex != -1) {
9355 Ops.push_back(LoLd);
9356 Ops.push_back(HiLd);
9357 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9361 LoAddr = St->getBasePtr();
9362 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9363 DAG.getConstant(4, MVT::i32));
9365 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9366 St->getSrcValue(), St->getSrcValueOffset(),
9367 St->isVolatile(), St->getAlignment());
9368 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9370 St->getSrcValueOffset() + 4,
9372 MinAlign(St->getAlignment(), 4));
9373 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9378 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9379 /// X86ISD::FXOR nodes.
9380 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9381 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9382 // F[X]OR(0.0, x) -> x
9383 // F[X]OR(x, 0.0) -> x
9384 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9385 if (C->getValueAPF().isPosZero())
9386 return N->getOperand(1);
9387 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9388 if (C->getValueAPF().isPosZero())
9389 return N->getOperand(0);
9393 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9394 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9395 // FAND(0.0, x) -> 0.0
9396 // FAND(x, 0.0) -> 0.0
9397 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9398 if (C->getValueAPF().isPosZero())
9399 return N->getOperand(0);
9400 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9401 if (C->getValueAPF().isPosZero())
9402 return N->getOperand(1);
9406 static SDValue PerformBTCombine(SDNode *N,
9408 TargetLowering::DAGCombinerInfo &DCI) {
9409 // BT ignores high bits in the bit index operand.
9410 SDValue Op1 = N->getOperand(1);
9411 if (Op1.hasOneUse()) {
9412 unsigned BitWidth = Op1.getValueSizeInBits();
9413 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9414 APInt KnownZero, KnownOne;
9415 TargetLowering::TargetLoweringOpt TLO(DAG);
9416 TargetLowering &TLI = DAG.getTargetLoweringInfo();
9417 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9418 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9419 DCI.CommitTargetLoweringOpt(TLO);
9424 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9425 SDValue Op = N->getOperand(0);
9426 if (Op.getOpcode() == ISD::BIT_CONVERT)
9427 Op = Op.getOperand(0);
9428 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9429 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9430 VT.getVectorElementType().getSizeInBits() ==
9431 OpVT.getVectorElementType().getSizeInBits()) {
9432 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9437 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9438 // Locked instructions, in turn, have implicit fence semantics (all memory
9439 // operations are flushed before issuing the locked instruction, and the
9440 // are not buffered), so we can fold away the common pattern of
9441 // fence-atomic-fence.
9442 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9443 SDValue atomic = N->getOperand(0);
9444 switch (atomic.getOpcode()) {
9445 case ISD::ATOMIC_CMP_SWAP:
9446 case ISD::ATOMIC_SWAP:
9447 case ISD::ATOMIC_LOAD_ADD:
9448 case ISD::ATOMIC_LOAD_SUB:
9449 case ISD::ATOMIC_LOAD_AND:
9450 case ISD::ATOMIC_LOAD_OR:
9451 case ISD::ATOMIC_LOAD_XOR:
9452 case ISD::ATOMIC_LOAD_NAND:
9453 case ISD::ATOMIC_LOAD_MIN:
9454 case ISD::ATOMIC_LOAD_MAX:
9455 case ISD::ATOMIC_LOAD_UMIN:
9456 case ISD::ATOMIC_LOAD_UMAX:
9462 SDValue fence = atomic.getOperand(0);
9463 if (fence.getOpcode() != ISD::MEMBARRIER)
9466 switch (atomic.getOpcode()) {
9467 case ISD::ATOMIC_CMP_SWAP:
9468 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9469 atomic.getOperand(1), atomic.getOperand(2),
9470 atomic.getOperand(3));
9471 case ISD::ATOMIC_SWAP:
9472 case ISD::ATOMIC_LOAD_ADD:
9473 case ISD::ATOMIC_LOAD_SUB:
9474 case ISD::ATOMIC_LOAD_AND:
9475 case ISD::ATOMIC_LOAD_OR:
9476 case ISD::ATOMIC_LOAD_XOR:
9477 case ISD::ATOMIC_LOAD_NAND:
9478 case ISD::ATOMIC_LOAD_MIN:
9479 case ISD::ATOMIC_LOAD_MAX:
9480 case ISD::ATOMIC_LOAD_UMIN:
9481 case ISD::ATOMIC_LOAD_UMAX:
9482 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9483 atomic.getOperand(1), atomic.getOperand(2));
9489 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9490 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
9491 // (and (i32 x86isd::setcc_carry), 1)
9492 // This eliminates the zext. This transformation is necessary because
9493 // ISD::SETCC is always legalized to i8.
9494 DebugLoc dl = N->getDebugLoc();
9495 SDValue N0 = N->getOperand(0);
9496 EVT VT = N->getValueType(0);
9497 if (N0.getOpcode() == ISD::AND &&
9499 N0.getOperand(0).hasOneUse()) {
9500 SDValue N00 = N0.getOperand(0);
9501 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9503 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9504 if (!C || C->getZExtValue() != 1)
9506 return DAG.getNode(ISD::AND, dl, VT,
9507 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9508 N00.getOperand(0), N00.getOperand(1)),
9509 DAG.getConstant(1, VT));
9515 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9516 DAGCombinerInfo &DCI) const {
9517 SelectionDAG &DAG = DCI.DAG;
9518 switch (N->getOpcode()) {
9520 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9521 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9522 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9523 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9526 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9527 case ISD::OR: return PerformOrCombine(N, DAG, Subtarget);
9528 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9530 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9531 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9532 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9533 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9534 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9535 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
9541 //===----------------------------------------------------------------------===//
9542 // X86 Inline Assembly Support
9543 //===----------------------------------------------------------------------===//
9545 static bool LowerToBSwap(CallInst *CI) {
9546 // FIXME: this should verify that we are targetting a 486 or better. If not,
9547 // we will turn this bswap into something that will be lowered to logical ops
9548 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9549 // so don't worry about this.
9551 // Verify this is a simple bswap.
9552 if (CI->getNumOperands() != 2 ||
9553 CI->getType() != CI->getOperand(1)->getType() ||
9554 !CI->getType()->isInteger())
9557 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9558 if (!Ty || Ty->getBitWidth() % 16 != 0)
9561 // Okay, we can do this xform, do so now.
9562 const Type *Tys[] = { Ty };
9563 Module *M = CI->getParent()->getParent()->getParent();
9564 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9566 Value *Op = CI->getOperand(1);
9567 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9569 CI->replaceAllUsesWith(Op);
9570 CI->eraseFromParent();
9574 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9575 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9576 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9578 std::string AsmStr = IA->getAsmString();
9580 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9581 SmallVector<StringRef, 4> AsmPieces;
9582 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9584 switch (AsmPieces.size()) {
9585 default: return false;
9587 AsmStr = AsmPieces[0];
9589 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9592 if (AsmPieces.size() == 2 &&
9593 (AsmPieces[0] == "bswap" ||
9594 AsmPieces[0] == "bswapq" ||
9595 AsmPieces[0] == "bswapl") &&
9596 (AsmPieces[1] == "$0" ||
9597 AsmPieces[1] == "${0:q}")) {
9598 // No need to check constraints, nothing other than the equivalent of
9599 // "=r,0" would be valid here.
9600 return LowerToBSwap(CI);
9602 // rorw $$8, ${0:w} --> llvm.bswap.i16
9603 if (CI->getType()->isInteger(16) &&
9604 AsmPieces.size() == 3 &&
9605 AsmPieces[0] == "rorw" &&
9606 AsmPieces[1] == "$$8," &&
9607 AsmPieces[2] == "${0:w}" &&
9608 IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
9609 return LowerToBSwap(CI);
9613 if (CI->getType()->isInteger(64) &&
9614 Constraints.size() >= 2 &&
9615 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9616 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9617 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9618 SmallVector<StringRef, 4> Words;
9619 SplitString(AsmPieces[0], Words, " \t");
9620 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9622 SplitString(AsmPieces[1], Words, " \t");
9623 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9625 SplitString(AsmPieces[2], Words, " \t,");
9626 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9627 Words[2] == "%edx") {
9628 return LowerToBSwap(CI);
9640 /// getConstraintType - Given a constraint letter, return the type of
9641 /// constraint it is for this target.
9642 X86TargetLowering::ConstraintType
9643 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9644 if (Constraint.size() == 1) {
9645 switch (Constraint[0]) {
9657 return C_RegisterClass;
9665 return TargetLowering::getConstraintType(Constraint);
9668 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9669 /// with another that has more specific requirements based on the type of the
9670 /// corresponding operand.
9671 const char *X86TargetLowering::
9672 LowerXConstraint(EVT ConstraintVT) const {
9673 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9674 // 'f' like normal targets.
9675 if (ConstraintVT.isFloatingPoint()) {
9676 if (Subtarget->hasSSE2())
9678 if (Subtarget->hasSSE1())
9682 return TargetLowering::LowerXConstraint(ConstraintVT);
9685 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9686 /// vector. If it is invalid, don't add anything to Ops.
9687 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9690 std::vector<SDValue>&Ops,
9691 SelectionDAG &DAG) const {
9692 SDValue Result(0, 0);
9694 switch (Constraint) {
9697 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9698 if (C->getZExtValue() <= 31) {
9699 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9705 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9706 if (C->getZExtValue() <= 63) {
9707 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9713 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9714 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9715 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9721 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9722 if (C->getZExtValue() <= 255) {
9723 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9729 // 32-bit signed value
9730 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9731 const ConstantInt *CI = C->getConstantIntValue();
9732 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9733 C->getSExtValue())) {
9734 // Widen to 64 bits here to get it sign extended.
9735 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9738 // FIXME gcc accepts some relocatable values here too, but only in certain
9739 // memory models; it's complicated.
9744 // 32-bit unsigned value
9745 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9746 const ConstantInt *CI = C->getConstantIntValue();
9747 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9748 C->getZExtValue())) {
9749 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9753 // FIXME gcc accepts some relocatable values here too, but only in certain
9754 // memory models; it's complicated.
9758 // Literal immediates are always ok.
9759 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9760 // Widen to 64 bits here to get it sign extended.
9761 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9765 // If we are in non-pic codegen mode, we allow the address of a global (with
9766 // an optional displacement) to be used with 'i'.
9767 GlobalAddressSDNode *GA = 0;
9770 // Match either (GA), (GA+C), (GA+C1+C2), etc.
9772 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9773 Offset += GA->getOffset();
9775 } else if (Op.getOpcode() == ISD::ADD) {
9776 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9777 Offset += C->getZExtValue();
9778 Op = Op.getOperand(0);
9781 } else if (Op.getOpcode() == ISD::SUB) {
9782 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9783 Offset += -C->getZExtValue();
9784 Op = Op.getOperand(0);
9789 // Otherwise, this isn't something we can handle, reject it.
9793 GlobalValue *GV = GA->getGlobal();
9794 // If we require an extra load to get this address, as in PIC mode, we
9796 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9797 getTargetMachine())))
9801 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9803 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9809 if (Result.getNode()) {
9810 Ops.push_back(Result);
9813 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9817 std::vector<unsigned> X86TargetLowering::
9818 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9820 if (Constraint.size() == 1) {
9821 // FIXME: not handling fp-stack yet!
9822 switch (Constraint[0]) { // GCC X86 Constraint Letters
9823 default: break; // Unknown constraint letter
9824 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9825 if (Subtarget->is64Bit()) {
9827 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9828 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9829 X86::R10D,X86::R11D,X86::R12D,
9830 X86::R13D,X86::R14D,X86::R15D,
9831 X86::EBP, X86::ESP, 0);
9832 else if (VT == MVT::i16)
9833 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
9834 X86::SI, X86::DI, X86::R8W,X86::R9W,
9835 X86::R10W,X86::R11W,X86::R12W,
9836 X86::R13W,X86::R14W,X86::R15W,
9837 X86::BP, X86::SP, 0);
9838 else if (VT == MVT::i8)
9839 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
9840 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9841 X86::R10B,X86::R11B,X86::R12B,
9842 X86::R13B,X86::R14B,X86::R15B,
9843 X86::BPL, X86::SPL, 0);
9845 else if (VT == MVT::i64)
9846 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9847 X86::RSI, X86::RDI, X86::R8, X86::R9,
9848 X86::R10, X86::R11, X86::R12,
9849 X86::R13, X86::R14, X86::R15,
9850 X86::RBP, X86::RSP, 0);
9854 // 32-bit fallthrough
9857 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9858 else if (VT == MVT::i16)
9859 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9860 else if (VT == MVT::i8)
9861 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9862 else if (VT == MVT::i64)
9863 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9868 return std::vector<unsigned>();
9871 std::pair<unsigned, const TargetRegisterClass*>
9872 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9874 // First, see if this is a constraint that directly corresponds to an LLVM
9876 if (Constraint.size() == 1) {
9877 // GCC Constraint Letters
9878 switch (Constraint[0]) {
9880 case 'r': // GENERAL_REGS
9881 case 'l': // INDEX_REGS
9883 return std::make_pair(0U, X86::GR8RegisterClass);
9885 return std::make_pair(0U, X86::GR16RegisterClass);
9886 if (VT == MVT::i32 || !Subtarget->is64Bit())
9887 return std::make_pair(0U, X86::GR32RegisterClass);
9888 return std::make_pair(0U, X86::GR64RegisterClass);
9889 case 'R': // LEGACY_REGS
9891 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
9893 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
9894 if (VT == MVT::i32 || !Subtarget->is64Bit())
9895 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
9896 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
9897 case 'f': // FP Stack registers.
9898 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9899 // value to the correct fpstack register class.
9900 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9901 return std::make_pair(0U, X86::RFP32RegisterClass);
9902 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9903 return std::make_pair(0U, X86::RFP64RegisterClass);
9904 return std::make_pair(0U, X86::RFP80RegisterClass);
9905 case 'y': // MMX_REGS if MMX allowed.
9906 if (!Subtarget->hasMMX()) break;
9907 return std::make_pair(0U, X86::VR64RegisterClass);
9908 case 'Y': // SSE_REGS if SSE2 allowed
9909 if (!Subtarget->hasSSE2()) break;
9911 case 'x': // SSE_REGS if SSE1 allowed
9912 if (!Subtarget->hasSSE1()) break;
9914 switch (VT.getSimpleVT().SimpleTy) {
9916 // Scalar SSE types.
9919 return std::make_pair(0U, X86::FR32RegisterClass);
9922 return std::make_pair(0U, X86::FR64RegisterClass);
9930 return std::make_pair(0U, X86::VR128RegisterClass);
9936 // Use the default implementation in TargetLowering to convert the register
9937 // constraint into a member of a register class.
9938 std::pair<unsigned, const TargetRegisterClass*> Res;
9939 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9941 // Not found as a standard register?
9942 if (Res.second == 0) {
9943 // Map st(0) -> st(7) -> ST0
9944 if (Constraint.size() == 7 && Constraint[0] == '{' &&
9945 tolower(Constraint[1]) == 's' &&
9946 tolower(Constraint[2]) == 't' &&
9947 Constraint[3] == '(' &&
9948 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
9949 Constraint[5] == ')' &&
9950 Constraint[6] == '}') {
9952 Res.first = X86::ST0+Constraint[4]-'0';
9953 Res.second = X86::RFP80RegisterClass;
9957 // GCC allows "st(0)" to be called just plain "st".
9958 if (StringRef("{st}").equals_lower(Constraint)) {
9959 Res.first = X86::ST0;
9960 Res.second = X86::RFP80RegisterClass;
9965 if (StringRef("{flags}").equals_lower(Constraint)) {
9966 Res.first = X86::EFLAGS;
9967 Res.second = X86::CCRRegisterClass;
9971 // 'A' means EAX + EDX.
9972 if (Constraint == "A") {
9973 Res.first = X86::EAX;
9974 Res.second = X86::GR32_ADRegisterClass;
9980 // Otherwise, check to see if this is a register class of the wrong value
9981 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
9982 // turn into {ax},{dx}.
9983 if (Res.second->hasType(VT))
9984 return Res; // Correct type already, nothing to do.
9986 // All of the single-register GCC register classes map their values onto
9987 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
9988 // really want an 8-bit or 32-bit register, map to the appropriate register
9989 // class and return the appropriate register.
9990 if (Res.second == X86::GR16RegisterClass) {
9991 if (VT == MVT::i8) {
9992 unsigned DestReg = 0;
9993 switch (Res.first) {
9995 case X86::AX: DestReg = X86::AL; break;
9996 case X86::DX: DestReg = X86::DL; break;
9997 case X86::CX: DestReg = X86::CL; break;
9998 case X86::BX: DestReg = X86::BL; break;
10001 Res.first = DestReg;
10002 Res.second = X86::GR8RegisterClass;
10004 } else if (VT == MVT::i32) {
10005 unsigned DestReg = 0;
10006 switch (Res.first) {
10008 case X86::AX: DestReg = X86::EAX; break;
10009 case X86::DX: DestReg = X86::EDX; break;
10010 case X86::CX: DestReg = X86::ECX; break;
10011 case X86::BX: DestReg = X86::EBX; break;
10012 case X86::SI: DestReg = X86::ESI; break;
10013 case X86::DI: DestReg = X86::EDI; break;
10014 case X86::BP: DestReg = X86::EBP; break;
10015 case X86::SP: DestReg = X86::ESP; break;
10018 Res.first = DestReg;
10019 Res.second = X86::GR32RegisterClass;
10021 } else if (VT == MVT::i64) {
10022 unsigned DestReg = 0;
10023 switch (Res.first) {
10025 case X86::AX: DestReg = X86::RAX; break;
10026 case X86::DX: DestReg = X86::RDX; break;
10027 case X86::CX: DestReg = X86::RCX; break;
10028 case X86::BX: DestReg = X86::RBX; break;
10029 case X86::SI: DestReg = X86::RSI; break;
10030 case X86::DI: DestReg = X86::RDI; break;
10031 case X86::BP: DestReg = X86::RBP; break;
10032 case X86::SP: DestReg = X86::RSP; break;
10035 Res.first = DestReg;
10036 Res.second = X86::GR64RegisterClass;
10039 } else if (Res.second == X86::FR32RegisterClass ||
10040 Res.second == X86::FR64RegisterClass ||
10041 Res.second == X86::VR128RegisterClass) {
10042 // Handle references to XMM physical registers that got mapped into the
10043 // wrong class. This can happen with constraints like {xmm0} where the
10044 // target independent register mapper will just pick the first match it can
10045 // find, ignoring the required type.
10046 if (VT == MVT::f32)
10047 Res.second = X86::FR32RegisterClass;
10048 else if (VT == MVT::f64)
10049 Res.second = X86::FR64RegisterClass;
10050 else if (X86::VR128RegisterClass->hasType(VT))
10051 Res.second = X86::VR128RegisterClass;
10057 //===----------------------------------------------------------------------===//
10058 // X86 Widen vector type
10059 //===----------------------------------------------------------------------===//
10061 /// getWidenVectorType: given a vector type, returns the type to widen
10062 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
10063 /// If there is no vector type that we want to widen to, returns MVT::Other
10064 /// When and where to widen is target dependent based on the cost of
10065 /// scalarizing vs using the wider vector type.
10067 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
10068 assert(VT.isVector());
10069 if (isTypeLegal(VT))
10072 // TODO: In computeRegisterProperty, we can compute the list of legal vector
10073 // type based on element type. This would speed up our search (though
10074 // it may not be worth it since the size of the list is relatively
10076 EVT EltVT = VT.getVectorElementType();
10077 unsigned NElts = VT.getVectorNumElements();
10079 // On X86, it make sense to widen any vector wider than 1
10083 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
10084 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
10085 EVT SVT = (MVT::SimpleValueType)nVT;
10087 if (isTypeLegal(SVT) &&
10088 SVT.getVectorElementType() == EltVT &&
10089 SVT.getVectorNumElements() > NElts)