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 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86ShuffleDecode.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.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/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
54 using namespace dwarf;
56 STATISTIC(NumTailCalls, "Number of tail calls");
59 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
61 // Forward declarations.
62 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
65 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
67 bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
69 if (TM.getSubtarget<X86Subtarget>().isTargetDarwin()) {
70 if (is64Bit) return new X8664_MachoTargetObjectFile();
71 return new TargetLoweringObjectFileMachO();
72 } else if (TM.getSubtarget<X86Subtarget>().isTargetELF() ){
73 if (is64Bit) return new X8664_ELFTargetObjectFile(TM);
74 return new X8632_ELFTargetObjectFile(TM);
75 } else if (TM.getSubtarget<X86Subtarget>().isTargetCOFF()) {
76 return new TargetLoweringObjectFileCOFF();
78 llvm_unreachable("unknown subtarget type");
81 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
82 : TargetLowering(TM, createTLOF(TM)) {
83 Subtarget = &TM.getSubtarget<X86Subtarget>();
84 X86ScalarSSEf64 = Subtarget->hasSSE2();
85 X86ScalarSSEf32 = Subtarget->hasSSE1();
86 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
88 RegInfo = TM.getRegisterInfo();
91 // Set up the TargetLowering object.
93 // X86 is weird, it always uses i8 for shift amounts and setcc results.
94 setShiftAmountType(MVT::i8);
95 setBooleanContents(ZeroOrOneBooleanContent);
96 setSchedulingPreference(Sched::RegPressure);
97 setStackPointerRegisterToSaveRestore(X86StackPtr);
99 if (Subtarget->isTargetDarwin()) {
100 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
101 setUseUnderscoreSetJmp(false);
102 setUseUnderscoreLongJmp(false);
103 } else if (Subtarget->isTargetMingw()) {
104 // MS runtime is weird: it exports _setjmp, but longjmp!
105 setUseUnderscoreSetJmp(true);
106 setUseUnderscoreLongJmp(false);
108 setUseUnderscoreSetJmp(true);
109 setUseUnderscoreLongJmp(true);
112 // Set up the register classes.
113 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);
123 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
124 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
125 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
126 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
127 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
129 // SETOEQ and SETUNE require checking two conditions.
130 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
131 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
132 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
133 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
134 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
135 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
137 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
139 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
140 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
141 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
143 if (Subtarget->is64Bit()) {
144 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
145 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
146 } else if (!UseSoftFloat) {
147 // We have an algorithm for SSE2->double, and we turn this into a
148 // 64-bit FILD followed by conditional FADD for other targets.
149 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
150 // We have an algorithm for SSE2, and we turn this into a 64-bit
151 // FILD for other targets.
152 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
155 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
157 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
158 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
161 // SSE has no i16 to fp conversion, only i32
162 if (X86ScalarSSEf32) {
163 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
164 // f32 and f64 cases are Legal, f80 case is not
165 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
167 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
168 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
171 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
172 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
175 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
176 // are Legal, f80 is custom lowered.
177 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
178 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
180 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
182 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
183 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
185 if (X86ScalarSSEf32) {
186 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
187 // f32 and f64 cases are Legal, f80 case is not
188 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
190 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
191 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
194 // Handle FP_TO_UINT by promoting the destination to a larger signed
196 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
197 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
198 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
200 if (Subtarget->is64Bit()) {
201 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
202 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
203 } else if (!UseSoftFloat) {
204 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
205 // Expand FP_TO_UINT into a select.
206 // FIXME: We would like to use a Custom expander here eventually to do
207 // the optimal thing for SSE vs. the default expansion in the legalizer.
208 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
210 // With SSE3 we can use fisttpll to convert to a signed i64; without
211 // SSE, we're stuck with a fistpll.
212 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
215 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
216 if (!X86ScalarSSEf64) {
217 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
218 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
219 if (Subtarget->is64Bit()) {
220 setOperationAction(ISD::BIT_CONVERT , MVT::f64 , Expand);
221 // Without SSE, i64->f64 goes through memory.
222 setOperationAction(ISD::BIT_CONVERT , MVT::i64 , Expand);
226 // Scalar integer divide and remainder are lowered to use operations that
227 // produce two results, to match the available instructions. This exposes
228 // the two-result form to trivial CSE, which is able to combine x/y and x%y
229 // into a single instruction.
231 // Scalar integer multiply-high is also lowered to use two-result
232 // operations, to match the available instructions. However, plain multiply
233 // (low) operations are left as Legal, as there are single-result
234 // instructions for this in x86. Using the two-result multiply instructions
235 // when both high and low results are needed must be arranged by dagcombine.
236 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
237 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
238 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
239 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
240 setOperationAction(ISD::SREM , MVT::i8 , Expand);
241 setOperationAction(ISD::UREM , MVT::i8 , Expand);
242 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
243 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
244 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
245 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
246 setOperationAction(ISD::SREM , MVT::i16 , Expand);
247 setOperationAction(ISD::UREM , MVT::i16 , Expand);
248 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
249 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
250 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
251 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
252 setOperationAction(ISD::SREM , MVT::i32 , Expand);
253 setOperationAction(ISD::UREM , MVT::i32 , Expand);
254 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
255 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
256 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
257 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
258 setOperationAction(ISD::SREM , MVT::i64 , Expand);
259 setOperationAction(ISD::UREM , MVT::i64 , Expand);
261 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
262 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
263 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
264 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
265 if (Subtarget->is64Bit())
266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
267 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
268 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
269 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
270 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
271 setOperationAction(ISD::FREM , MVT::f32 , Expand);
272 setOperationAction(ISD::FREM , MVT::f64 , Expand);
273 setOperationAction(ISD::FREM , MVT::f80 , Expand);
274 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
276 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
277 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
278 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
279 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
280 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
281 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
282 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
283 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
284 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
285 if (Subtarget->is64Bit()) {
286 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
287 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
288 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
291 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
292 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
294 // These should be promoted to a larger select which is supported.
295 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
296 // X86 wants to expand cmov itself.
297 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
298 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
299 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
300 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
301 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
302 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
303 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
304 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
305 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
306 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
307 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
308 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
309 if (Subtarget->is64Bit()) {
310 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
311 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
313 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
316 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
317 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
318 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
319 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
320 if (Subtarget->is64Bit())
321 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
322 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
323 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
324 if (Subtarget->is64Bit()) {
325 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
326 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
327 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
328 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
329 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
331 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
332 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
333 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
334 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
335 if (Subtarget->is64Bit()) {
336 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
337 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
338 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
341 if (Subtarget->hasSSE1())
342 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
344 // We may not have a libcall for MEMBARRIER so we should lower this.
345 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
347 // On X86 and X86-64, atomic operations are lowered to locked instructions.
348 // Locked instructions, in turn, have implicit fence semantics (all memory
349 // operations are flushed before issuing the locked instruction, and they
350 // are not buffered), so we can fold away the common pattern of
351 // fence-atomic-fence.
352 setShouldFoldAtomicFences(true);
354 // Expand certain atomics
355 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
356 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
357 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
358 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
360 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
361 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
362 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
363 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
365 if (!Subtarget->is64Bit()) {
366 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
367 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
368 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
369 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
370 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
371 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
372 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
375 // FIXME - use subtarget debug flags
376 if (!Subtarget->isTargetDarwin() &&
377 !Subtarget->isTargetELF() &&
378 !Subtarget->isTargetCygMing()) {
379 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
382 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
383 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
384 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
385 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
386 if (Subtarget->is64Bit()) {
387 setExceptionPointerRegister(X86::RAX);
388 setExceptionSelectorRegister(X86::RDX);
390 setExceptionPointerRegister(X86::EAX);
391 setExceptionSelectorRegister(X86::EDX);
393 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
394 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
396 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
398 setOperationAction(ISD::TRAP, MVT::Other, Legal);
400 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
401 setOperationAction(ISD::VASTART , MVT::Other, Custom);
402 setOperationAction(ISD::VAEND , MVT::Other, Expand);
403 if (Subtarget->is64Bit()) {
404 setOperationAction(ISD::VAARG , MVT::Other, Custom);
405 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
407 setOperationAction(ISD::VAARG , MVT::Other, Expand);
408 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
411 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
412 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
413 if (Subtarget->is64Bit())
414 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
415 if (Subtarget->isTargetCygMing())
416 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
418 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
420 if (!UseSoftFloat && X86ScalarSSEf64) {
421 // f32 and f64 use SSE.
422 // Set up the FP register classes.
423 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
424 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
426 // Use ANDPD to simulate FABS.
427 setOperationAction(ISD::FABS , MVT::f64, Custom);
428 setOperationAction(ISD::FABS , MVT::f32, Custom);
430 // Use XORP to simulate FNEG.
431 setOperationAction(ISD::FNEG , MVT::f64, Custom);
432 setOperationAction(ISD::FNEG , MVT::f32, Custom);
434 // Use ANDPD and ORPD to simulate FCOPYSIGN.
435 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
436 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
438 // We don't support sin/cos/fmod
439 setOperationAction(ISD::FSIN , MVT::f64, Expand);
440 setOperationAction(ISD::FCOS , MVT::f64, Expand);
441 setOperationAction(ISD::FSIN , MVT::f32, Expand);
442 setOperationAction(ISD::FCOS , MVT::f32, Expand);
444 // Expand FP immediates into loads from the stack, except for the special
446 addLegalFPImmediate(APFloat(+0.0)); // xorpd
447 addLegalFPImmediate(APFloat(+0.0f)); // xorps
448 } else if (!UseSoftFloat && X86ScalarSSEf32) {
449 // Use SSE for f32, x87 for f64.
450 // Set up the FP register classes.
451 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
452 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
454 // Use ANDPS to simulate FABS.
455 setOperationAction(ISD::FABS , MVT::f32, Custom);
457 // Use XORP to simulate FNEG.
458 setOperationAction(ISD::FNEG , MVT::f32, Custom);
460 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
462 // Use ANDPS and ORPS to simulate FCOPYSIGN.
463 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
464 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
466 // We don't support sin/cos/fmod
467 setOperationAction(ISD::FSIN , MVT::f32, Expand);
468 setOperationAction(ISD::FCOS , MVT::f32, Expand);
470 // Special cases we handle for FP constants.
471 addLegalFPImmediate(APFloat(+0.0f)); // xorps
472 addLegalFPImmediate(APFloat(+0.0)); // FLD0
473 addLegalFPImmediate(APFloat(+1.0)); // FLD1
474 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
475 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
478 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
479 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
481 } else if (!UseSoftFloat) {
482 // f32 and f64 in x87.
483 // Set up the FP register classes.
484 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
485 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
487 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
488 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
489 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
490 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
493 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
494 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
496 addLegalFPImmediate(APFloat(+0.0)); // FLD0
497 addLegalFPImmediate(APFloat(+1.0)); // FLD1
498 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
499 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
500 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
501 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
502 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
503 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
506 // Long double always uses X87.
508 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
509 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
510 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
513 APFloat TmpFlt(+0.0);
514 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
516 addLegalFPImmediate(TmpFlt); // FLD0
518 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
519 APFloat TmpFlt2(+1.0);
520 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
522 addLegalFPImmediate(TmpFlt2); // FLD1
523 TmpFlt2.changeSign();
524 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
528 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
529 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
533 // Always use a library call for pow.
534 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
535 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
536 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
538 setOperationAction(ISD::FLOG, MVT::f80, Expand);
539 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
540 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
541 setOperationAction(ISD::FEXP, MVT::f80, Expand);
542 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
544 // First set operation action for all vector types to either promote
545 // (for widening) or expand (for scalarization). Then we will selectively
546 // turn on ones that can be effectively codegen'd.
547 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
548 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
549 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
564 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
565 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
598 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
602 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
603 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
604 setTruncStoreAction((MVT::SimpleValueType)VT,
605 (MVT::SimpleValueType)InnerVT, Expand);
606 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
607 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
608 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
611 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
612 // with -msoft-float, disable use of MMX as well.
613 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
614 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass, false);
615 // No operations on x86mmx supported, everything uses intrinsics.
618 // MMX-sized vectors (other than x86mmx) are expected to be expanded
619 // into smaller operations.
620 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
621 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
622 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
623 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
624 setOperationAction(ISD::AND, MVT::v8i8, Expand);
625 setOperationAction(ISD::AND, MVT::v4i16, Expand);
626 setOperationAction(ISD::AND, MVT::v2i32, Expand);
627 setOperationAction(ISD::AND, MVT::v1i64, Expand);
628 setOperationAction(ISD::OR, MVT::v8i8, Expand);
629 setOperationAction(ISD::OR, MVT::v4i16, Expand);
630 setOperationAction(ISD::OR, MVT::v2i32, Expand);
631 setOperationAction(ISD::OR, MVT::v1i64, Expand);
632 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
633 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
634 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
635 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
636 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
637 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
638 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
639 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
640 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
641 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
642 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
643 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
644 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
645 setOperationAction(ISD::BIT_CONVERT, MVT::v8i8, Expand);
646 setOperationAction(ISD::BIT_CONVERT, MVT::v4i16, Expand);
647 setOperationAction(ISD::BIT_CONVERT, MVT::v2i32, Expand);
648 setOperationAction(ISD::BIT_CONVERT, MVT::v1i64, Expand);
650 if (!UseSoftFloat && Subtarget->hasSSE1()) {
651 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
653 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
654 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
655 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
656 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
657 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
658 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
659 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
660 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
661 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
663 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
664 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
667 if (!UseSoftFloat && Subtarget->hasSSE2()) {
668 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
670 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
671 // registers cannot be used even for integer operations.
672 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
673 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
674 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
675 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
677 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
678 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
679 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
680 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
681 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
682 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
683 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
684 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
685 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
686 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
687 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
688 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
689 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
690 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
691 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
692 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
694 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
695 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
696 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
697 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
699 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
700 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
701 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
702 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
703 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
705 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
706 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
707 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
708 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
709 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
711 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
712 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
713 EVT VT = (MVT::SimpleValueType)i;
714 // Do not attempt to custom lower non-power-of-2 vectors
715 if (!isPowerOf2_32(VT.getVectorNumElements()))
717 // Do not attempt to custom lower non-128-bit vectors
718 if (!VT.is128BitVector())
720 setOperationAction(ISD::BUILD_VECTOR,
721 VT.getSimpleVT().SimpleTy, Custom);
722 setOperationAction(ISD::VECTOR_SHUFFLE,
723 VT.getSimpleVT().SimpleTy, Custom);
724 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
725 VT.getSimpleVT().SimpleTy, Custom);
728 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
729 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
730 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
731 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
732 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
733 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
735 if (Subtarget->is64Bit()) {
736 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
740 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
741 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
742 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
745 // Do not attempt to promote non-128-bit vectors
746 if (!VT.is128BitVector())
749 setOperationAction(ISD::AND, SVT, Promote);
750 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
751 setOperationAction(ISD::OR, SVT, Promote);
752 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
753 setOperationAction(ISD::XOR, SVT, Promote);
754 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
755 setOperationAction(ISD::LOAD, SVT, Promote);
756 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
757 setOperationAction(ISD::SELECT, SVT, Promote);
758 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
761 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
763 // Custom lower v2i64 and v2f64 selects.
764 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
765 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
766 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
767 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
769 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
770 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
773 if (Subtarget->hasSSE41()) {
774 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
775 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
776 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
777 setOperationAction(ISD::FRINT, MVT::f32, Legal);
778 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
779 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
780 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
781 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
782 setOperationAction(ISD::FRINT, MVT::f64, Legal);
783 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
785 // FIXME: Do we need to handle scalar-to-vector here?
786 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
788 // Can turn SHL into an integer multiply.
789 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
790 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
792 // i8 and i16 vectors are custom , because the source register and source
793 // source memory operand types are not the same width. f32 vectors are
794 // custom since the immediate controlling the insert encodes additional
796 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
797 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
798 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
799 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
801 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
802 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
803 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
804 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
806 if (Subtarget->is64Bit()) {
807 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
808 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
812 if (Subtarget->hasSSE42()) {
813 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
816 if (!UseSoftFloat && Subtarget->hasAVX()) {
817 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
818 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
819 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
820 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
821 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
823 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
824 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
825 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
826 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
827 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
828 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
829 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
830 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
831 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
832 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
833 setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
834 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
835 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
836 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
837 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
839 // Operations to consider commented out -v16i16 v32i8
840 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
841 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
842 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
843 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
844 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
845 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
846 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
847 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
848 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
849 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
850 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
851 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
852 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
853 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
855 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
856 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
857 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
858 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
860 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
861 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
862 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
863 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
864 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
866 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
867 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
868 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
869 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
870 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
871 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
874 // Not sure we want to do this since there are no 256-bit integer
877 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
878 // This includes 256-bit vectors
879 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
880 EVT VT = (MVT::SimpleValueType)i;
882 // Do not attempt to custom lower non-power-of-2 vectors
883 if (!isPowerOf2_32(VT.getVectorNumElements()))
886 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
887 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
888 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
891 if (Subtarget->is64Bit()) {
892 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
893 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
898 // Not sure we want to do this since there are no 256-bit integer
901 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
902 // Including 256-bit vectors
903 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
904 EVT VT = (MVT::SimpleValueType)i;
906 if (!VT.is256BitVector()) {
909 setOperationAction(ISD::AND, VT, Promote);
910 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
911 setOperationAction(ISD::OR, VT, Promote);
912 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
913 setOperationAction(ISD::XOR, VT, Promote);
914 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
915 setOperationAction(ISD::LOAD, VT, Promote);
916 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
917 setOperationAction(ISD::SELECT, VT, Promote);
918 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
921 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
925 // We want to custom lower some of our intrinsics.
926 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
928 // Add/Sub/Mul with overflow operations are custom lowered.
929 setOperationAction(ISD::SADDO, MVT::i32, Custom);
930 setOperationAction(ISD::UADDO, MVT::i32, Custom);
931 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
932 setOperationAction(ISD::USUBO, MVT::i32, Custom);
933 setOperationAction(ISD::SMULO, MVT::i32, Custom);
935 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
936 // handle type legalization for these operations here.
938 // FIXME: We really should do custom legalization for addition and
939 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
940 // than generic legalization for 64-bit multiplication-with-overflow, though.
941 if (Subtarget->is64Bit()) {
942 setOperationAction(ISD::SADDO, MVT::i64, Custom);
943 setOperationAction(ISD::UADDO, MVT::i64, Custom);
944 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
945 setOperationAction(ISD::USUBO, MVT::i64, Custom);
946 setOperationAction(ISD::SMULO, MVT::i64, Custom);
949 if (!Subtarget->is64Bit()) {
950 // These libcalls are not available in 32-bit.
951 setLibcallName(RTLIB::SHL_I128, 0);
952 setLibcallName(RTLIB::SRL_I128, 0);
953 setLibcallName(RTLIB::SRA_I128, 0);
956 // We have target-specific dag combine patterns for the following nodes:
957 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
958 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
959 setTargetDAGCombine(ISD::BUILD_VECTOR);
960 setTargetDAGCombine(ISD::SELECT);
961 setTargetDAGCombine(ISD::SHL);
962 setTargetDAGCombine(ISD::SRA);
963 setTargetDAGCombine(ISD::SRL);
964 setTargetDAGCombine(ISD::OR);
965 setTargetDAGCombine(ISD::STORE);
966 setTargetDAGCombine(ISD::ZERO_EXTEND);
967 if (Subtarget->is64Bit())
968 setTargetDAGCombine(ISD::MUL);
970 computeRegisterProperties();
972 // FIXME: These should be based on subtarget info. Plus, the values should
973 // be smaller when we are in optimizing for size mode.
974 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
975 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
976 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
977 setPrefLoopAlignment(16);
978 benefitFromCodePlacementOpt = true;
982 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
987 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
988 /// the desired ByVal argument alignment.
989 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
992 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
993 if (VTy->getBitWidth() == 128)
995 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
996 unsigned EltAlign = 0;
997 getMaxByValAlign(ATy->getElementType(), EltAlign);
998 if (EltAlign > MaxAlign)
1000 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1001 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1002 unsigned EltAlign = 0;
1003 getMaxByValAlign(STy->getElementType(i), EltAlign);
1004 if (EltAlign > MaxAlign)
1005 MaxAlign = EltAlign;
1013 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1014 /// function arguments in the caller parameter area. For X86, aggregates
1015 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1016 /// are at 4-byte boundaries.
1017 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1018 if (Subtarget->is64Bit()) {
1019 // Max of 8 and alignment of type.
1020 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1027 if (Subtarget->hasSSE1())
1028 getMaxByValAlign(Ty, Align);
1032 /// getOptimalMemOpType - Returns the target specific optimal type for load
1033 /// and store operations as a result of memset, memcpy, and memmove
1034 /// lowering. If DstAlign is zero that means it's safe to destination
1035 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1036 /// means there isn't a need to check it against alignment requirement,
1037 /// probably because the source does not need to be loaded. If
1038 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1039 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1040 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1041 /// constant so it does not need to be loaded.
1042 /// It returns EVT::Other if the type should be determined using generic
1043 /// target-independent logic.
1045 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1046 unsigned DstAlign, unsigned SrcAlign,
1047 bool NonScalarIntSafe,
1049 MachineFunction &MF) const {
1050 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1051 // linux. This is because the stack realignment code can't handle certain
1052 // cases like PR2962. This should be removed when PR2962 is fixed.
1053 const Function *F = MF.getFunction();
1054 if (NonScalarIntSafe &&
1055 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1057 (Subtarget->isUnalignedMemAccessFast() ||
1058 ((DstAlign == 0 || DstAlign >= 16) &&
1059 (SrcAlign == 0 || SrcAlign >= 16))) &&
1060 Subtarget->getStackAlignment() >= 16) {
1061 if (Subtarget->hasSSE2())
1063 if (Subtarget->hasSSE1())
1065 } else if (!MemcpyStrSrc && Size >= 8 &&
1066 !Subtarget->is64Bit() &&
1067 Subtarget->getStackAlignment() >= 8 &&
1068 Subtarget->hasSSE2()) {
1069 // Do not use f64 to lower memcpy if source is string constant. It's
1070 // better to use i32 to avoid the loads.
1074 if (Subtarget->is64Bit() && Size >= 8)
1079 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1080 /// current function. The returned value is a member of the
1081 /// MachineJumpTableInfo::JTEntryKind enum.
1082 unsigned X86TargetLowering::getJumpTableEncoding() const {
1083 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1085 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1086 Subtarget->isPICStyleGOT())
1087 return MachineJumpTableInfo::EK_Custom32;
1089 // Otherwise, use the normal jump table encoding heuristics.
1090 return TargetLowering::getJumpTableEncoding();
1093 /// getPICBaseSymbol - Return the X86-32 PIC base.
1095 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1096 MCContext &Ctx) const {
1097 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1098 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1099 Twine(MF->getFunctionNumber())+"$pb");
1104 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1105 const MachineBasicBlock *MBB,
1106 unsigned uid,MCContext &Ctx) const{
1107 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1108 Subtarget->isPICStyleGOT());
1109 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1111 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1112 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1115 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1117 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1118 SelectionDAG &DAG) const {
1119 if (!Subtarget->is64Bit())
1120 // This doesn't have DebugLoc associated with it, but is not really the
1121 // same as a Register.
1122 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1126 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1127 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1129 const MCExpr *X86TargetLowering::
1130 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1131 MCContext &Ctx) const {
1132 // X86-64 uses RIP relative addressing based on the jump table label.
1133 if (Subtarget->isPICStyleRIPRel())
1134 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1136 // Otherwise, the reference is relative to the PIC base.
1137 return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1140 /// getFunctionAlignment - Return the Log2 alignment of this function.
1141 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1142 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1145 std::pair<const TargetRegisterClass*, uint8_t>
1146 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1147 const TargetRegisterClass *RRC = 0;
1149 switch (VT.getSimpleVT().SimpleTy) {
1151 return TargetLowering::findRepresentativeClass(VT);
1152 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1153 RRC = (Subtarget->is64Bit()
1154 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1157 RRC = X86::VR64RegisterClass;
1159 case MVT::f32: case MVT::f64:
1160 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1161 case MVT::v4f32: case MVT::v2f64:
1162 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1164 RRC = X86::VR128RegisterClass;
1167 return std::make_pair(RRC, Cost);
1171 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1172 MachineFunction &MF) const {
1173 unsigned FPDiff = RegInfo->hasFP(MF) ? 1 : 0;
1174 switch (RC->getID()) {
1177 case X86::GR32RegClassID:
1179 case X86::GR64RegClassID:
1181 case X86::VR128RegClassID:
1182 return Subtarget->is64Bit() ? 10 : 4;
1183 case X86::VR64RegClassID:
1188 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1189 unsigned &Offset) const {
1190 if (!Subtarget->isTargetLinux())
1193 if (Subtarget->is64Bit()) {
1194 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1196 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1209 //===----------------------------------------------------------------------===//
1210 // Return Value Calling Convention Implementation
1211 //===----------------------------------------------------------------------===//
1213 #include "X86GenCallingConv.inc"
1216 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1217 const SmallVectorImpl<ISD::OutputArg> &Outs,
1218 LLVMContext &Context) const {
1219 SmallVector<CCValAssign, 16> RVLocs;
1220 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1222 return CCInfo.CheckReturn(Outs, RetCC_X86);
1226 X86TargetLowering::LowerReturn(SDValue Chain,
1227 CallingConv::ID CallConv, bool isVarArg,
1228 const SmallVectorImpl<ISD::OutputArg> &Outs,
1229 const SmallVectorImpl<SDValue> &OutVals,
1230 DebugLoc dl, SelectionDAG &DAG) const {
1231 MachineFunction &MF = DAG.getMachineFunction();
1232 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1234 SmallVector<CCValAssign, 16> RVLocs;
1235 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1236 RVLocs, *DAG.getContext());
1237 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1239 // Add the regs to the liveout set for the function.
1240 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1241 for (unsigned i = 0; i != RVLocs.size(); ++i)
1242 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1243 MRI.addLiveOut(RVLocs[i].getLocReg());
1247 SmallVector<SDValue, 6> RetOps;
1248 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1249 // Operand #1 = Bytes To Pop
1250 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1253 // Copy the result values into the output registers.
1254 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1255 CCValAssign &VA = RVLocs[i];
1256 assert(VA.isRegLoc() && "Can only return in registers!");
1257 SDValue ValToCopy = OutVals[i];
1258 EVT ValVT = ValToCopy.getValueType();
1260 // If this is x86-64, and we disabled SSE, we can't return FP values,
1261 // or SSE or MMX vectors.
1262 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1263 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1264 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1265 report_fatal_error("SSE register return with SSE disabled");
1267 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1268 // llvm-gcc has never done it right and no one has noticed, so this
1269 // should be OK for now.
1270 if (ValVT == MVT::f64 &&
1271 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1272 report_fatal_error("SSE2 register return with SSE2 disabled");
1274 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1275 // the RET instruction and handled by the FP Stackifier.
1276 if (VA.getLocReg() == X86::ST0 ||
1277 VA.getLocReg() == X86::ST1) {
1278 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1279 // change the value to the FP stack register class.
1280 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1281 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1282 RetOps.push_back(ValToCopy);
1283 // Don't emit a copytoreg.
1287 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1288 // which is returned in RAX / RDX.
1289 if (Subtarget->is64Bit()) {
1290 if (ValVT == MVT::x86mmx) {
1291 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1292 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1293 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1295 // If we don't have SSE2 available, convert to v4f32 so the generated
1296 // register is legal.
1297 if (!Subtarget->hasSSE2())
1298 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32,ValToCopy);
1303 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1304 Flag = Chain.getValue(1);
1307 // The x86-64 ABI for returning structs by value requires that we copy
1308 // the sret argument into %rax for the return. We saved the argument into
1309 // a virtual register in the entry block, so now we copy the value out
1311 if (Subtarget->is64Bit() &&
1312 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1313 MachineFunction &MF = DAG.getMachineFunction();
1314 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1315 unsigned Reg = FuncInfo->getSRetReturnReg();
1317 "SRetReturnReg should have been set in LowerFormalArguments().");
1318 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1320 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1321 Flag = Chain.getValue(1);
1323 // RAX now acts like a return value.
1324 MRI.addLiveOut(X86::RAX);
1327 RetOps[0] = Chain; // Update chain.
1329 // Add the flag if we have it.
1331 RetOps.push_back(Flag);
1333 return DAG.getNode(X86ISD::RET_FLAG, dl,
1334 MVT::Other, &RetOps[0], RetOps.size());
1337 /// LowerCallResult - Lower the result values of a call into the
1338 /// appropriate copies out of appropriate physical registers.
1341 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1342 CallingConv::ID CallConv, bool isVarArg,
1343 const SmallVectorImpl<ISD::InputArg> &Ins,
1344 DebugLoc dl, SelectionDAG &DAG,
1345 SmallVectorImpl<SDValue> &InVals) const {
1347 // Assign locations to each value returned by this call.
1348 SmallVector<CCValAssign, 16> RVLocs;
1349 bool Is64Bit = Subtarget->is64Bit();
1350 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1351 RVLocs, *DAG.getContext());
1352 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1354 // Copy all of the result registers out of their specified physreg.
1355 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1356 CCValAssign &VA = RVLocs[i];
1357 EVT CopyVT = VA.getValVT();
1359 // If this is x86-64, and we disabled SSE, we can't return FP values
1360 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1361 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1362 report_fatal_error("SSE register return with SSE disabled");
1367 // If this is a call to a function that returns an fp value on the floating
1368 // point stack, we must guarantee the the value is popped from the stack, so
1369 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1370 // if the return value is not used. We use the FpGET_ST0 instructions
1372 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1373 // If we prefer to use the value in xmm registers, copy it out as f80 and
1374 // use a truncate to move it from fp stack reg to xmm reg.
1375 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1376 bool isST0 = VA.getLocReg() == X86::ST0;
1378 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1379 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1380 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1381 SDValue Ops[] = { Chain, InFlag };
1382 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1384 Val = Chain.getValue(0);
1386 // Round the f80 to the right size, which also moves it to the appropriate
1388 if (CopyVT != VA.getValVT())
1389 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1390 // This truncation won't change the value.
1391 DAG.getIntPtrConstant(1));
1392 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1393 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1394 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1395 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1396 MVT::v2i64, InFlag).getValue(1);
1397 Val = Chain.getValue(0);
1398 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1399 Val, DAG.getConstant(0, MVT::i64));
1401 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1402 MVT::i64, InFlag).getValue(1);
1403 Val = Chain.getValue(0);
1405 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1407 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1408 CopyVT, InFlag).getValue(1);
1409 Val = Chain.getValue(0);
1411 InFlag = Chain.getValue(2);
1412 InVals.push_back(Val);
1419 //===----------------------------------------------------------------------===//
1420 // C & StdCall & Fast Calling Convention implementation
1421 //===----------------------------------------------------------------------===//
1422 // StdCall calling convention seems to be standard for many Windows' API
1423 // routines and around. It differs from C calling convention just a little:
1424 // callee should clean up the stack, not caller. Symbols should be also
1425 // decorated in some fancy way :) It doesn't support any vector arguments.
1426 // For info on fast calling convention see Fast Calling Convention (tail call)
1427 // implementation LowerX86_32FastCCCallTo.
1429 /// CallIsStructReturn - Determines whether a call uses struct return
1431 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1435 return Outs[0].Flags.isSRet();
1438 /// ArgsAreStructReturn - Determines whether a function uses struct
1439 /// return semantics.
1441 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1445 return Ins[0].Flags.isSRet();
1448 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1449 /// given CallingConvention value.
1450 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1451 if (Subtarget->is64Bit()) {
1452 if (CC == CallingConv::GHC)
1453 return CC_X86_64_GHC;
1454 else if (Subtarget->isTargetWin64())
1455 return CC_X86_Win64_C;
1460 if (CC == CallingConv::X86_FastCall)
1461 return CC_X86_32_FastCall;
1462 else if (CC == CallingConv::X86_ThisCall)
1463 return CC_X86_32_ThisCall;
1464 else if (CC == CallingConv::Fast)
1465 return CC_X86_32_FastCC;
1466 else if (CC == CallingConv::GHC)
1467 return CC_X86_32_GHC;
1472 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1473 /// by "Src" to address "Dst" with size and alignment information specified by
1474 /// the specific parameter attribute. The copy will be passed as a byval
1475 /// function parameter.
1477 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1478 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1480 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1482 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1483 /*isVolatile*/false, /*AlwaysInline=*/true,
1484 MachinePointerInfo(), MachinePointerInfo());
1487 /// IsTailCallConvention - Return true if the calling convention is one that
1488 /// supports tail call optimization.
1489 static bool IsTailCallConvention(CallingConv::ID CC) {
1490 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1493 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1494 /// a tailcall target by changing its ABI.
1495 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1496 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1500 X86TargetLowering::LowerMemArgument(SDValue Chain,
1501 CallingConv::ID CallConv,
1502 const SmallVectorImpl<ISD::InputArg> &Ins,
1503 DebugLoc dl, SelectionDAG &DAG,
1504 const CCValAssign &VA,
1505 MachineFrameInfo *MFI,
1507 // Create the nodes corresponding to a load from this parameter slot.
1508 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1509 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1510 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1513 // If value is passed by pointer we have address passed instead of the value
1515 if (VA.getLocInfo() == CCValAssign::Indirect)
1516 ValVT = VA.getLocVT();
1518 ValVT = VA.getValVT();
1520 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1521 // changed with more analysis.
1522 // In case of tail call optimization mark all arguments mutable. Since they
1523 // could be overwritten by lowering of arguments in case of a tail call.
1524 if (Flags.isByVal()) {
1525 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1526 VA.getLocMemOffset(), isImmutable);
1527 return DAG.getFrameIndex(FI, getPointerTy());
1529 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1530 VA.getLocMemOffset(), isImmutable);
1531 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1532 return DAG.getLoad(ValVT, dl, Chain, FIN,
1533 MachinePointerInfo::getFixedStack(FI),
1539 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1540 CallingConv::ID CallConv,
1542 const SmallVectorImpl<ISD::InputArg> &Ins,
1545 SmallVectorImpl<SDValue> &InVals)
1547 MachineFunction &MF = DAG.getMachineFunction();
1548 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1550 const Function* Fn = MF.getFunction();
1551 if (Fn->hasExternalLinkage() &&
1552 Subtarget->isTargetCygMing() &&
1553 Fn->getName() == "main")
1554 FuncInfo->setForceFramePointer(true);
1556 MachineFrameInfo *MFI = MF.getFrameInfo();
1557 bool Is64Bit = Subtarget->is64Bit();
1558 bool IsWin64 = Subtarget->isTargetWin64();
1560 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1561 "Var args not supported with calling convention fastcc or ghc");
1563 // Assign locations to all of the incoming arguments.
1564 SmallVector<CCValAssign, 16> ArgLocs;
1565 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1566 ArgLocs, *DAG.getContext());
1567 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1569 unsigned LastVal = ~0U;
1571 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1572 CCValAssign &VA = ArgLocs[i];
1573 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1575 assert(VA.getValNo() != LastVal &&
1576 "Don't support value assigned to multiple locs yet");
1577 LastVal = VA.getValNo();
1579 if (VA.isRegLoc()) {
1580 EVT RegVT = VA.getLocVT();
1581 TargetRegisterClass *RC = NULL;
1582 if (RegVT == MVT::i32)
1583 RC = X86::GR32RegisterClass;
1584 else if (Is64Bit && RegVT == MVT::i64)
1585 RC = X86::GR64RegisterClass;
1586 else if (RegVT == MVT::f32)
1587 RC = X86::FR32RegisterClass;
1588 else if (RegVT == MVT::f64)
1589 RC = X86::FR64RegisterClass;
1590 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1591 RC = X86::VR256RegisterClass;
1592 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1593 RC = X86::VR128RegisterClass;
1594 else if (RegVT == MVT::x86mmx)
1595 RC = X86::VR64RegisterClass;
1597 llvm_unreachable("Unknown argument type!");
1599 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1600 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1602 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1603 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1605 if (VA.getLocInfo() == CCValAssign::SExt)
1606 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1607 DAG.getValueType(VA.getValVT()));
1608 else if (VA.getLocInfo() == CCValAssign::ZExt)
1609 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1610 DAG.getValueType(VA.getValVT()));
1611 else if (VA.getLocInfo() == CCValAssign::BCvt)
1612 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1614 if (VA.isExtInLoc()) {
1615 // Handle MMX values passed in XMM regs.
1616 if (RegVT.isVector()) {
1617 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1620 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1623 assert(VA.isMemLoc());
1624 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1627 // If value is passed via pointer - do a load.
1628 if (VA.getLocInfo() == CCValAssign::Indirect)
1629 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1630 MachinePointerInfo(), false, false, 0);
1632 InVals.push_back(ArgValue);
1635 // The x86-64 ABI for returning structs by value requires that we copy
1636 // the sret argument into %rax for the return. Save the argument into
1637 // a virtual register so that we can access it from the return points.
1638 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1639 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1640 unsigned Reg = FuncInfo->getSRetReturnReg();
1642 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1643 FuncInfo->setSRetReturnReg(Reg);
1645 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1646 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1649 unsigned StackSize = CCInfo.getNextStackOffset();
1650 // Align stack specially for tail calls.
1651 if (FuncIsMadeTailCallSafe(CallConv))
1652 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1654 // If the function takes variable number of arguments, make a frame index for
1655 // the start of the first vararg value... for expansion of llvm.va_start.
1657 if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1658 CallConv != CallingConv::X86_ThisCall))) {
1659 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1662 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1664 // FIXME: We should really autogenerate these arrays
1665 static const unsigned GPR64ArgRegsWin64[] = {
1666 X86::RCX, X86::RDX, X86::R8, X86::R9
1668 static const unsigned GPR64ArgRegs64Bit[] = {
1669 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1671 static const unsigned XMMArgRegs64Bit[] = {
1672 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1673 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1675 const unsigned *GPR64ArgRegs;
1676 unsigned NumXMMRegs = 0;
1679 // The XMM registers which might contain var arg parameters are shadowed
1680 // in their paired GPR. So we only need to save the GPR to their home
1682 TotalNumIntRegs = 4;
1683 GPR64ArgRegs = GPR64ArgRegsWin64;
1685 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1686 GPR64ArgRegs = GPR64ArgRegs64Bit;
1688 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1690 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1693 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1694 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1695 "SSE register cannot be used when SSE is disabled!");
1696 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1697 "SSE register cannot be used when SSE is disabled!");
1698 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1699 // Kernel mode asks for SSE to be disabled, so don't push them
1701 TotalNumXMMRegs = 0;
1704 const TargetFrameInfo &TFI = *getTargetMachine().getFrameInfo();
1705 // Get to the caller-allocated home save location. Add 8 to account
1706 // for the return address.
1707 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1708 FuncInfo->setRegSaveFrameIndex(
1709 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1710 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1712 // For X86-64, if there are vararg parameters that are passed via
1713 // registers, then we must store them to their spots on the stack so they
1714 // may be loaded by deferencing the result of va_next.
1715 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1716 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1717 FuncInfo->setRegSaveFrameIndex(
1718 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1722 // Store the integer parameter registers.
1723 SmallVector<SDValue, 8> MemOps;
1724 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1726 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1727 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1728 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1729 DAG.getIntPtrConstant(Offset));
1730 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1731 X86::GR64RegisterClass);
1732 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1734 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1735 MachinePointerInfo::getFixedStack(
1736 FuncInfo->getRegSaveFrameIndex(), Offset),
1738 MemOps.push_back(Store);
1742 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1743 // Now store the XMM (fp + vector) parameter registers.
1744 SmallVector<SDValue, 11> SaveXMMOps;
1745 SaveXMMOps.push_back(Chain);
1747 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1748 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1749 SaveXMMOps.push_back(ALVal);
1751 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1752 FuncInfo->getRegSaveFrameIndex()));
1753 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1754 FuncInfo->getVarArgsFPOffset()));
1756 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1757 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1758 X86::VR128RegisterClass);
1759 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1760 SaveXMMOps.push_back(Val);
1762 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1764 &SaveXMMOps[0], SaveXMMOps.size()));
1767 if (!MemOps.empty())
1768 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1769 &MemOps[0], MemOps.size());
1773 // Some CCs need callee pop.
1774 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1775 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1777 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1778 // If this is an sret function, the return should pop the hidden pointer.
1779 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1780 FuncInfo->setBytesToPopOnReturn(4);
1784 // RegSaveFrameIndex is X86-64 only.
1785 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1786 if (CallConv == CallingConv::X86_FastCall ||
1787 CallConv == CallingConv::X86_ThisCall)
1788 // fastcc functions can't have varargs.
1789 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1796 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1797 SDValue StackPtr, SDValue Arg,
1798 DebugLoc dl, SelectionDAG &DAG,
1799 const CCValAssign &VA,
1800 ISD::ArgFlagsTy Flags) const {
1801 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1802 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1803 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1804 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1805 if (Flags.isByVal())
1806 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1808 return DAG.getStore(Chain, dl, Arg, PtrOff,
1809 MachinePointerInfo::getStack(LocMemOffset),
1813 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1814 /// optimization is performed and it is required.
1816 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1817 SDValue &OutRetAddr, SDValue Chain,
1818 bool IsTailCall, bool Is64Bit,
1819 int FPDiff, DebugLoc dl) const {
1820 // Adjust the Return address stack slot.
1821 EVT VT = getPointerTy();
1822 OutRetAddr = getReturnAddressFrameIndex(DAG);
1824 // Load the "old" Return address.
1825 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1827 return SDValue(OutRetAddr.getNode(), 1);
1830 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1831 /// optimization is performed and it is required (FPDiff!=0).
1833 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1834 SDValue Chain, SDValue RetAddrFrIdx,
1835 bool Is64Bit, int FPDiff, DebugLoc dl) {
1836 // Store the return address to the appropriate stack slot.
1837 if (!FPDiff) return Chain;
1838 // Calculate the new stack slot for the return address.
1839 int SlotSize = Is64Bit ? 8 : 4;
1840 int NewReturnAddrFI =
1841 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1842 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1843 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1844 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1845 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1851 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1852 CallingConv::ID CallConv, bool isVarArg,
1854 const SmallVectorImpl<ISD::OutputArg> &Outs,
1855 const SmallVectorImpl<SDValue> &OutVals,
1856 const SmallVectorImpl<ISD::InputArg> &Ins,
1857 DebugLoc dl, SelectionDAG &DAG,
1858 SmallVectorImpl<SDValue> &InVals) const {
1859 MachineFunction &MF = DAG.getMachineFunction();
1860 bool Is64Bit = Subtarget->is64Bit();
1861 bool IsStructRet = CallIsStructReturn(Outs);
1862 bool IsSibcall = false;
1865 // Check if it's really possible to do a tail call.
1866 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1867 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1868 Outs, OutVals, Ins, DAG);
1870 // Sibcalls are automatically detected tailcalls which do not require
1872 if (!GuaranteedTailCallOpt && isTailCall)
1879 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1880 "Var args not supported with calling convention fastcc or ghc");
1882 // Analyze operands of the call, assigning locations to each operand.
1883 SmallVector<CCValAssign, 16> ArgLocs;
1884 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1885 ArgLocs, *DAG.getContext());
1886 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1888 // Get a count of how many bytes are to be pushed on the stack.
1889 unsigned NumBytes = CCInfo.getNextStackOffset();
1891 // This is a sibcall. The memory operands are available in caller's
1892 // own caller's stack.
1894 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1895 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1898 if (isTailCall && !IsSibcall) {
1899 // Lower arguments at fp - stackoffset + fpdiff.
1900 unsigned NumBytesCallerPushed =
1901 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1902 FPDiff = NumBytesCallerPushed - NumBytes;
1904 // Set the delta of movement of the returnaddr stackslot.
1905 // But only set if delta is greater than previous delta.
1906 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1907 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1911 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1913 SDValue RetAddrFrIdx;
1914 // Load return adress for tail calls.
1915 if (isTailCall && FPDiff)
1916 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1917 Is64Bit, FPDiff, dl);
1919 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1920 SmallVector<SDValue, 8> MemOpChains;
1923 // Walk the register/memloc assignments, inserting copies/loads. In the case
1924 // of tail call optimization arguments are handle later.
1925 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1926 CCValAssign &VA = ArgLocs[i];
1927 EVT RegVT = VA.getLocVT();
1928 SDValue Arg = OutVals[i];
1929 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1930 bool isByVal = Flags.isByVal();
1932 // Promote the value if needed.
1933 switch (VA.getLocInfo()) {
1934 default: llvm_unreachable("Unknown loc info!");
1935 case CCValAssign::Full: break;
1936 case CCValAssign::SExt:
1937 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1939 case CCValAssign::ZExt:
1940 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1942 case CCValAssign::AExt:
1943 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1944 // Special case: passing MMX values in XMM registers.
1945 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1946 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1947 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1949 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1951 case CCValAssign::BCvt:
1952 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1954 case CCValAssign::Indirect: {
1955 // Store the argument.
1956 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1957 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1958 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1959 MachinePointerInfo::getFixedStack(FI),
1966 if (VA.isRegLoc()) {
1967 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1968 if (isVarArg && Subtarget->isTargetWin64()) {
1969 // Win64 ABI requires argument XMM reg to be copied to the corresponding
1970 // shadow reg if callee is a varargs function.
1971 unsigned ShadowReg = 0;
1972 switch (VA.getLocReg()) {
1973 case X86::XMM0: ShadowReg = X86::RCX; break;
1974 case X86::XMM1: ShadowReg = X86::RDX; break;
1975 case X86::XMM2: ShadowReg = X86::R8; break;
1976 case X86::XMM3: ShadowReg = X86::R9; break;
1979 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1981 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1982 assert(VA.isMemLoc());
1983 if (StackPtr.getNode() == 0)
1984 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1985 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1986 dl, DAG, VA, Flags));
1990 if (!MemOpChains.empty())
1991 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1992 &MemOpChains[0], MemOpChains.size());
1994 // Build a sequence of copy-to-reg nodes chained together with token chain
1995 // and flag operands which copy the outgoing args into registers.
1997 // Tail call byval lowering might overwrite argument registers so in case of
1998 // tail call optimization the copies to registers are lowered later.
2000 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2001 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2002 RegsToPass[i].second, InFlag);
2003 InFlag = Chain.getValue(1);
2006 if (Subtarget->isPICStyleGOT()) {
2007 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2010 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2011 DAG.getNode(X86ISD::GlobalBaseReg,
2012 DebugLoc(), getPointerTy()),
2014 InFlag = Chain.getValue(1);
2016 // If we are tail calling and generating PIC/GOT style code load the
2017 // address of the callee into ECX. The value in ecx is used as target of
2018 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2019 // for tail calls on PIC/GOT architectures. Normally we would just put the
2020 // address of GOT into ebx and then call target@PLT. But for tail calls
2021 // ebx would be restored (since ebx is callee saved) before jumping to the
2024 // Note: The actual moving to ECX is done further down.
2025 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2026 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2027 !G->getGlobal()->hasProtectedVisibility())
2028 Callee = LowerGlobalAddress(Callee, DAG);
2029 else if (isa<ExternalSymbolSDNode>(Callee))
2030 Callee = LowerExternalSymbol(Callee, DAG);
2034 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2035 // From AMD64 ABI document:
2036 // For calls that may call functions that use varargs or stdargs
2037 // (prototype-less calls or calls to functions containing ellipsis (...) in
2038 // the declaration) %al is used as hidden argument to specify the number
2039 // of SSE registers used. The contents of %al do not need to match exactly
2040 // the number of registers, but must be an ubound on the number of SSE
2041 // registers used and is in the range 0 - 8 inclusive.
2043 // Count the number of XMM registers allocated.
2044 static const unsigned XMMArgRegs[] = {
2045 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2046 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2048 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2049 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2050 && "SSE registers cannot be used when SSE is disabled");
2052 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2053 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2054 InFlag = Chain.getValue(1);
2058 // For tail calls lower the arguments to the 'real' stack slot.
2060 // Force all the incoming stack arguments to be loaded from the stack
2061 // before any new outgoing arguments are stored to the stack, because the
2062 // outgoing stack slots may alias the incoming argument stack slots, and
2063 // the alias isn't otherwise explicit. This is slightly more conservative
2064 // than necessary, because it means that each store effectively depends
2065 // on every argument instead of just those arguments it would clobber.
2066 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2068 SmallVector<SDValue, 8> MemOpChains2;
2071 // Do not flag preceeding copytoreg stuff together with the following stuff.
2073 if (GuaranteedTailCallOpt) {
2074 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2075 CCValAssign &VA = ArgLocs[i];
2078 assert(VA.isMemLoc());
2079 SDValue Arg = OutVals[i];
2080 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2081 // Create frame index.
2082 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2083 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2084 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2085 FIN = DAG.getFrameIndex(FI, getPointerTy());
2087 if (Flags.isByVal()) {
2088 // Copy relative to framepointer.
2089 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2090 if (StackPtr.getNode() == 0)
2091 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2093 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2095 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2099 // Store relative to framepointer.
2100 MemOpChains2.push_back(
2101 DAG.getStore(ArgChain, dl, Arg, FIN,
2102 MachinePointerInfo::getFixedStack(FI),
2108 if (!MemOpChains2.empty())
2109 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2110 &MemOpChains2[0], MemOpChains2.size());
2112 // Copy arguments to their registers.
2113 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2114 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2115 RegsToPass[i].second, InFlag);
2116 InFlag = Chain.getValue(1);
2120 // Store the return address to the appropriate stack slot.
2121 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2125 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2126 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2127 // In the 64-bit large code model, we have to make all calls
2128 // through a register, since the call instruction's 32-bit
2129 // pc-relative offset may not be large enough to hold the whole
2131 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2132 // If the callee is a GlobalAddress node (quite common, every direct call
2133 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2136 // We should use extra load for direct calls to dllimported functions in
2138 const GlobalValue *GV = G->getGlobal();
2139 if (!GV->hasDLLImportLinkage()) {
2140 unsigned char OpFlags = 0;
2142 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2143 // external symbols most go through the PLT in PIC mode. If the symbol
2144 // has hidden or protected visibility, or if it is static or local, then
2145 // we don't need to use the PLT - we can directly call it.
2146 if (Subtarget->isTargetELF() &&
2147 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2148 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2149 OpFlags = X86II::MO_PLT;
2150 } else if (Subtarget->isPICStyleStubAny() &&
2151 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2152 Subtarget->getDarwinVers() < 9) {
2153 // PC-relative references to external symbols should go through $stub,
2154 // unless we're building with the leopard linker or later, which
2155 // automatically synthesizes these stubs.
2156 OpFlags = X86II::MO_DARWIN_STUB;
2159 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2160 G->getOffset(), OpFlags);
2162 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2163 unsigned char OpFlags = 0;
2165 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2166 // symbols should go through the PLT.
2167 if (Subtarget->isTargetELF() &&
2168 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2169 OpFlags = X86II::MO_PLT;
2170 } else if (Subtarget->isPICStyleStubAny() &&
2171 Subtarget->getDarwinVers() < 9) {
2172 // PC-relative references to external symbols should go through $stub,
2173 // unless we're building with the leopard linker or later, which
2174 // automatically synthesizes these stubs.
2175 OpFlags = X86II::MO_DARWIN_STUB;
2178 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2182 // Returns a chain & a flag for retval copy to use.
2183 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2184 SmallVector<SDValue, 8> Ops;
2186 if (!IsSibcall && isTailCall) {
2187 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2188 DAG.getIntPtrConstant(0, true), InFlag);
2189 InFlag = Chain.getValue(1);
2192 Ops.push_back(Chain);
2193 Ops.push_back(Callee);
2196 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2198 // Add argument registers to the end of the list so that they are known live
2200 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2201 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2202 RegsToPass[i].second.getValueType()));
2204 // Add an implicit use GOT pointer in EBX.
2205 if (!isTailCall && Subtarget->isPICStyleGOT())
2206 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2208 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2209 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2210 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2212 if (InFlag.getNode())
2213 Ops.push_back(InFlag);
2217 //// If this is the first return lowered for this function, add the regs
2218 //// to the liveout set for the function.
2219 // This isn't right, although it's probably harmless on x86; liveouts
2220 // should be computed from returns not tail calls. Consider a void
2221 // function making a tail call to a function returning int.
2222 return DAG.getNode(X86ISD::TC_RETURN, dl,
2223 NodeTys, &Ops[0], Ops.size());
2226 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2227 InFlag = Chain.getValue(1);
2229 // Create the CALLSEQ_END node.
2230 unsigned NumBytesForCalleeToPush;
2231 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2232 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2233 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2234 // If this is a call to a struct-return function, the callee
2235 // pops the hidden struct pointer, so we have to push it back.
2236 // This is common for Darwin/X86, Linux & Mingw32 targets.
2237 NumBytesForCalleeToPush = 4;
2239 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2241 // Returns a flag for retval copy to use.
2243 Chain = DAG.getCALLSEQ_END(Chain,
2244 DAG.getIntPtrConstant(NumBytes, true),
2245 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2248 InFlag = Chain.getValue(1);
2251 // Handle result values, copying them out of physregs into vregs that we
2253 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2254 Ins, dl, DAG, InVals);
2258 //===----------------------------------------------------------------------===//
2259 // Fast Calling Convention (tail call) implementation
2260 //===----------------------------------------------------------------------===//
2262 // Like std call, callee cleans arguments, convention except that ECX is
2263 // reserved for storing the tail called function address. Only 2 registers are
2264 // free for argument passing (inreg). Tail call optimization is performed
2266 // * tailcallopt is enabled
2267 // * caller/callee are fastcc
2268 // On X86_64 architecture with GOT-style position independent code only local
2269 // (within module) calls are supported at the moment.
2270 // To keep the stack aligned according to platform abi the function
2271 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2272 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2273 // If a tail called function callee has more arguments than the caller the
2274 // caller needs to make sure that there is room to move the RETADDR to. This is
2275 // achieved by reserving an area the size of the argument delta right after the
2276 // original REtADDR, but before the saved framepointer or the spilled registers
2277 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2289 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2290 /// for a 16 byte align requirement.
2292 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2293 SelectionDAG& DAG) const {
2294 MachineFunction &MF = DAG.getMachineFunction();
2295 const TargetMachine &TM = MF.getTarget();
2296 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2297 unsigned StackAlignment = TFI.getStackAlignment();
2298 uint64_t AlignMask = StackAlignment - 1;
2299 int64_t Offset = StackSize;
2300 uint64_t SlotSize = TD->getPointerSize();
2301 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2302 // Number smaller than 12 so just add the difference.
2303 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2305 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2306 Offset = ((~AlignMask) & Offset) + StackAlignment +
2307 (StackAlignment-SlotSize);
2312 /// MatchingStackOffset - Return true if the given stack call argument is
2313 /// already available in the same position (relatively) of the caller's
2314 /// incoming argument stack.
2316 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2317 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2318 const X86InstrInfo *TII) {
2319 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2321 if (Arg.getOpcode() == ISD::CopyFromReg) {
2322 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2323 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2325 MachineInstr *Def = MRI->getVRegDef(VR);
2328 if (!Flags.isByVal()) {
2329 if (!TII->isLoadFromStackSlot(Def, FI))
2332 unsigned Opcode = Def->getOpcode();
2333 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2334 Def->getOperand(1).isFI()) {
2335 FI = Def->getOperand(1).getIndex();
2336 Bytes = Flags.getByValSize();
2340 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2341 if (Flags.isByVal())
2342 // ByVal argument is passed in as a pointer but it's now being
2343 // dereferenced. e.g.
2344 // define @foo(%struct.X* %A) {
2345 // tail call @bar(%struct.X* byval %A)
2348 SDValue Ptr = Ld->getBasePtr();
2349 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2352 FI = FINode->getIndex();
2356 assert(FI != INT_MAX);
2357 if (!MFI->isFixedObjectIndex(FI))
2359 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2362 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2363 /// for tail call optimization. Targets which want to do tail call
2364 /// optimization should implement this function.
2366 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2367 CallingConv::ID CalleeCC,
2369 bool isCalleeStructRet,
2370 bool isCallerStructRet,
2371 const SmallVectorImpl<ISD::OutputArg> &Outs,
2372 const SmallVectorImpl<SDValue> &OutVals,
2373 const SmallVectorImpl<ISD::InputArg> &Ins,
2374 SelectionDAG& DAG) const {
2375 if (!IsTailCallConvention(CalleeCC) &&
2376 CalleeCC != CallingConv::C)
2379 // If -tailcallopt is specified, make fastcc functions tail-callable.
2380 const MachineFunction &MF = DAG.getMachineFunction();
2381 const Function *CallerF = DAG.getMachineFunction().getFunction();
2382 CallingConv::ID CallerCC = CallerF->getCallingConv();
2383 bool CCMatch = CallerCC == CalleeCC;
2385 if (GuaranteedTailCallOpt) {
2386 if (IsTailCallConvention(CalleeCC) && CCMatch)
2391 // Look for obvious safe cases to perform tail call optimization that do not
2392 // require ABI changes. This is what gcc calls sibcall.
2394 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2395 // emit a special epilogue.
2396 if (RegInfo->needsStackRealignment(MF))
2399 // Do not sibcall optimize vararg calls unless the call site is not passing
2401 if (isVarArg && !Outs.empty())
2404 // Also avoid sibcall optimization if either caller or callee uses struct
2405 // return semantics.
2406 if (isCalleeStructRet || isCallerStructRet)
2409 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2410 // Therefore if it's not used by the call it is not safe to optimize this into
2412 bool Unused = false;
2413 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2420 SmallVector<CCValAssign, 16> RVLocs;
2421 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2422 RVLocs, *DAG.getContext());
2423 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2424 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2425 CCValAssign &VA = RVLocs[i];
2426 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2431 // If the calling conventions do not match, then we'd better make sure the
2432 // results are returned in the same way as what the caller expects.
2434 SmallVector<CCValAssign, 16> RVLocs1;
2435 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2436 RVLocs1, *DAG.getContext());
2437 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2439 SmallVector<CCValAssign, 16> RVLocs2;
2440 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2441 RVLocs2, *DAG.getContext());
2442 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2444 if (RVLocs1.size() != RVLocs2.size())
2446 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2447 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2449 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2451 if (RVLocs1[i].isRegLoc()) {
2452 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2455 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2461 // If the callee takes no arguments then go on to check the results of the
2463 if (!Outs.empty()) {
2464 // Check if stack adjustment is needed. For now, do not do this if any
2465 // argument is passed on the stack.
2466 SmallVector<CCValAssign, 16> ArgLocs;
2467 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2468 ArgLocs, *DAG.getContext());
2469 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2470 if (CCInfo.getNextStackOffset()) {
2471 MachineFunction &MF = DAG.getMachineFunction();
2472 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2474 if (Subtarget->isTargetWin64())
2475 // Win64 ABI has additional complications.
2478 // Check if the arguments are already laid out in the right way as
2479 // the caller's fixed stack objects.
2480 MachineFrameInfo *MFI = MF.getFrameInfo();
2481 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2482 const X86InstrInfo *TII =
2483 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2484 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2485 CCValAssign &VA = ArgLocs[i];
2486 SDValue Arg = OutVals[i];
2487 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2488 if (VA.getLocInfo() == CCValAssign::Indirect)
2490 if (!VA.isRegLoc()) {
2491 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2498 // If the tailcall address may be in a register, then make sure it's
2499 // possible to register allocate for it. In 32-bit, the call address can
2500 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2501 // callee-saved registers are restored. These happen to be the same
2502 // registers used to pass 'inreg' arguments so watch out for those.
2503 if (!Subtarget->is64Bit() &&
2504 !isa<GlobalAddressSDNode>(Callee) &&
2505 !isa<ExternalSymbolSDNode>(Callee)) {
2506 unsigned NumInRegs = 0;
2507 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2508 CCValAssign &VA = ArgLocs[i];
2511 unsigned Reg = VA.getLocReg();
2514 case X86::EAX: case X86::EDX: case X86::ECX:
2515 if (++NumInRegs == 3)
2527 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2528 return X86::createFastISel(funcInfo);
2532 //===----------------------------------------------------------------------===//
2533 // Other Lowering Hooks
2534 //===----------------------------------------------------------------------===//
2536 static bool MayFoldLoad(SDValue Op) {
2537 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2540 static bool MayFoldIntoStore(SDValue Op) {
2541 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2544 static bool isTargetShuffle(unsigned Opcode) {
2546 default: return false;
2547 case X86ISD::PSHUFD:
2548 case X86ISD::PSHUFHW:
2549 case X86ISD::PSHUFLW:
2550 case X86ISD::SHUFPD:
2551 case X86ISD::PALIGN:
2552 case X86ISD::SHUFPS:
2553 case X86ISD::MOVLHPS:
2554 case X86ISD::MOVLHPD:
2555 case X86ISD::MOVHLPS:
2556 case X86ISD::MOVLPS:
2557 case X86ISD::MOVLPD:
2558 case X86ISD::MOVSHDUP:
2559 case X86ISD::MOVSLDUP:
2560 case X86ISD::MOVDDUP:
2563 case X86ISD::UNPCKLPS:
2564 case X86ISD::UNPCKLPD:
2565 case X86ISD::PUNPCKLWD:
2566 case X86ISD::PUNPCKLBW:
2567 case X86ISD::PUNPCKLDQ:
2568 case X86ISD::PUNPCKLQDQ:
2569 case X86ISD::UNPCKHPS:
2570 case X86ISD::UNPCKHPD:
2571 case X86ISD::PUNPCKHWD:
2572 case X86ISD::PUNPCKHBW:
2573 case X86ISD::PUNPCKHDQ:
2574 case X86ISD::PUNPCKHQDQ:
2580 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2581 SDValue V1, SelectionDAG &DAG) {
2583 default: llvm_unreachable("Unknown x86 shuffle node");
2584 case X86ISD::MOVSHDUP:
2585 case X86ISD::MOVSLDUP:
2586 case X86ISD::MOVDDUP:
2587 return DAG.getNode(Opc, dl, VT, V1);
2593 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2594 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2596 default: llvm_unreachable("Unknown x86 shuffle node");
2597 case X86ISD::PSHUFD:
2598 case X86ISD::PSHUFHW:
2599 case X86ISD::PSHUFLW:
2600 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2606 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2607 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2609 default: llvm_unreachable("Unknown x86 shuffle node");
2610 case X86ISD::PALIGN:
2611 case X86ISD::SHUFPD:
2612 case X86ISD::SHUFPS:
2613 return DAG.getNode(Opc, dl, VT, V1, V2,
2614 DAG.getConstant(TargetMask, MVT::i8));
2619 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2620 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2622 default: llvm_unreachable("Unknown x86 shuffle node");
2623 case X86ISD::MOVLHPS:
2624 case X86ISD::MOVLHPD:
2625 case X86ISD::MOVHLPS:
2626 case X86ISD::MOVLPS:
2627 case X86ISD::MOVLPD:
2630 case X86ISD::UNPCKLPS:
2631 case X86ISD::UNPCKLPD:
2632 case X86ISD::PUNPCKLWD:
2633 case X86ISD::PUNPCKLBW:
2634 case X86ISD::PUNPCKLDQ:
2635 case X86ISD::PUNPCKLQDQ:
2636 case X86ISD::UNPCKHPS:
2637 case X86ISD::UNPCKHPD:
2638 case X86ISD::PUNPCKHWD:
2639 case X86ISD::PUNPCKHBW:
2640 case X86ISD::PUNPCKHDQ:
2641 case X86ISD::PUNPCKHQDQ:
2642 return DAG.getNode(Opc, dl, VT, V1, V2);
2647 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2648 MachineFunction &MF = DAG.getMachineFunction();
2649 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2650 int ReturnAddrIndex = FuncInfo->getRAIndex();
2652 if (ReturnAddrIndex == 0) {
2653 // Set up a frame object for the return address.
2654 uint64_t SlotSize = TD->getPointerSize();
2655 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2657 FuncInfo->setRAIndex(ReturnAddrIndex);
2660 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2664 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2665 bool hasSymbolicDisplacement) {
2666 // Offset should fit into 32 bit immediate field.
2667 if (!isInt<32>(Offset))
2670 // If we don't have a symbolic displacement - we don't have any extra
2672 if (!hasSymbolicDisplacement)
2675 // FIXME: Some tweaks might be needed for medium code model.
2676 if (M != CodeModel::Small && M != CodeModel::Kernel)
2679 // For small code model we assume that latest object is 16MB before end of 31
2680 // bits boundary. We may also accept pretty large negative constants knowing
2681 // that all objects are in the positive half of address space.
2682 if (M == CodeModel::Small && Offset < 16*1024*1024)
2685 // For kernel code model we know that all object resist in the negative half
2686 // of 32bits address space. We may not accept negative offsets, since they may
2687 // be just off and we may accept pretty large positive ones.
2688 if (M == CodeModel::Kernel && Offset > 0)
2694 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2695 /// specific condition code, returning the condition code and the LHS/RHS of the
2696 /// comparison to make.
2697 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2698 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2700 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2701 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2702 // X > -1 -> X == 0, jump !sign.
2703 RHS = DAG.getConstant(0, RHS.getValueType());
2704 return X86::COND_NS;
2705 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2706 // X < 0 -> X == 0, jump on sign.
2708 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2710 RHS = DAG.getConstant(0, RHS.getValueType());
2711 return X86::COND_LE;
2715 switch (SetCCOpcode) {
2716 default: llvm_unreachable("Invalid integer condition!");
2717 case ISD::SETEQ: return X86::COND_E;
2718 case ISD::SETGT: return X86::COND_G;
2719 case ISD::SETGE: return X86::COND_GE;
2720 case ISD::SETLT: return X86::COND_L;
2721 case ISD::SETLE: return X86::COND_LE;
2722 case ISD::SETNE: return X86::COND_NE;
2723 case ISD::SETULT: return X86::COND_B;
2724 case ISD::SETUGT: return X86::COND_A;
2725 case ISD::SETULE: return X86::COND_BE;
2726 case ISD::SETUGE: return X86::COND_AE;
2730 // First determine if it is required or is profitable to flip the operands.
2732 // If LHS is a foldable load, but RHS is not, flip the condition.
2733 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2734 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2735 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2736 std::swap(LHS, RHS);
2739 switch (SetCCOpcode) {
2745 std::swap(LHS, RHS);
2749 // On a floating point condition, the flags are set as follows:
2751 // 0 | 0 | 0 | X > Y
2752 // 0 | 0 | 1 | X < Y
2753 // 1 | 0 | 0 | X == Y
2754 // 1 | 1 | 1 | unordered
2755 switch (SetCCOpcode) {
2756 default: llvm_unreachable("Condcode should be pre-legalized away");
2758 case ISD::SETEQ: return X86::COND_E;
2759 case ISD::SETOLT: // flipped
2761 case ISD::SETGT: return X86::COND_A;
2762 case ISD::SETOLE: // flipped
2764 case ISD::SETGE: return X86::COND_AE;
2765 case ISD::SETUGT: // flipped
2767 case ISD::SETLT: return X86::COND_B;
2768 case ISD::SETUGE: // flipped
2770 case ISD::SETLE: return X86::COND_BE;
2772 case ISD::SETNE: return X86::COND_NE;
2773 case ISD::SETUO: return X86::COND_P;
2774 case ISD::SETO: return X86::COND_NP;
2776 case ISD::SETUNE: return X86::COND_INVALID;
2780 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2781 /// code. Current x86 isa includes the following FP cmov instructions:
2782 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2783 static bool hasFPCMov(unsigned X86CC) {
2799 /// isFPImmLegal - Returns true if the target can instruction select the
2800 /// specified FP immediate natively. If false, the legalizer will
2801 /// materialize the FP immediate as a load from a constant pool.
2802 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2803 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2804 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2810 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2811 /// the specified range (L, H].
2812 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2813 return (Val < 0) || (Val >= Low && Val < Hi);
2816 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2817 /// specified value.
2818 static bool isUndefOrEqual(int Val, int CmpVal) {
2819 if (Val < 0 || Val == CmpVal)
2824 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2825 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2826 /// the second operand.
2827 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2828 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2829 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2830 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2831 return (Mask[0] < 2 && Mask[1] < 2);
2835 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2836 SmallVector<int, 8> M;
2838 return ::isPSHUFDMask(M, N->getValueType(0));
2841 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2842 /// is suitable for input to PSHUFHW.
2843 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2844 if (VT != MVT::v8i16)
2847 // Lower quadword copied in order or undef.
2848 for (int i = 0; i != 4; ++i)
2849 if (Mask[i] >= 0 && Mask[i] != i)
2852 // Upper quadword shuffled.
2853 for (int i = 4; i != 8; ++i)
2854 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2860 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2861 SmallVector<int, 8> M;
2863 return ::isPSHUFHWMask(M, N->getValueType(0));
2866 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2867 /// is suitable for input to PSHUFLW.
2868 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2869 if (VT != MVT::v8i16)
2872 // Upper quadword copied in order.
2873 for (int i = 4; i != 8; ++i)
2874 if (Mask[i] >= 0 && Mask[i] != i)
2877 // Lower quadword shuffled.
2878 for (int i = 0; i != 4; ++i)
2885 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2886 SmallVector<int, 8> M;
2888 return ::isPSHUFLWMask(M, N->getValueType(0));
2891 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2892 /// is suitable for input to PALIGNR.
2893 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2895 int i, e = VT.getVectorNumElements();
2897 // Do not handle v2i64 / v2f64 shuffles with palignr.
2898 if (e < 4 || !hasSSSE3)
2901 for (i = 0; i != e; ++i)
2905 // All undef, not a palignr.
2909 // Determine if it's ok to perform a palignr with only the LHS, since we
2910 // don't have access to the actual shuffle elements to see if RHS is undef.
2911 bool Unary = Mask[i] < (int)e;
2912 bool NeedsUnary = false;
2914 int s = Mask[i] - i;
2916 // Check the rest of the elements to see if they are consecutive.
2917 for (++i; i != e; ++i) {
2922 Unary = Unary && (m < (int)e);
2923 NeedsUnary = NeedsUnary || (m < s);
2925 if (NeedsUnary && !Unary)
2927 if (Unary && m != ((s+i) & (e-1)))
2929 if (!Unary && m != (s+i))
2935 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2936 SmallVector<int, 8> M;
2938 return ::isPALIGNRMask(M, N->getValueType(0), true);
2941 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2942 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2943 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2944 int NumElems = VT.getVectorNumElements();
2945 if (NumElems != 2 && NumElems != 4)
2948 int Half = NumElems / 2;
2949 for (int i = 0; i < Half; ++i)
2950 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2952 for (int i = Half; i < NumElems; ++i)
2953 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2959 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2960 SmallVector<int, 8> M;
2962 return ::isSHUFPMask(M, N->getValueType(0));
2965 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2966 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2967 /// half elements to come from vector 1 (which would equal the dest.) and
2968 /// the upper half to come from vector 2.
2969 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2970 int NumElems = VT.getVectorNumElements();
2972 if (NumElems != 2 && NumElems != 4)
2975 int Half = NumElems / 2;
2976 for (int i = 0; i < Half; ++i)
2977 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2979 for (int i = Half; i < NumElems; ++i)
2980 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2985 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2986 SmallVector<int, 8> M;
2988 return isCommutedSHUFPMask(M, N->getValueType(0));
2991 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2992 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2993 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2994 if (N->getValueType(0).getVectorNumElements() != 4)
2997 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2998 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2999 isUndefOrEqual(N->getMaskElt(1), 7) &&
3000 isUndefOrEqual(N->getMaskElt(2), 2) &&
3001 isUndefOrEqual(N->getMaskElt(3), 3);
3004 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3005 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3007 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3008 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3013 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3014 isUndefOrEqual(N->getMaskElt(1), 3) &&
3015 isUndefOrEqual(N->getMaskElt(2), 2) &&
3016 isUndefOrEqual(N->getMaskElt(3), 3);
3019 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3020 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3021 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3022 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3024 if (NumElems != 2 && NumElems != 4)
3027 for (unsigned i = 0; i < NumElems/2; ++i)
3028 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3031 for (unsigned i = NumElems/2; i < NumElems; ++i)
3032 if (!isUndefOrEqual(N->getMaskElt(i), i))
3038 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3039 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3040 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3041 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3043 if (NumElems != 2 && NumElems != 4)
3046 for (unsigned i = 0; i < NumElems/2; ++i)
3047 if (!isUndefOrEqual(N->getMaskElt(i), i))
3050 for (unsigned i = 0; i < NumElems/2; ++i)
3051 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3057 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3058 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3059 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3060 bool V2IsSplat = false) {
3061 int NumElts = VT.getVectorNumElements();
3062 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3065 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3067 int BitI1 = Mask[i+1];
3068 if (!isUndefOrEqual(BitI, j))
3071 if (!isUndefOrEqual(BitI1, NumElts))
3074 if (!isUndefOrEqual(BitI1, j + NumElts))
3081 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3082 SmallVector<int, 8> M;
3084 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3087 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3088 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3089 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3090 bool V2IsSplat = false) {
3091 int NumElts = VT.getVectorNumElements();
3092 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3095 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3097 int BitI1 = Mask[i+1];
3098 if (!isUndefOrEqual(BitI, j + NumElts/2))
3101 if (isUndefOrEqual(BitI1, NumElts))
3104 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3111 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3112 SmallVector<int, 8> M;
3114 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3117 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3118 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3120 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3121 int NumElems = VT.getVectorNumElements();
3122 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3125 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3127 int BitI1 = Mask[i+1];
3128 if (!isUndefOrEqual(BitI, j))
3130 if (!isUndefOrEqual(BitI1, j))
3136 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3137 SmallVector<int, 8> M;
3139 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3142 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3143 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3145 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3146 int NumElems = VT.getVectorNumElements();
3147 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3150 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3152 int BitI1 = Mask[i+1];
3153 if (!isUndefOrEqual(BitI, j))
3155 if (!isUndefOrEqual(BitI1, j))
3161 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3162 SmallVector<int, 8> M;
3164 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3167 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3168 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3169 /// MOVSD, and MOVD, i.e. setting the lowest element.
3170 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3171 if (VT.getVectorElementType().getSizeInBits() < 32)
3174 int NumElts = VT.getVectorNumElements();
3176 if (!isUndefOrEqual(Mask[0], NumElts))
3179 for (int i = 1; i < NumElts; ++i)
3180 if (!isUndefOrEqual(Mask[i], i))
3186 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3187 SmallVector<int, 8> M;
3189 return ::isMOVLMask(M, N->getValueType(0));
3192 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3193 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3194 /// element of vector 2 and the other elements to come from vector 1 in order.
3195 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3196 bool V2IsSplat = false, bool V2IsUndef = false) {
3197 int NumOps = VT.getVectorNumElements();
3198 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3201 if (!isUndefOrEqual(Mask[0], 0))
3204 for (int i = 1; i < NumOps; ++i)
3205 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3206 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3207 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3213 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3214 bool V2IsUndef = false) {
3215 SmallVector<int, 8> M;
3217 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3220 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3221 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3222 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3223 if (N->getValueType(0).getVectorNumElements() != 4)
3226 // Expect 1, 1, 3, 3
3227 for (unsigned i = 0; i < 2; ++i) {
3228 int Elt = N->getMaskElt(i);
3229 if (Elt >= 0 && Elt != 1)
3234 for (unsigned i = 2; i < 4; ++i) {
3235 int Elt = N->getMaskElt(i);
3236 if (Elt >= 0 && Elt != 3)
3241 // Don't use movshdup if it can be done with a shufps.
3242 // FIXME: verify that matching u, u, 3, 3 is what we want.
3246 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3247 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3248 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3249 if (N->getValueType(0).getVectorNumElements() != 4)
3252 // Expect 0, 0, 2, 2
3253 for (unsigned i = 0; i < 2; ++i)
3254 if (N->getMaskElt(i) > 0)
3258 for (unsigned i = 2; i < 4; ++i) {
3259 int Elt = N->getMaskElt(i);
3260 if (Elt >= 0 && Elt != 2)
3265 // Don't use movsldup if it can be done with a shufps.
3269 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3270 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3271 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3272 int e = N->getValueType(0).getVectorNumElements() / 2;
3274 for (int i = 0; i < e; ++i)
3275 if (!isUndefOrEqual(N->getMaskElt(i), i))
3277 for (int i = 0; i < e; ++i)
3278 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3283 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3284 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3285 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3286 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3287 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3289 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3291 for (int i = 0; i < NumOperands; ++i) {
3292 int Val = SVOp->getMaskElt(NumOperands-i-1);
3293 if (Val < 0) Val = 0;
3294 if (Val >= NumOperands) Val -= NumOperands;
3296 if (i != NumOperands - 1)
3302 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3303 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3304 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3305 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3307 // 8 nodes, but we only care about the last 4.
3308 for (unsigned i = 7; i >= 4; --i) {
3309 int Val = SVOp->getMaskElt(i);
3318 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3319 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3320 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3321 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3323 // 8 nodes, but we only care about the first 4.
3324 for (int i = 3; i >= 0; --i) {
3325 int Val = SVOp->getMaskElt(i);
3334 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3335 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3336 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3337 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3338 EVT VVT = N->getValueType(0);
3339 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3343 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3344 Val = SVOp->getMaskElt(i);
3348 return (Val - i) * EltSize;
3351 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3353 bool X86::isZeroNode(SDValue Elt) {
3354 return ((isa<ConstantSDNode>(Elt) &&
3355 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3356 (isa<ConstantFPSDNode>(Elt) &&
3357 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3360 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3361 /// their permute mask.
3362 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3363 SelectionDAG &DAG) {
3364 EVT VT = SVOp->getValueType(0);
3365 unsigned NumElems = VT.getVectorNumElements();
3366 SmallVector<int, 8> MaskVec;
3368 for (unsigned i = 0; i != NumElems; ++i) {
3369 int idx = SVOp->getMaskElt(i);
3371 MaskVec.push_back(idx);
3372 else if (idx < (int)NumElems)
3373 MaskVec.push_back(idx + NumElems);
3375 MaskVec.push_back(idx - NumElems);
3377 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3378 SVOp->getOperand(0), &MaskVec[0]);
3381 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3382 /// the two vector operands have swapped position.
3383 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3384 unsigned NumElems = VT.getVectorNumElements();
3385 for (unsigned i = 0; i != NumElems; ++i) {
3389 else if (idx < (int)NumElems)
3390 Mask[i] = idx + NumElems;
3392 Mask[i] = idx - NumElems;
3396 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3397 /// match movhlps. The lower half elements should come from upper half of
3398 /// V1 (and in order), and the upper half elements should come from the upper
3399 /// half of V2 (and in order).
3400 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3401 if (Op->getValueType(0).getVectorNumElements() != 4)
3403 for (unsigned i = 0, e = 2; i != e; ++i)
3404 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3406 for (unsigned i = 2; i != 4; ++i)
3407 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3412 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3413 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3415 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3416 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3418 N = N->getOperand(0).getNode();
3419 if (!ISD::isNON_EXTLoad(N))
3422 *LD = cast<LoadSDNode>(N);
3426 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3427 /// match movlp{s|d}. The lower half elements should come from lower half of
3428 /// V1 (and in order), and the upper half elements should come from the upper
3429 /// half of V2 (and in order). And since V1 will become the source of the
3430 /// MOVLP, it must be either a vector load or a scalar load to vector.
3431 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3432 ShuffleVectorSDNode *Op) {
3433 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3435 // Is V2 is a vector load, don't do this transformation. We will try to use
3436 // load folding shufps op.
3437 if (ISD::isNON_EXTLoad(V2))
3440 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3442 if (NumElems != 2 && NumElems != 4)
3444 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3445 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3447 for (unsigned i = NumElems/2; i != NumElems; ++i)
3448 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3453 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3455 static bool isSplatVector(SDNode *N) {
3456 if (N->getOpcode() != ISD::BUILD_VECTOR)
3459 SDValue SplatValue = N->getOperand(0);
3460 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3461 if (N->getOperand(i) != SplatValue)
3466 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3467 /// to an zero vector.
3468 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3469 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3470 SDValue V1 = N->getOperand(0);
3471 SDValue V2 = N->getOperand(1);
3472 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3473 for (unsigned i = 0; i != NumElems; ++i) {
3474 int Idx = N->getMaskElt(i);
3475 if (Idx >= (int)NumElems) {
3476 unsigned Opc = V2.getOpcode();
3477 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3479 if (Opc != ISD::BUILD_VECTOR ||
3480 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3482 } else if (Idx >= 0) {
3483 unsigned Opc = V1.getOpcode();
3484 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3486 if (Opc != ISD::BUILD_VECTOR ||
3487 !X86::isZeroNode(V1.getOperand(Idx)))
3494 /// getZeroVector - Returns a vector of specified type with all zero elements.
3496 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3498 assert(VT.isVector() && "Expected a vector type");
3500 // Always build SSE zero vectors as <4 x i32> bitcasted
3501 // to their dest type. This ensures they get CSE'd.
3503 if (VT.getSizeInBits() == 128) { // SSE
3504 if (HasSSE2) { // SSE2
3505 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3506 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3508 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3509 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3511 } else if (VT.getSizeInBits() == 256) { // AVX
3512 // 256-bit logic and arithmetic instructions in AVX are
3513 // all floating-point, no support for integer ops. Default
3514 // to emitting fp zeroed vectors then.
3515 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3516 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3517 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3519 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3522 /// getOnesVector - Returns a vector of specified type with all bits set.
3524 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3525 assert(VT.isVector() && "Expected a vector type");
3527 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3528 // type. This ensures they get CSE'd.
3529 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3531 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3532 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3536 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3537 /// that point to V2 points to its first element.
3538 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3539 EVT VT = SVOp->getValueType(0);
3540 unsigned NumElems = VT.getVectorNumElements();
3542 bool Changed = false;
3543 SmallVector<int, 8> MaskVec;
3544 SVOp->getMask(MaskVec);
3546 for (unsigned i = 0; i != NumElems; ++i) {
3547 if (MaskVec[i] > (int)NumElems) {
3548 MaskVec[i] = NumElems;
3553 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3554 SVOp->getOperand(1), &MaskVec[0]);
3555 return SDValue(SVOp, 0);
3558 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3559 /// operation of specified width.
3560 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3562 unsigned NumElems = VT.getVectorNumElements();
3563 SmallVector<int, 8> Mask;
3564 Mask.push_back(NumElems);
3565 for (unsigned i = 1; i != NumElems; ++i)
3567 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3570 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3571 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3573 unsigned NumElems = VT.getVectorNumElements();
3574 SmallVector<int, 8> Mask;
3575 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3577 Mask.push_back(i + NumElems);
3579 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3582 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3583 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3585 unsigned NumElems = VT.getVectorNumElements();
3586 unsigned Half = NumElems/2;
3587 SmallVector<int, 8> Mask;
3588 for (unsigned i = 0; i != Half; ++i) {
3589 Mask.push_back(i + Half);
3590 Mask.push_back(i + NumElems + Half);
3592 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3595 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3596 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3597 EVT PVT = MVT::v4f32;
3598 EVT VT = SV->getValueType(0);
3599 DebugLoc dl = SV->getDebugLoc();
3600 SDValue V1 = SV->getOperand(0);
3601 int NumElems = VT.getVectorNumElements();
3602 int EltNo = SV->getSplatIndex();
3604 // unpack elements to the correct location
3605 while (NumElems > 4) {
3606 if (EltNo < NumElems/2) {
3607 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3609 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3610 EltNo -= NumElems/2;
3615 // Perform the splat.
3616 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3617 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3618 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3619 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3622 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3623 /// vector of zero or undef vector. This produces a shuffle where the low
3624 /// element of V2 is swizzled into the zero/undef vector, landing at element
3625 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3626 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3627 bool isZero, bool HasSSE2,
3628 SelectionDAG &DAG) {
3629 EVT VT = V2.getValueType();
3631 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3632 unsigned NumElems = VT.getVectorNumElements();
3633 SmallVector<int, 16> MaskVec;
3634 for (unsigned i = 0; i != NumElems; ++i)
3635 // If this is the insertion idx, put the low elt of V2 here.
3636 MaskVec.push_back(i == Idx ? NumElems : i);
3637 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3640 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3641 /// element of the result of the vector shuffle.
3642 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3645 return SDValue(); // Limit search depth.
3647 SDValue V = SDValue(N, 0);
3648 EVT VT = V.getValueType();
3649 unsigned Opcode = V.getOpcode();
3651 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3652 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3653 Index = SV->getMaskElt(Index);
3656 return DAG.getUNDEF(VT.getVectorElementType());
3658 int NumElems = VT.getVectorNumElements();
3659 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3660 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3663 // Recurse into target specific vector shuffles to find scalars.
3664 if (isTargetShuffle(Opcode)) {
3665 int NumElems = VT.getVectorNumElements();
3666 SmallVector<unsigned, 16> ShuffleMask;
3670 case X86ISD::SHUFPS:
3671 case X86ISD::SHUFPD:
3672 ImmN = N->getOperand(N->getNumOperands()-1);
3673 DecodeSHUFPSMask(NumElems,
3674 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3677 case X86ISD::PUNPCKHBW:
3678 case X86ISD::PUNPCKHWD:
3679 case X86ISD::PUNPCKHDQ:
3680 case X86ISD::PUNPCKHQDQ:
3681 DecodePUNPCKHMask(NumElems, ShuffleMask);
3683 case X86ISD::UNPCKHPS:
3684 case X86ISD::UNPCKHPD:
3685 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3687 case X86ISD::PUNPCKLBW:
3688 case X86ISD::PUNPCKLWD:
3689 case X86ISD::PUNPCKLDQ:
3690 case X86ISD::PUNPCKLQDQ:
3691 DecodePUNPCKLMask(NumElems, ShuffleMask);
3693 case X86ISD::UNPCKLPS:
3694 case X86ISD::UNPCKLPD:
3695 DecodeUNPCKLPMask(NumElems, ShuffleMask);
3697 case X86ISD::MOVHLPS:
3698 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3700 case X86ISD::MOVLHPS:
3701 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3703 case X86ISD::PSHUFD:
3704 ImmN = N->getOperand(N->getNumOperands()-1);
3705 DecodePSHUFMask(NumElems,
3706 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3709 case X86ISD::PSHUFHW:
3710 ImmN = N->getOperand(N->getNumOperands()-1);
3711 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3714 case X86ISD::PSHUFLW:
3715 ImmN = N->getOperand(N->getNumOperands()-1);
3716 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3720 case X86ISD::MOVSD: {
3721 // The index 0 always comes from the first element of the second source,
3722 // this is why MOVSS and MOVSD are used in the first place. The other
3723 // elements come from the other positions of the first source vector.
3724 unsigned OpNum = (Index == 0) ? 1 : 0;
3725 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3729 assert("not implemented for target shuffle node");
3733 Index = ShuffleMask[Index];
3735 return DAG.getUNDEF(VT.getVectorElementType());
3737 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3738 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3742 // Actual nodes that may contain scalar elements
3743 if (Opcode == ISD::BIT_CONVERT) {
3744 V = V.getOperand(0);
3745 EVT SrcVT = V.getValueType();
3746 unsigned NumElems = VT.getVectorNumElements();
3748 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3752 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3753 return (Index == 0) ? V.getOperand(0)
3754 : DAG.getUNDEF(VT.getVectorElementType());
3756 if (V.getOpcode() == ISD::BUILD_VECTOR)
3757 return V.getOperand(Index);
3762 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3763 /// shuffle operation which come from a consecutively from a zero. The
3764 /// search can start in two diferent directions, from left or right.
3766 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3767 bool ZerosFromLeft, SelectionDAG &DAG) {
3770 while (i < NumElems) {
3771 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3772 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3773 if (!(Elt.getNode() &&
3774 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3782 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3783 /// MaskE correspond consecutively to elements from one of the vector operands,
3784 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3786 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3787 int OpIdx, int NumElems, unsigned &OpNum) {
3788 bool SeenV1 = false;
3789 bool SeenV2 = false;
3791 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3792 int Idx = SVOp->getMaskElt(i);
3793 // Ignore undef indicies
3802 // Only accept consecutive elements from the same vector
3803 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3807 OpNum = SeenV1 ? 0 : 1;
3811 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3812 /// logical left shift of a vector.
3813 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3814 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3815 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3816 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3817 false /* check zeros from right */, DAG);
3823 // Considering the elements in the mask that are not consecutive zeros,
3824 // check if they consecutively come from only one of the source vectors.
3826 // V1 = {X, A, B, C} 0
3828 // vector_shuffle V1, V2 <1, 2, 3, X>
3830 if (!isShuffleMaskConsecutive(SVOp,
3831 0, // Mask Start Index
3832 NumElems-NumZeros-1, // Mask End Index
3833 NumZeros, // Where to start looking in the src vector
3834 NumElems, // Number of elements in vector
3835 OpSrc)) // Which source operand ?
3840 ShVal = SVOp->getOperand(OpSrc);
3844 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3845 /// logical left shift of a vector.
3846 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3847 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3848 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3849 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3850 true /* check zeros from left */, DAG);
3856 // Considering the elements in the mask that are not consecutive zeros,
3857 // check if they consecutively come from only one of the source vectors.
3859 // 0 { A, B, X, X } = V2
3861 // vector_shuffle V1, V2 <X, X, 4, 5>
3863 if (!isShuffleMaskConsecutive(SVOp,
3864 NumZeros, // Mask Start Index
3865 NumElems-1, // Mask End Index
3866 0, // Where to start looking in the src vector
3867 NumElems, // Number of elements in vector
3868 OpSrc)) // Which source operand ?
3873 ShVal = SVOp->getOperand(OpSrc);
3877 /// isVectorShift - Returns true if the shuffle can be implemented as a
3878 /// logical left or right shift of a vector.
3879 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3880 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3881 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3882 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3888 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3890 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3891 unsigned NumNonZero, unsigned NumZero,
3893 const TargetLowering &TLI) {
3897 DebugLoc dl = Op.getDebugLoc();
3900 for (unsigned i = 0; i < 16; ++i) {
3901 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3902 if (ThisIsNonZero && First) {
3904 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3906 V = DAG.getUNDEF(MVT::v8i16);
3911 SDValue ThisElt(0, 0), LastElt(0, 0);
3912 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3913 if (LastIsNonZero) {
3914 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3915 MVT::i16, Op.getOperand(i-1));
3917 if (ThisIsNonZero) {
3918 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3919 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3920 ThisElt, DAG.getConstant(8, MVT::i8));
3922 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3926 if (ThisElt.getNode())
3927 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3928 DAG.getIntPtrConstant(i/2));
3932 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3935 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3937 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3938 unsigned NumNonZero, unsigned NumZero,
3940 const TargetLowering &TLI) {
3944 DebugLoc dl = Op.getDebugLoc();
3947 for (unsigned i = 0; i < 8; ++i) {
3948 bool isNonZero = (NonZeros & (1 << i)) != 0;
3952 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3954 V = DAG.getUNDEF(MVT::v8i16);
3957 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3958 MVT::v8i16, V, Op.getOperand(i),
3959 DAG.getIntPtrConstant(i));
3966 /// getVShift - Return a vector logical shift node.
3968 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3969 unsigned NumBits, SelectionDAG &DAG,
3970 const TargetLowering &TLI, DebugLoc dl) {
3971 EVT ShVT = MVT::v2i64;
3972 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3973 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3974 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3975 DAG.getNode(Opc, dl, ShVT, SrcOp,
3976 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3980 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3981 SelectionDAG &DAG) const {
3983 // Check if the scalar load can be widened into a vector load. And if
3984 // the address is "base + cst" see if the cst can be "absorbed" into
3985 // the shuffle mask.
3986 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3987 SDValue Ptr = LD->getBasePtr();
3988 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3990 EVT PVT = LD->getValueType(0);
3991 if (PVT != MVT::i32 && PVT != MVT::f32)
3996 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3997 FI = FINode->getIndex();
3999 } else if (Ptr.getOpcode() == ISD::ADD &&
4000 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4001 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4002 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4003 Offset = Ptr.getConstantOperandVal(1);
4004 Ptr = Ptr.getOperand(0);
4009 SDValue Chain = LD->getChain();
4010 // Make sure the stack object alignment is at least 16.
4011 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4012 if (DAG.InferPtrAlignment(Ptr) < 16) {
4013 if (MFI->isFixedObjectIndex(FI)) {
4014 // Can't change the alignment. FIXME: It's possible to compute
4015 // the exact stack offset and reference FI + adjust offset instead.
4016 // If someone *really* cares about this. That's the way to implement it.
4019 MFI->setObjectAlignment(FI, 16);
4023 // (Offset % 16) must be multiple of 4. Then address is then
4024 // Ptr + (Offset & ~15).
4027 if ((Offset % 16) & 3)
4029 int64_t StartOffset = Offset & ~15;
4031 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4032 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4034 int EltNo = (Offset - StartOffset) >> 2;
4035 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4036 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4037 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4038 LD->getPointerInfo().getWithOffset(StartOffset),
4040 // Canonicalize it to a v4i32 shuffle.
4041 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
4042 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4043 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4044 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4050 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4051 /// vector of type 'VT', see if the elements can be replaced by a single large
4052 /// load which has the same value as a build_vector whose operands are 'elts'.
4054 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4056 /// FIXME: we'd also like to handle the case where the last elements are zero
4057 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4058 /// There's even a handy isZeroNode for that purpose.
4059 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4060 DebugLoc &DL, SelectionDAG &DAG) {
4061 EVT EltVT = VT.getVectorElementType();
4062 unsigned NumElems = Elts.size();
4064 LoadSDNode *LDBase = NULL;
4065 unsigned LastLoadedElt = -1U;
4067 // For each element in the initializer, see if we've found a load or an undef.
4068 // If we don't find an initial load element, or later load elements are
4069 // non-consecutive, bail out.
4070 for (unsigned i = 0; i < NumElems; ++i) {
4071 SDValue Elt = Elts[i];
4073 if (!Elt.getNode() ||
4074 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4077 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4079 LDBase = cast<LoadSDNode>(Elt.getNode());
4083 if (Elt.getOpcode() == ISD::UNDEF)
4086 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4087 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4092 // If we have found an entire vector of loads and undefs, then return a large
4093 // load of the entire vector width starting at the base pointer. If we found
4094 // consecutive loads for the low half, generate a vzext_load node.
4095 if (LastLoadedElt == NumElems - 1) {
4096 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4097 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4098 LDBase->getPointerInfo(),
4099 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4100 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4101 LDBase->getPointerInfo(),
4102 LDBase->isVolatile(), LDBase->isNonTemporal(),
4103 LDBase->getAlignment());
4104 } else if (NumElems == 4 && LastLoadedElt == 1) {
4105 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4106 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4107 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4109 LDBase->getMemOperand());
4110 return DAG.getNode(ISD::BIT_CONVERT, DL, VT, ResNode);
4116 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4117 DebugLoc dl = Op.getDebugLoc();
4118 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4119 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4120 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4121 // is present, so AllOnes is ignored.
4122 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4123 (Op.getValueType().getSizeInBits() != 256 &&
4124 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4125 // Canonicalize this to <4 x i32> (SSE) to
4126 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4127 // eliminated on x86-32 hosts.
4128 if (Op.getValueType() == MVT::v4i32)
4131 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4132 return getOnesVector(Op.getValueType(), DAG, dl);
4133 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4136 EVT VT = Op.getValueType();
4137 EVT ExtVT = VT.getVectorElementType();
4138 unsigned EVTBits = ExtVT.getSizeInBits();
4140 unsigned NumElems = Op.getNumOperands();
4141 unsigned NumZero = 0;
4142 unsigned NumNonZero = 0;
4143 unsigned NonZeros = 0;
4144 bool IsAllConstants = true;
4145 SmallSet<SDValue, 8> Values;
4146 for (unsigned i = 0; i < NumElems; ++i) {
4147 SDValue Elt = Op.getOperand(i);
4148 if (Elt.getOpcode() == ISD::UNDEF)
4151 if (Elt.getOpcode() != ISD::Constant &&
4152 Elt.getOpcode() != ISD::ConstantFP)
4153 IsAllConstants = false;
4154 if (X86::isZeroNode(Elt))
4157 NonZeros |= (1 << i);
4162 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4163 if (NumNonZero == 0)
4164 return DAG.getUNDEF(VT);
4166 // Special case for single non-zero, non-undef, element.
4167 if (NumNonZero == 1) {
4168 unsigned Idx = CountTrailingZeros_32(NonZeros);
4169 SDValue Item = Op.getOperand(Idx);
4171 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4172 // the value are obviously zero, truncate the value to i32 and do the
4173 // insertion that way. Only do this if the value is non-constant or if the
4174 // value is a constant being inserted into element 0. It is cheaper to do
4175 // a constant pool load than it is to do a movd + shuffle.
4176 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4177 (!IsAllConstants || Idx == 0)) {
4178 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4180 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4181 EVT VecVT = MVT::v4i32;
4182 unsigned VecElts = 4;
4184 // Truncate the value (which may itself be a constant) to i32, and
4185 // convert it to a vector with movd (S2V+shuffle to zero extend).
4186 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4187 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4188 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4189 Subtarget->hasSSE2(), DAG);
4191 // Now we have our 32-bit value zero extended in the low element of
4192 // a vector. If Idx != 0, swizzle it into place.
4194 SmallVector<int, 4> Mask;
4195 Mask.push_back(Idx);
4196 for (unsigned i = 1; i != VecElts; ++i)
4198 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4199 DAG.getUNDEF(Item.getValueType()),
4202 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
4206 // If we have a constant or non-constant insertion into the low element of
4207 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4208 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4209 // depending on what the source datatype is.
4212 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4213 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4214 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4215 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4216 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4217 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4219 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4220 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4221 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4222 EVT MiddleVT = MVT::v4i32;
4223 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4224 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4225 Subtarget->hasSSE2(), DAG);
4226 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
4230 // Is it a vector logical left shift?
4231 if (NumElems == 2 && Idx == 1 &&
4232 X86::isZeroNode(Op.getOperand(0)) &&
4233 !X86::isZeroNode(Op.getOperand(1))) {
4234 unsigned NumBits = VT.getSizeInBits();
4235 return getVShift(true, VT,
4236 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4237 VT, Op.getOperand(1)),
4238 NumBits/2, DAG, *this, dl);
4241 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4244 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4245 // is a non-constant being inserted into an element other than the low one,
4246 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4247 // movd/movss) to move this into the low element, then shuffle it into
4249 if (EVTBits == 32) {
4250 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4252 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4253 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4254 Subtarget->hasSSE2(), DAG);
4255 SmallVector<int, 8> MaskVec;
4256 for (unsigned i = 0; i < NumElems; i++)
4257 MaskVec.push_back(i == Idx ? 0 : 1);
4258 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4262 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4263 if (Values.size() == 1) {
4264 if (EVTBits == 32) {
4265 // Instead of a shuffle like this:
4266 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4267 // Check if it's possible to issue this instead.
4268 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4269 unsigned Idx = CountTrailingZeros_32(NonZeros);
4270 SDValue Item = Op.getOperand(Idx);
4271 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4272 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4277 // A vector full of immediates; various special cases are already
4278 // handled, so this is best done with a single constant-pool load.
4282 // Let legalizer expand 2-wide build_vectors.
4283 if (EVTBits == 64) {
4284 if (NumNonZero == 1) {
4285 // One half is zero or undef.
4286 unsigned Idx = CountTrailingZeros_32(NonZeros);
4287 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4288 Op.getOperand(Idx));
4289 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4290 Subtarget->hasSSE2(), DAG);
4295 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4296 if (EVTBits == 8 && NumElems == 16) {
4297 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4299 if (V.getNode()) return V;
4302 if (EVTBits == 16 && NumElems == 8) {
4303 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4305 if (V.getNode()) return V;
4308 // If element VT is == 32 bits, turn it into a number of shuffles.
4309 SmallVector<SDValue, 8> V;
4311 if (NumElems == 4 && NumZero > 0) {
4312 for (unsigned i = 0; i < 4; ++i) {
4313 bool isZero = !(NonZeros & (1 << i));
4315 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4317 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4320 for (unsigned i = 0; i < 2; ++i) {
4321 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4324 V[i] = V[i*2]; // Must be a zero vector.
4327 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4330 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4333 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4338 SmallVector<int, 8> MaskVec;
4339 bool Reverse = (NonZeros & 0x3) == 2;
4340 for (unsigned i = 0; i < 2; ++i)
4341 MaskVec.push_back(Reverse ? 1-i : i);
4342 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4343 for (unsigned i = 0; i < 2; ++i)
4344 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4345 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4348 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4349 // Check for a build vector of consecutive loads.
4350 for (unsigned i = 0; i < NumElems; ++i)
4351 V[i] = Op.getOperand(i);
4353 // Check for elements which are consecutive loads.
4354 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4358 // For SSE 4.1, use insertps to put the high elements into the low element.
4359 if (getSubtarget()->hasSSE41()) {
4361 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4362 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4364 Result = DAG.getUNDEF(VT);
4366 for (unsigned i = 1; i < NumElems; ++i) {
4367 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4368 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4369 Op.getOperand(i), DAG.getIntPtrConstant(i));
4374 // Otherwise, expand into a number of unpckl*, start by extending each of
4375 // our (non-undef) elements to the full vector width with the element in the
4376 // bottom slot of the vector (which generates no code for SSE).
4377 for (unsigned i = 0; i < NumElems; ++i) {
4378 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4379 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4381 V[i] = DAG.getUNDEF(VT);
4384 // Next, we iteratively mix elements, e.g. for v4f32:
4385 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4386 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4387 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4388 unsigned EltStride = NumElems >> 1;
4389 while (EltStride != 0) {
4390 for (unsigned i = 0; i < EltStride; ++i) {
4391 // If V[i+EltStride] is undef and this is the first round of mixing,
4392 // then it is safe to just drop this shuffle: V[i] is already in the
4393 // right place, the one element (since it's the first round) being
4394 // inserted as undef can be dropped. This isn't safe for successive
4395 // rounds because they will permute elements within both vectors.
4396 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4397 EltStride == NumElems/2)
4400 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4410 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4411 // We support concatenate two MMX registers and place them in a MMX
4412 // register. This is better than doing a stack convert.
4413 DebugLoc dl = Op.getDebugLoc();
4414 EVT ResVT = Op.getValueType();
4415 assert(Op.getNumOperands() == 2);
4416 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4417 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4419 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4420 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4421 InVec = Op.getOperand(1);
4422 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4423 unsigned NumElts = ResVT.getVectorNumElements();
4424 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4425 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4426 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4428 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4429 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4430 Mask[0] = 0; Mask[1] = 2;
4431 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4433 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4436 // v8i16 shuffles - Prefer shuffles in the following order:
4437 // 1. [all] pshuflw, pshufhw, optional move
4438 // 2. [ssse3] 1 x pshufb
4439 // 3. [ssse3] 2 x pshufb + 1 x por
4440 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4442 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4443 SelectionDAG &DAG) const {
4444 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4445 SDValue V1 = SVOp->getOperand(0);
4446 SDValue V2 = SVOp->getOperand(1);
4447 DebugLoc dl = SVOp->getDebugLoc();
4448 SmallVector<int, 8> MaskVals;
4450 // Determine if more than 1 of the words in each of the low and high quadwords
4451 // of the result come from the same quadword of one of the two inputs. Undef
4452 // mask values count as coming from any quadword, for better codegen.
4453 SmallVector<unsigned, 4> LoQuad(4);
4454 SmallVector<unsigned, 4> HiQuad(4);
4455 BitVector InputQuads(4);
4456 for (unsigned i = 0; i < 8; ++i) {
4457 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4458 int EltIdx = SVOp->getMaskElt(i);
4459 MaskVals.push_back(EltIdx);
4468 InputQuads.set(EltIdx / 4);
4471 int BestLoQuad = -1;
4472 unsigned MaxQuad = 1;
4473 for (unsigned i = 0; i < 4; ++i) {
4474 if (LoQuad[i] > MaxQuad) {
4476 MaxQuad = LoQuad[i];
4480 int BestHiQuad = -1;
4482 for (unsigned i = 0; i < 4; ++i) {
4483 if (HiQuad[i] > MaxQuad) {
4485 MaxQuad = HiQuad[i];
4489 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4490 // of the two input vectors, shuffle them into one input vector so only a
4491 // single pshufb instruction is necessary. If There are more than 2 input
4492 // quads, disable the next transformation since it does not help SSSE3.
4493 bool V1Used = InputQuads[0] || InputQuads[1];
4494 bool V2Used = InputQuads[2] || InputQuads[3];
4495 if (Subtarget->hasSSSE3()) {
4496 if (InputQuads.count() == 2 && V1Used && V2Used) {
4497 BestLoQuad = InputQuads.find_first();
4498 BestHiQuad = InputQuads.find_next(BestLoQuad);
4500 if (InputQuads.count() > 2) {
4506 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4507 // the shuffle mask. If a quad is scored as -1, that means that it contains
4508 // words from all 4 input quadwords.
4510 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4511 SmallVector<int, 8> MaskV;
4512 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4513 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4514 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4515 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4516 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4517 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4519 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4520 // source words for the shuffle, to aid later transformations.
4521 bool AllWordsInNewV = true;
4522 bool InOrder[2] = { true, true };
4523 for (unsigned i = 0; i != 8; ++i) {
4524 int idx = MaskVals[i];
4526 InOrder[i/4] = false;
4527 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4529 AllWordsInNewV = false;
4533 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4534 if (AllWordsInNewV) {
4535 for (int i = 0; i != 8; ++i) {
4536 int idx = MaskVals[i];
4539 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4540 if ((idx != i) && idx < 4)
4542 if ((idx != i) && idx > 3)
4551 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4552 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4553 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4554 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4555 unsigned TargetMask = 0;
4556 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4557 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4558 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4559 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4560 V1 = NewV.getOperand(0);
4561 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4565 // If we have SSSE3, and all words of the result are from 1 input vector,
4566 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4567 // is present, fall back to case 4.
4568 if (Subtarget->hasSSSE3()) {
4569 SmallVector<SDValue,16> pshufbMask;
4571 // If we have elements from both input vectors, set the high bit of the
4572 // shuffle mask element to zero out elements that come from V2 in the V1
4573 // mask, and elements that come from V1 in the V2 mask, so that the two
4574 // results can be OR'd together.
4575 bool TwoInputs = V1Used && V2Used;
4576 for (unsigned i = 0; i != 8; ++i) {
4577 int EltIdx = MaskVals[i] * 2;
4578 if (TwoInputs && (EltIdx >= 16)) {
4579 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4580 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4583 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4584 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4586 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4587 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4588 DAG.getNode(ISD::BUILD_VECTOR, dl,
4589 MVT::v16i8, &pshufbMask[0], 16));
4591 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4593 // Calculate the shuffle mask for the second input, shuffle it, and
4594 // OR it with the first shuffled input.
4596 for (unsigned i = 0; i != 8; ++i) {
4597 int EltIdx = MaskVals[i] * 2;
4599 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4600 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4603 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4604 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4606 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4607 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4608 DAG.getNode(ISD::BUILD_VECTOR, dl,
4609 MVT::v16i8, &pshufbMask[0], 16));
4610 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4611 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4614 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4615 // and update MaskVals with new element order.
4616 BitVector InOrder(8);
4617 if (BestLoQuad >= 0) {
4618 SmallVector<int, 8> MaskV;
4619 for (int i = 0; i != 4; ++i) {
4620 int idx = MaskVals[i];
4622 MaskV.push_back(-1);
4624 } else if ((idx / 4) == BestLoQuad) {
4625 MaskV.push_back(idx & 3);
4628 MaskV.push_back(-1);
4631 for (unsigned i = 4; i != 8; ++i)
4633 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4636 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4637 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4639 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4643 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4644 // and update MaskVals with the new element order.
4645 if (BestHiQuad >= 0) {
4646 SmallVector<int, 8> MaskV;
4647 for (unsigned i = 0; i != 4; ++i)
4649 for (unsigned i = 4; i != 8; ++i) {
4650 int idx = MaskVals[i];
4652 MaskV.push_back(-1);
4654 } else if ((idx / 4) == BestHiQuad) {
4655 MaskV.push_back((idx & 3) + 4);
4658 MaskV.push_back(-1);
4661 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4664 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4665 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4667 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4671 // In case BestHi & BestLo were both -1, which means each quadword has a word
4672 // from each of the four input quadwords, calculate the InOrder bitvector now
4673 // before falling through to the insert/extract cleanup.
4674 if (BestLoQuad == -1 && BestHiQuad == -1) {
4676 for (int i = 0; i != 8; ++i)
4677 if (MaskVals[i] < 0 || MaskVals[i] == i)
4681 // The other elements are put in the right place using pextrw and pinsrw.
4682 for (unsigned i = 0; i != 8; ++i) {
4685 int EltIdx = MaskVals[i];
4688 SDValue ExtOp = (EltIdx < 8)
4689 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4690 DAG.getIntPtrConstant(EltIdx))
4691 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4692 DAG.getIntPtrConstant(EltIdx - 8));
4693 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4694 DAG.getIntPtrConstant(i));
4699 // v16i8 shuffles - Prefer shuffles in the following order:
4700 // 1. [ssse3] 1 x pshufb
4701 // 2. [ssse3] 2 x pshufb + 1 x por
4702 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4704 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4706 const X86TargetLowering &TLI) {
4707 SDValue V1 = SVOp->getOperand(0);
4708 SDValue V2 = SVOp->getOperand(1);
4709 DebugLoc dl = SVOp->getDebugLoc();
4710 SmallVector<int, 16> MaskVals;
4711 SVOp->getMask(MaskVals);
4713 // If we have SSSE3, case 1 is generated when all result bytes come from
4714 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4715 // present, fall back to case 3.
4716 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4719 for (unsigned i = 0; i < 16; ++i) {
4720 int EltIdx = MaskVals[i];
4729 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4730 if (TLI.getSubtarget()->hasSSSE3()) {
4731 SmallVector<SDValue,16> pshufbMask;
4733 // If all result elements are from one input vector, then only translate
4734 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4736 // Otherwise, we have elements from both input vectors, and must zero out
4737 // elements that come from V2 in the first mask, and V1 in the second mask
4738 // so that we can OR them together.
4739 bool TwoInputs = !(V1Only || V2Only);
4740 for (unsigned i = 0; i != 16; ++i) {
4741 int EltIdx = MaskVals[i];
4742 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4743 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4746 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4748 // If all the elements are from V2, assign it to V1 and return after
4749 // building the first pshufb.
4752 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4753 DAG.getNode(ISD::BUILD_VECTOR, dl,
4754 MVT::v16i8, &pshufbMask[0], 16));
4758 // Calculate the shuffle mask for the second input, shuffle it, and
4759 // OR it with the first shuffled input.
4761 for (unsigned i = 0; i != 16; ++i) {
4762 int EltIdx = MaskVals[i];
4764 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4767 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4769 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4770 DAG.getNode(ISD::BUILD_VECTOR, dl,
4771 MVT::v16i8, &pshufbMask[0], 16));
4772 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4775 // No SSSE3 - Calculate in place words and then fix all out of place words
4776 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4777 // the 16 different words that comprise the two doublequadword input vectors.
4778 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4779 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4780 SDValue NewV = V2Only ? V2 : V1;
4781 for (int i = 0; i != 8; ++i) {
4782 int Elt0 = MaskVals[i*2];
4783 int Elt1 = MaskVals[i*2+1];
4785 // This word of the result is all undef, skip it.
4786 if (Elt0 < 0 && Elt1 < 0)
4789 // This word of the result is already in the correct place, skip it.
4790 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4792 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4795 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4796 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4799 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4800 // using a single extract together, load it and store it.
4801 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4802 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4803 DAG.getIntPtrConstant(Elt1 / 2));
4804 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4805 DAG.getIntPtrConstant(i));
4809 // If Elt1 is defined, extract it from the appropriate source. If the
4810 // source byte is not also odd, shift the extracted word left 8 bits
4811 // otherwise clear the bottom 8 bits if we need to do an or.
4813 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4814 DAG.getIntPtrConstant(Elt1 / 2));
4815 if ((Elt1 & 1) == 0)
4816 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4817 DAG.getConstant(8, TLI.getShiftAmountTy()));
4819 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4820 DAG.getConstant(0xFF00, MVT::i16));
4822 // If Elt0 is defined, extract it from the appropriate source. If the
4823 // source byte is not also even, shift the extracted word right 8 bits. If
4824 // Elt1 was also defined, OR the extracted values together before
4825 // inserting them in the result.
4827 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4828 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4829 if ((Elt0 & 1) != 0)
4830 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4831 DAG.getConstant(8, TLI.getShiftAmountTy()));
4833 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4834 DAG.getConstant(0x00FF, MVT::i16));
4835 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4838 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4839 DAG.getIntPtrConstant(i));
4841 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4844 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4845 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4846 /// done when every pair / quad of shuffle mask elements point to elements in
4847 /// the right sequence. e.g.
4848 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4850 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4851 SelectionDAG &DAG, DebugLoc dl) {
4852 EVT VT = SVOp->getValueType(0);
4853 SDValue V1 = SVOp->getOperand(0);
4854 SDValue V2 = SVOp->getOperand(1);
4855 unsigned NumElems = VT.getVectorNumElements();
4856 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4858 switch (VT.getSimpleVT().SimpleTy) {
4859 default: assert(false && "Unexpected!");
4860 case MVT::v4f32: NewVT = MVT::v2f64; break;
4861 case MVT::v4i32: NewVT = MVT::v2i64; break;
4862 case MVT::v8i16: NewVT = MVT::v4i32; break;
4863 case MVT::v16i8: NewVT = MVT::v4i32; break;
4866 int Scale = NumElems / NewWidth;
4867 SmallVector<int, 8> MaskVec;
4868 for (unsigned i = 0; i < NumElems; i += Scale) {
4870 for (int j = 0; j < Scale; ++j) {
4871 int EltIdx = SVOp->getMaskElt(i+j);
4875 StartIdx = EltIdx - (EltIdx % Scale);
4876 if (EltIdx != StartIdx + j)
4880 MaskVec.push_back(-1);
4882 MaskVec.push_back(StartIdx / Scale);
4885 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4886 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4887 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4890 /// getVZextMovL - Return a zero-extending vector move low node.
4892 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4893 SDValue SrcOp, SelectionDAG &DAG,
4894 const X86Subtarget *Subtarget, DebugLoc dl) {
4895 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4896 LoadSDNode *LD = NULL;
4897 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4898 LD = dyn_cast<LoadSDNode>(SrcOp);
4900 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4902 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4903 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4904 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4905 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4906 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4908 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4909 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4910 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4911 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4919 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4920 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4921 DAG.getNode(ISD::BIT_CONVERT, dl,
4925 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4928 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4929 SDValue V1 = SVOp->getOperand(0);
4930 SDValue V2 = SVOp->getOperand(1);
4931 DebugLoc dl = SVOp->getDebugLoc();
4932 EVT VT = SVOp->getValueType(0);
4934 SmallVector<std::pair<int, int>, 8> Locs;
4936 SmallVector<int, 8> Mask1(4U, -1);
4937 SmallVector<int, 8> PermMask;
4938 SVOp->getMask(PermMask);
4942 for (unsigned i = 0; i != 4; ++i) {
4943 int Idx = PermMask[i];
4945 Locs[i] = std::make_pair(-1, -1);
4947 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4949 Locs[i] = std::make_pair(0, NumLo);
4953 Locs[i] = std::make_pair(1, NumHi);
4955 Mask1[2+NumHi] = Idx;
4961 if (NumLo <= 2 && NumHi <= 2) {
4962 // If no more than two elements come from either vector. This can be
4963 // implemented with two shuffles. First shuffle gather the elements.
4964 // The second shuffle, which takes the first shuffle as both of its
4965 // vector operands, put the elements into the right order.
4966 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4968 SmallVector<int, 8> Mask2(4U, -1);
4970 for (unsigned i = 0; i != 4; ++i) {
4971 if (Locs[i].first == -1)
4974 unsigned Idx = (i < 2) ? 0 : 4;
4975 Idx += Locs[i].first * 2 + Locs[i].second;
4980 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4981 } else if (NumLo == 3 || NumHi == 3) {
4982 // Otherwise, we must have three elements from one vector, call it X, and
4983 // one element from the other, call it Y. First, use a shufps to build an
4984 // intermediate vector with the one element from Y and the element from X
4985 // that will be in the same half in the final destination (the indexes don't
4986 // matter). Then, use a shufps to build the final vector, taking the half
4987 // containing the element from Y from the intermediate, and the other half
4990 // Normalize it so the 3 elements come from V1.
4991 CommuteVectorShuffleMask(PermMask, VT);
4995 // Find the element from V2.
4997 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4998 int Val = PermMask[HiIndex];
5005 Mask1[0] = PermMask[HiIndex];
5007 Mask1[2] = PermMask[HiIndex^1];
5009 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5012 Mask1[0] = PermMask[0];
5013 Mask1[1] = PermMask[1];
5014 Mask1[2] = HiIndex & 1 ? 6 : 4;
5015 Mask1[3] = HiIndex & 1 ? 4 : 6;
5016 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5018 Mask1[0] = HiIndex & 1 ? 2 : 0;
5019 Mask1[1] = HiIndex & 1 ? 0 : 2;
5020 Mask1[2] = PermMask[2];
5021 Mask1[3] = PermMask[3];
5026 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5030 // Break it into (shuffle shuffle_hi, shuffle_lo).
5032 SmallVector<int,8> LoMask(4U, -1);
5033 SmallVector<int,8> HiMask(4U, -1);
5035 SmallVector<int,8> *MaskPtr = &LoMask;
5036 unsigned MaskIdx = 0;
5039 for (unsigned i = 0; i != 4; ++i) {
5046 int Idx = PermMask[i];
5048 Locs[i] = std::make_pair(-1, -1);
5049 } else if (Idx < 4) {
5050 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5051 (*MaskPtr)[LoIdx] = Idx;
5054 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5055 (*MaskPtr)[HiIdx] = Idx;
5060 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5061 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5062 SmallVector<int, 8> MaskOps;
5063 for (unsigned i = 0; i != 4; ++i) {
5064 if (Locs[i].first == -1) {
5065 MaskOps.push_back(-1);
5067 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5068 MaskOps.push_back(Idx);
5071 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5074 static bool MayFoldVectorLoad(SDValue V) {
5075 if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5076 V = V.getOperand(0);
5077 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5078 V = V.getOperand(0);
5084 // FIXME: the version above should always be used. Since there's
5085 // a bug where several vector shuffles can't be folded because the
5086 // DAG is not updated during lowering and a node claims to have two
5087 // uses while it only has one, use this version, and let isel match
5088 // another instruction if the load really happens to have more than
5089 // one use. Remove this version after this bug get fixed.
5090 // rdar://8434668, PR8156
5091 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5092 if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5093 V = V.getOperand(0);
5094 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5095 V = V.getOperand(0);
5096 if (ISD::isNormalLoad(V.getNode()))
5101 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5102 /// a vector extract, and if both can be later optimized into a single load.
5103 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5104 /// here because otherwise a target specific shuffle node is going to be
5105 /// emitted for this shuffle, and the optimization not done.
5106 /// FIXME: This is probably not the best approach, but fix the problem
5107 /// until the right path is decided.
5109 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5110 const TargetLowering &TLI) {
5111 EVT VT = V.getValueType();
5112 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5114 // Be sure that the vector shuffle is present in a pattern like this:
5115 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5119 SDNode *N = *V.getNode()->use_begin();
5120 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5123 SDValue EltNo = N->getOperand(1);
5124 if (!isa<ConstantSDNode>(EltNo))
5127 // If the bit convert changed the number of elements, it is unsafe
5128 // to examine the mask.
5129 bool HasShuffleIntoBitcast = false;
5130 if (V.getOpcode() == ISD::BIT_CONVERT) {
5131 EVT SrcVT = V.getOperand(0).getValueType();
5132 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5134 V = V.getOperand(0);
5135 HasShuffleIntoBitcast = true;
5138 // Select the input vector, guarding against out of range extract vector.
5139 unsigned NumElems = VT.getVectorNumElements();
5140 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5141 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5142 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5144 // Skip one more bit_convert if necessary
5145 if (V.getOpcode() == ISD::BIT_CONVERT)
5146 V = V.getOperand(0);
5148 if (ISD::isNormalLoad(V.getNode())) {
5149 // Is the original load suitable?
5150 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5152 // FIXME: avoid the multi-use bug that is preventing lots of
5153 // of foldings to be detected, this is still wrong of course, but
5154 // give the temporary desired behavior, and if it happens that
5155 // the load has real more uses, during isel it will not fold, and
5156 // will generate poor code.
5157 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5160 if (!HasShuffleIntoBitcast)
5163 // If there's a bitcast before the shuffle, check if the load type and
5164 // alignment is valid.
5165 unsigned Align = LN0->getAlignment();
5167 TLI.getTargetData()->getABITypeAlignment(
5168 VT.getTypeForEVT(*DAG.getContext()));
5170 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5178 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5179 EVT VT = Op.getValueType();
5181 // Canonizalize to v2f64.
5182 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, V1);
5183 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5184 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5189 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5191 SDValue V1 = Op.getOperand(0);
5192 SDValue V2 = Op.getOperand(1);
5193 EVT VT = Op.getValueType();
5195 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5197 if (HasSSE2 && VT == MVT::v2f64)
5198 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5201 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5205 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5206 SDValue V1 = Op.getOperand(0);
5207 SDValue V2 = Op.getOperand(1);
5208 EVT VT = Op.getValueType();
5210 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5211 "unsupported shuffle type");
5213 if (V2.getOpcode() == ISD::UNDEF)
5217 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5221 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5222 SDValue V1 = Op.getOperand(0);
5223 SDValue V2 = Op.getOperand(1);
5224 EVT VT = Op.getValueType();
5225 unsigned NumElems = VT.getVectorNumElements();
5227 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5228 // operand of these instructions is only memory, so check if there's a
5229 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5231 bool CanFoldLoad = false;
5233 // Trivial case, when V2 comes from a load.
5234 if (MayFoldVectorLoad(V2))
5237 // When V1 is a load, it can be folded later into a store in isel, example:
5238 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5240 // (MOVLPSmr addr:$src1, VR128:$src2)
5241 // So, recognize this potential and also use MOVLPS or MOVLPD
5242 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5246 if (HasSSE2 && NumElems == 2)
5247 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5250 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5253 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5254 // movl and movlp will both match v2i64, but v2i64 is never matched by
5255 // movl earlier because we make it strict to avoid messing with the movlp load
5256 // folding logic (see the code above getMOVLP call). Match it here then,
5257 // this is horrible, but will stay like this until we move all shuffle
5258 // matching to x86 specific nodes. Note that for the 1st condition all
5259 // types are matched with movsd.
5260 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5261 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5263 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5266 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5268 // Invert the operand order and use SHUFPS to match it.
5269 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5270 X86::getShuffleSHUFImmediate(SVOp), DAG);
5273 static inline unsigned getUNPCKLOpcode(EVT VT) {
5274 switch(VT.getSimpleVT().SimpleTy) {
5275 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5276 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5277 case MVT::v4f32: return X86ISD::UNPCKLPS;
5278 case MVT::v2f64: return X86ISD::UNPCKLPD;
5279 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5280 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5282 llvm_unreachable("Unknow type for unpckl");
5287 static inline unsigned getUNPCKHOpcode(EVT VT) {
5288 switch(VT.getSimpleVT().SimpleTy) {
5289 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5290 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5291 case MVT::v4f32: return X86ISD::UNPCKHPS;
5292 case MVT::v2f64: return X86ISD::UNPCKHPD;
5293 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5294 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5296 llvm_unreachable("Unknow type for unpckh");
5302 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5303 const TargetLowering &TLI,
5304 const X86Subtarget *Subtarget) {
5305 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5306 EVT VT = Op.getValueType();
5307 DebugLoc dl = Op.getDebugLoc();
5308 SDValue V1 = Op.getOperand(0);
5309 SDValue V2 = Op.getOperand(1);
5311 if (isZeroShuffle(SVOp))
5312 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5314 // Handle splat operations
5315 if (SVOp->isSplat()) {
5316 // Special case, this is the only place now where it's
5317 // allowed to return a vector_shuffle operation without
5318 // using a target specific node, because *hopefully* it
5319 // will be optimized away by the dag combiner.
5320 if (VT.getVectorNumElements() <= 4 &&
5321 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5324 // Handle splats by matching through known masks
5325 if (VT.getVectorNumElements() <= 4)
5328 // Canonicalize all of the remaining to v4f32.
5329 return PromoteSplat(SVOp, DAG);
5332 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5334 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5335 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5336 if (NewOp.getNode())
5337 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, NewOp);
5338 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5339 // FIXME: Figure out a cleaner way to do this.
5340 // Try to make use of movq to zero out the top part.
5341 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5342 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5343 if (NewOp.getNode()) {
5344 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5345 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5346 DAG, Subtarget, dl);
5348 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5349 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5350 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5351 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5352 DAG, Subtarget, dl);
5359 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5360 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5361 SDValue V1 = Op.getOperand(0);
5362 SDValue V2 = Op.getOperand(1);
5363 EVT VT = Op.getValueType();
5364 DebugLoc dl = Op.getDebugLoc();
5365 unsigned NumElems = VT.getVectorNumElements();
5366 bool isMMX = VT.getSizeInBits() == 64;
5367 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5368 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5369 bool V1IsSplat = false;
5370 bool V2IsSplat = false;
5371 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5372 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5373 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5374 MachineFunction &MF = DAG.getMachineFunction();
5375 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5377 // Shuffle operations on MMX not supported.
5381 // Vector shuffle lowering takes 3 steps:
5383 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5384 // narrowing and commutation of operands should be handled.
5385 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5387 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5388 // so the shuffle can be broken into other shuffles and the legalizer can
5389 // try the lowering again.
5391 // The general ideia is that no vector_shuffle operation should be left to
5392 // be matched during isel, all of them must be converted to a target specific
5395 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5396 // narrowing and commutation of operands should be handled. The actual code
5397 // doesn't include all of those, work in progress...
5398 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5399 if (NewOp.getNode())
5402 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5403 // unpckh_undef). Only use pshufd if speed is more important than size.
5404 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5405 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5406 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5407 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5408 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5409 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5411 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5412 RelaxedMayFoldVectorLoad(V1))
5413 return getMOVDDup(Op, dl, V1, DAG);
5415 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5416 return getMOVHighToLow(Op, dl, DAG);
5418 // Use to match splats
5419 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5420 (VT == MVT::v2f64 || VT == MVT::v2i64))
5421 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5423 if (X86::isPSHUFDMask(SVOp)) {
5424 // The actual implementation will match the mask in the if above and then
5425 // during isel it can match several different instructions, not only pshufd
5426 // as its name says, sad but true, emulate the behavior for now...
5427 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5428 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5430 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5432 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5433 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5435 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5436 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5439 if (VT == MVT::v4f32)
5440 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5444 // Check if this can be converted into a logical shift.
5445 bool isLeft = false;
5448 bool isShift = getSubtarget()->hasSSE2() &&
5449 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5450 if (isShift && ShVal.hasOneUse()) {
5451 // If the shifted value has multiple uses, it may be cheaper to use
5452 // v_set0 + movlhps or movhlps, etc.
5453 EVT EltVT = VT.getVectorElementType();
5454 ShAmt *= EltVT.getSizeInBits();
5455 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5458 if (X86::isMOVLMask(SVOp)) {
5461 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5462 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5463 if (!X86::isMOVLPMask(SVOp)) {
5464 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5465 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5467 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5468 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5472 // FIXME: fold these into legal mask.
5473 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5474 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5476 if (X86::isMOVHLPSMask(SVOp))
5477 return getMOVHighToLow(Op, dl, DAG);
5479 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5480 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5482 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5483 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5485 if (X86::isMOVLPMask(SVOp))
5486 return getMOVLP(Op, dl, DAG, HasSSE2);
5488 if (ShouldXformToMOVHLPS(SVOp) ||
5489 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5490 return CommuteVectorShuffle(SVOp, DAG);
5493 // No better options. Use a vshl / vsrl.
5494 EVT EltVT = VT.getVectorElementType();
5495 ShAmt *= EltVT.getSizeInBits();
5496 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5499 bool Commuted = false;
5500 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5501 // 1,1,1,1 -> v8i16 though.
5502 V1IsSplat = isSplatVector(V1.getNode());
5503 V2IsSplat = isSplatVector(V2.getNode());
5505 // Canonicalize the splat or undef, if present, to be on the RHS.
5506 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5507 Op = CommuteVectorShuffle(SVOp, DAG);
5508 SVOp = cast<ShuffleVectorSDNode>(Op);
5509 V1 = SVOp->getOperand(0);
5510 V2 = SVOp->getOperand(1);
5511 std::swap(V1IsSplat, V2IsSplat);
5512 std::swap(V1IsUndef, V2IsUndef);
5516 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5517 // Shuffling low element of v1 into undef, just return v1.
5520 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5521 // the instruction selector will not match, so get a canonical MOVL with
5522 // swapped operands to undo the commute.
5523 return getMOVL(DAG, dl, VT, V2, V1);
5526 if (X86::isUNPCKLMask(SVOp))
5527 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5529 if (X86::isUNPCKHMask(SVOp))
5530 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5533 // Normalize mask so all entries that point to V2 points to its first
5534 // element then try to match unpck{h|l} again. If match, return a
5535 // new vector_shuffle with the corrected mask.
5536 SDValue NewMask = NormalizeMask(SVOp, DAG);
5537 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5538 if (NSVOp != SVOp) {
5539 if (X86::isUNPCKLMask(NSVOp, true)) {
5541 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5548 // Commute is back and try unpck* again.
5549 // FIXME: this seems wrong.
5550 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5551 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5553 if (X86::isUNPCKLMask(NewSVOp))
5554 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5556 if (X86::isUNPCKHMask(NewSVOp))
5557 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5560 // Normalize the node to match x86 shuffle ops if needed
5561 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5562 return CommuteVectorShuffle(SVOp, DAG);
5564 // The checks below are all present in isShuffleMaskLegal, but they are
5565 // inlined here right now to enable us to directly emit target specific
5566 // nodes, and remove one by one until they don't return Op anymore.
5567 SmallVector<int, 16> M;
5570 if (isPALIGNRMask(M, VT, HasSSSE3))
5571 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5572 X86::getShufflePALIGNRImmediate(SVOp),
5575 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5576 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5577 if (VT == MVT::v2f64)
5578 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5579 if (VT == MVT::v2i64)
5580 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5583 if (isPSHUFHWMask(M, VT))
5584 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5585 X86::getShufflePSHUFHWImmediate(SVOp),
5588 if (isPSHUFLWMask(M, VT))
5589 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5590 X86::getShufflePSHUFLWImmediate(SVOp),
5593 if (isSHUFPMask(M, VT)) {
5594 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5595 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5596 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5598 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5599 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5603 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5604 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5605 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5606 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5607 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5608 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5610 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5611 if (VT == MVT::v8i16) {
5612 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5613 if (NewOp.getNode())
5617 if (VT == MVT::v16i8) {
5618 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5619 if (NewOp.getNode())
5623 // Handle all 4 wide cases with a number of shuffles.
5625 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5631 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5632 SelectionDAG &DAG) const {
5633 EVT VT = Op.getValueType();
5634 DebugLoc dl = Op.getDebugLoc();
5635 if (VT.getSizeInBits() == 8) {
5636 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5637 Op.getOperand(0), Op.getOperand(1));
5638 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5639 DAG.getValueType(VT));
5640 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5641 } else if (VT.getSizeInBits() == 16) {
5642 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5643 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5645 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5646 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5647 DAG.getNode(ISD::BIT_CONVERT, dl,
5651 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5652 Op.getOperand(0), Op.getOperand(1));
5653 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5654 DAG.getValueType(VT));
5655 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5656 } else if (VT == MVT::f32) {
5657 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5658 // the result back to FR32 register. It's only worth matching if the
5659 // result has a single use which is a store or a bitcast to i32. And in
5660 // the case of a store, it's not worth it if the index is a constant 0,
5661 // because a MOVSSmr can be used instead, which is smaller and faster.
5662 if (!Op.hasOneUse())
5664 SDNode *User = *Op.getNode()->use_begin();
5665 if ((User->getOpcode() != ISD::STORE ||
5666 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5667 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5668 (User->getOpcode() != ISD::BIT_CONVERT ||
5669 User->getValueType(0) != MVT::i32))
5671 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5672 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
5675 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
5676 } else if (VT == MVT::i32) {
5677 // ExtractPS works with constant index.
5678 if (isa<ConstantSDNode>(Op.getOperand(1)))
5686 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5687 SelectionDAG &DAG) const {
5688 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5691 if (Subtarget->hasSSE41()) {
5692 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5697 EVT VT = Op.getValueType();
5698 DebugLoc dl = Op.getDebugLoc();
5699 // TODO: handle v16i8.
5700 if (VT.getSizeInBits() == 16) {
5701 SDValue Vec = Op.getOperand(0);
5702 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5704 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5705 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5706 DAG.getNode(ISD::BIT_CONVERT, dl,
5709 // Transform it so it match pextrw which produces a 32-bit result.
5710 EVT EltVT = MVT::i32;
5711 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5712 Op.getOperand(0), Op.getOperand(1));
5713 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5714 DAG.getValueType(VT));
5715 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5716 } else if (VT.getSizeInBits() == 32) {
5717 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5721 // SHUFPS the element to the lowest double word, then movss.
5722 int Mask[4] = { Idx, -1, -1, -1 };
5723 EVT VVT = Op.getOperand(0).getValueType();
5724 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5725 DAG.getUNDEF(VVT), Mask);
5726 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5727 DAG.getIntPtrConstant(0));
5728 } else if (VT.getSizeInBits() == 64) {
5729 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5730 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5731 // to match extract_elt for f64.
5732 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5736 // UNPCKHPD the element to the lowest double word, then movsd.
5737 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5738 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5739 int Mask[2] = { 1, -1 };
5740 EVT VVT = Op.getOperand(0).getValueType();
5741 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5742 DAG.getUNDEF(VVT), Mask);
5743 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5744 DAG.getIntPtrConstant(0));
5751 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5752 SelectionDAG &DAG) const {
5753 EVT VT = Op.getValueType();
5754 EVT EltVT = VT.getVectorElementType();
5755 DebugLoc dl = Op.getDebugLoc();
5757 SDValue N0 = Op.getOperand(0);
5758 SDValue N1 = Op.getOperand(1);
5759 SDValue N2 = Op.getOperand(2);
5761 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5762 isa<ConstantSDNode>(N2)) {
5764 if (VT == MVT::v8i16)
5765 Opc = X86ISD::PINSRW;
5766 else if (VT == MVT::v16i8)
5767 Opc = X86ISD::PINSRB;
5769 Opc = X86ISD::PINSRB;
5771 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5773 if (N1.getValueType() != MVT::i32)
5774 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5775 if (N2.getValueType() != MVT::i32)
5776 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5777 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5778 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5779 // Bits [7:6] of the constant are the source select. This will always be
5780 // zero here. The DAG Combiner may combine an extract_elt index into these
5781 // bits. For example (insert (extract, 3), 2) could be matched by putting
5782 // the '3' into bits [7:6] of X86ISD::INSERTPS.
5783 // Bits [5:4] of the constant are the destination select. This is the
5784 // value of the incoming immediate.
5785 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
5786 // combine either bitwise AND or insert of float 0.0 to set these bits.
5787 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5788 // Create this as a scalar to vector..
5789 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5790 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5791 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5792 // PINSR* works with constant index.
5799 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5800 EVT VT = Op.getValueType();
5801 EVT EltVT = VT.getVectorElementType();
5803 if (Subtarget->hasSSE41())
5804 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5806 if (EltVT == MVT::i8)
5809 DebugLoc dl = Op.getDebugLoc();
5810 SDValue N0 = Op.getOperand(0);
5811 SDValue N1 = Op.getOperand(1);
5812 SDValue N2 = Op.getOperand(2);
5814 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5815 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5816 // as its second argument.
5817 if (N1.getValueType() != MVT::i32)
5818 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5819 if (N2.getValueType() != MVT::i32)
5820 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5821 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5827 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5828 DebugLoc dl = Op.getDebugLoc();
5830 if (Op.getValueType() == MVT::v1i64 &&
5831 Op.getOperand(0).getValueType() == MVT::i64)
5832 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5834 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5835 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5836 "Expected an SSE type!");
5837 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5838 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5841 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5842 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5843 // one of the above mentioned nodes. It has to be wrapped because otherwise
5844 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5845 // be used to form addressing mode. These wrapped nodes will be selected
5848 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5849 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5851 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5853 unsigned char OpFlag = 0;
5854 unsigned WrapperKind = X86ISD::Wrapper;
5855 CodeModel::Model M = getTargetMachine().getCodeModel();
5857 if (Subtarget->isPICStyleRIPRel() &&
5858 (M == CodeModel::Small || M == CodeModel::Kernel))
5859 WrapperKind = X86ISD::WrapperRIP;
5860 else if (Subtarget->isPICStyleGOT())
5861 OpFlag = X86II::MO_GOTOFF;
5862 else if (Subtarget->isPICStyleStubPIC())
5863 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5865 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5867 CP->getOffset(), OpFlag);
5868 DebugLoc DL = CP->getDebugLoc();
5869 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5870 // With PIC, the address is actually $g + Offset.
5872 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5873 DAG.getNode(X86ISD::GlobalBaseReg,
5874 DebugLoc(), getPointerTy()),
5881 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5882 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5884 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5886 unsigned char OpFlag = 0;
5887 unsigned WrapperKind = X86ISD::Wrapper;
5888 CodeModel::Model M = getTargetMachine().getCodeModel();
5890 if (Subtarget->isPICStyleRIPRel() &&
5891 (M == CodeModel::Small || M == CodeModel::Kernel))
5892 WrapperKind = X86ISD::WrapperRIP;
5893 else if (Subtarget->isPICStyleGOT())
5894 OpFlag = X86II::MO_GOTOFF;
5895 else if (Subtarget->isPICStyleStubPIC())
5896 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5898 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5900 DebugLoc DL = JT->getDebugLoc();
5901 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5903 // With PIC, the address is actually $g + Offset.
5905 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5906 DAG.getNode(X86ISD::GlobalBaseReg,
5907 DebugLoc(), getPointerTy()),
5915 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5916 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5918 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5920 unsigned char OpFlag = 0;
5921 unsigned WrapperKind = X86ISD::Wrapper;
5922 CodeModel::Model M = getTargetMachine().getCodeModel();
5924 if (Subtarget->isPICStyleRIPRel() &&
5925 (M == CodeModel::Small || M == CodeModel::Kernel))
5926 WrapperKind = X86ISD::WrapperRIP;
5927 else if (Subtarget->isPICStyleGOT())
5928 OpFlag = X86II::MO_GOTOFF;
5929 else if (Subtarget->isPICStyleStubPIC())
5930 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5932 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5934 DebugLoc DL = Op.getDebugLoc();
5935 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5938 // With PIC, the address is actually $g + Offset.
5939 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5940 !Subtarget->is64Bit()) {
5941 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5942 DAG.getNode(X86ISD::GlobalBaseReg,
5943 DebugLoc(), getPointerTy()),
5951 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5952 // Create the TargetBlockAddressAddress node.
5953 unsigned char OpFlags =
5954 Subtarget->ClassifyBlockAddressReference();
5955 CodeModel::Model M = getTargetMachine().getCodeModel();
5956 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5957 DebugLoc dl = Op.getDebugLoc();
5958 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5959 /*isTarget=*/true, OpFlags);
5961 if (Subtarget->isPICStyleRIPRel() &&
5962 (M == CodeModel::Small || M == CodeModel::Kernel))
5963 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5965 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5967 // With PIC, the address is actually $g + Offset.
5968 if (isGlobalRelativeToPICBase(OpFlags)) {
5969 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5970 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5978 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5980 SelectionDAG &DAG) const {
5981 // Create the TargetGlobalAddress node, folding in the constant
5982 // offset if it is legal.
5983 unsigned char OpFlags =
5984 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5985 CodeModel::Model M = getTargetMachine().getCodeModel();
5987 if (OpFlags == X86II::MO_NO_FLAG &&
5988 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5989 // A direct static reference to a global.
5990 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5993 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5996 if (Subtarget->isPICStyleRIPRel() &&
5997 (M == CodeModel::Small || M == CodeModel::Kernel))
5998 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6000 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6002 // With PIC, the address is actually $g + Offset.
6003 if (isGlobalRelativeToPICBase(OpFlags)) {
6004 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6005 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6009 // For globals that require a load from a stub to get the address, emit the
6011 if (isGlobalStubReference(OpFlags))
6012 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6013 MachinePointerInfo::getGOT(), false, false, 0);
6015 // If there was a non-zero offset that we didn't fold, create an explicit
6018 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6019 DAG.getConstant(Offset, getPointerTy()));
6025 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6026 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6027 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6028 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6032 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6033 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6034 unsigned char OperandFlags) {
6035 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6036 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6037 DebugLoc dl = GA->getDebugLoc();
6038 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6039 GA->getValueType(0),
6043 SDValue Ops[] = { Chain, TGA, *InFlag };
6044 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6046 SDValue Ops[] = { Chain, TGA };
6047 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6050 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6051 MFI->setAdjustsStack(true);
6053 SDValue Flag = Chain.getValue(1);
6054 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6057 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6059 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6062 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6063 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6064 DAG.getNode(X86ISD::GlobalBaseReg,
6065 DebugLoc(), PtrVT), InFlag);
6066 InFlag = Chain.getValue(1);
6068 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6071 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6073 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6075 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6076 X86::RAX, X86II::MO_TLSGD);
6079 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6080 // "local exec" model.
6081 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6082 const EVT PtrVT, TLSModel::Model model,
6084 DebugLoc dl = GA->getDebugLoc();
6086 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6087 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6088 is64Bit ? 257 : 256));
6090 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6091 DAG.getIntPtrConstant(0),
6092 MachinePointerInfo(Ptr), false, false, 0);
6094 unsigned char OperandFlags = 0;
6095 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6097 unsigned WrapperKind = X86ISD::Wrapper;
6098 if (model == TLSModel::LocalExec) {
6099 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6100 } else if (is64Bit) {
6101 assert(model == TLSModel::InitialExec);
6102 OperandFlags = X86II::MO_GOTTPOFF;
6103 WrapperKind = X86ISD::WrapperRIP;
6105 assert(model == TLSModel::InitialExec);
6106 OperandFlags = X86II::MO_INDNTPOFF;
6109 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6111 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6112 GA->getValueType(0),
6113 GA->getOffset(), OperandFlags);
6114 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6116 if (model == TLSModel::InitialExec)
6117 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6118 MachinePointerInfo::getGOT(), false, false, 0);
6120 // The address of the thread local variable is the add of the thread
6121 // pointer with the offset of the variable.
6122 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6126 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6128 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6129 const GlobalValue *GV = GA->getGlobal();
6131 if (Subtarget->isTargetELF()) {
6132 // TODO: implement the "local dynamic" model
6133 // TODO: implement the "initial exec"model for pic executables
6135 // If GV is an alias then use the aliasee for determining
6136 // thread-localness.
6137 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6138 GV = GA->resolveAliasedGlobal(false);
6140 TLSModel::Model model
6141 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6144 case TLSModel::GeneralDynamic:
6145 case TLSModel::LocalDynamic: // not implemented
6146 if (Subtarget->is64Bit())
6147 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6148 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6150 case TLSModel::InitialExec:
6151 case TLSModel::LocalExec:
6152 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6153 Subtarget->is64Bit());
6155 } else if (Subtarget->isTargetDarwin()) {
6156 // Darwin only has one model of TLS. Lower to that.
6157 unsigned char OpFlag = 0;
6158 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6159 X86ISD::WrapperRIP : X86ISD::Wrapper;
6161 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6163 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6164 !Subtarget->is64Bit();
6166 OpFlag = X86II::MO_TLVP_PIC_BASE;
6168 OpFlag = X86II::MO_TLVP;
6169 DebugLoc DL = Op.getDebugLoc();
6170 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6172 GA->getOffset(), OpFlag);
6173 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6175 // With PIC32, the address is actually $g + Offset.
6177 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6178 DAG.getNode(X86ISD::GlobalBaseReg,
6179 DebugLoc(), getPointerTy()),
6182 // Lowering the machine isd will make sure everything is in the right
6184 SDValue Args[] = { Offset };
6185 SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
6187 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6188 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6189 MFI->setAdjustsStack(true);
6191 // And our return value (tls address) is in the standard call return value
6193 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6194 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6198 "TLS not implemented for this target.");
6200 llvm_unreachable("Unreachable");
6205 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6206 /// take a 2 x i32 value to shift plus a shift amount.
6207 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6208 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6209 EVT VT = Op.getValueType();
6210 unsigned VTBits = VT.getSizeInBits();
6211 DebugLoc dl = Op.getDebugLoc();
6212 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6213 SDValue ShOpLo = Op.getOperand(0);
6214 SDValue ShOpHi = Op.getOperand(1);
6215 SDValue ShAmt = Op.getOperand(2);
6216 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6217 DAG.getConstant(VTBits - 1, MVT::i8))
6218 : DAG.getConstant(0, VT);
6221 if (Op.getOpcode() == ISD::SHL_PARTS) {
6222 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6223 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6225 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6226 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6229 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6230 DAG.getConstant(VTBits, MVT::i8));
6231 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6232 AndNode, DAG.getConstant(0, MVT::i8));
6235 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6236 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6237 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6239 if (Op.getOpcode() == ISD::SHL_PARTS) {
6240 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6241 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6243 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6244 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6247 SDValue Ops[2] = { Lo, Hi };
6248 return DAG.getMergeValues(Ops, 2, dl);
6251 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6252 SelectionDAG &DAG) const {
6253 EVT SrcVT = Op.getOperand(0).getValueType();
6255 if (SrcVT.isVector())
6258 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6259 "Unknown SINT_TO_FP to lower!");
6261 // These are really Legal; return the operand so the caller accepts it as
6263 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6265 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6266 Subtarget->is64Bit()) {
6270 DebugLoc dl = Op.getDebugLoc();
6271 unsigned Size = SrcVT.getSizeInBits()/8;
6272 MachineFunction &MF = DAG.getMachineFunction();
6273 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6274 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6275 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6277 MachinePointerInfo::getFixedStack(SSFI),
6279 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6282 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6284 SelectionDAG &DAG) const {
6286 DebugLoc DL = Op.getDebugLoc();
6288 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6290 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6292 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6294 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6296 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6297 MachineMemOperand *MMO =
6298 DAG.getMachineFunction()
6299 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6300 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6302 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6303 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6305 Tys, Ops, array_lengthof(Ops),
6309 Chain = Result.getValue(1);
6310 SDValue InFlag = Result.getValue(2);
6312 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6313 // shouldn't be necessary except that RFP cannot be live across
6314 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6315 MachineFunction &MF = DAG.getMachineFunction();
6316 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6317 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6318 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6319 Tys = DAG.getVTList(MVT::Other);
6321 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6323 MachineMemOperand *MMO =
6324 DAG.getMachineFunction()
6325 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6326 MachineMemOperand::MOStore, SSFISize, SSFISize);
6328 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6329 Ops, array_lengthof(Ops),
6330 Op.getValueType(), MMO);
6331 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6332 MachinePointerInfo::getFixedStack(SSFI),
6339 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6340 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6341 SelectionDAG &DAG) const {
6342 // This algorithm is not obvious. Here it is in C code, more or less:
6344 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6345 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6346 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6348 // Copy ints to xmm registers.
6349 __m128i xh = _mm_cvtsi32_si128( hi );
6350 __m128i xl = _mm_cvtsi32_si128( lo );
6352 // Combine into low half of a single xmm register.
6353 __m128i x = _mm_unpacklo_epi32( xh, xl );
6357 // Merge in appropriate exponents to give the integer bits the right
6359 x = _mm_unpacklo_epi32( x, exp );
6361 // Subtract away the biases to deal with the IEEE-754 double precision
6363 d = _mm_sub_pd( (__m128d) x, bias );
6365 // All conversions up to here are exact. The correctly rounded result is
6366 // calculated using the current rounding mode using the following
6368 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6369 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6370 // store doesn't really need to be here (except
6371 // maybe to zero the other double)
6376 DebugLoc dl = Op.getDebugLoc();
6377 LLVMContext *Context = DAG.getContext();
6379 // Build some magic constants.
6380 std::vector<Constant*> CV0;
6381 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6382 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6383 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6384 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6385 Constant *C0 = ConstantVector::get(CV0);
6386 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6388 std::vector<Constant*> CV1;
6390 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6392 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6393 Constant *C1 = ConstantVector::get(CV1);
6394 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6396 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6397 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6399 DAG.getIntPtrConstant(1)));
6400 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6401 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6403 DAG.getIntPtrConstant(0)));
6404 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6405 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6406 MachinePointerInfo::getConstantPool(),
6408 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6409 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
6410 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6411 MachinePointerInfo::getConstantPool(),
6413 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6415 // Add the halves; easiest way is to swap them into another reg first.
6416 int ShufMask[2] = { 1, -1 };
6417 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6418 DAG.getUNDEF(MVT::v2f64), ShufMask);
6419 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6420 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6421 DAG.getIntPtrConstant(0));
6424 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6425 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6426 SelectionDAG &DAG) const {
6427 DebugLoc dl = Op.getDebugLoc();
6428 // FP constant to bias correct the final result.
6429 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6432 // Load the 32-bit value into an XMM register.
6433 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6434 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6436 DAG.getIntPtrConstant(0)));
6438 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6439 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
6440 DAG.getIntPtrConstant(0));
6442 // Or the load with the bias.
6443 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6444 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6445 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6447 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6448 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6449 MVT::v2f64, Bias)));
6450 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6451 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
6452 DAG.getIntPtrConstant(0));
6454 // Subtract the bias.
6455 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6457 // Handle final rounding.
6458 EVT DestVT = Op.getValueType();
6460 if (DestVT.bitsLT(MVT::f64)) {
6461 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6462 DAG.getIntPtrConstant(0));
6463 } else if (DestVT.bitsGT(MVT::f64)) {
6464 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6467 // Handle final rounding.
6471 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6472 SelectionDAG &DAG) const {
6473 SDValue N0 = Op.getOperand(0);
6474 DebugLoc dl = Op.getDebugLoc();
6476 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6477 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6478 // the optimization here.
6479 if (DAG.SignBitIsZero(N0))
6480 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6482 EVT SrcVT = N0.getValueType();
6483 EVT DstVT = Op.getValueType();
6484 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6485 return LowerUINT_TO_FP_i64(Op, DAG);
6486 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6487 return LowerUINT_TO_FP_i32(Op, DAG);
6489 // Make a 64-bit buffer, and use it to build an FILD.
6490 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6491 if (SrcVT == MVT::i32) {
6492 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6493 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6494 getPointerTy(), StackSlot, WordOff);
6495 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6496 StackSlot, MachinePointerInfo(),
6498 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6499 OffsetSlot, MachinePointerInfo(),
6501 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6505 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6506 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6507 StackSlot, MachinePointerInfo(),
6509 // For i64 source, we need to add the appropriate power of 2 if the input
6510 // was negative. This is the same as the optimization in
6511 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6512 // we must be careful to do the computation in x87 extended precision, not
6513 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6514 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6515 MachineMemOperand *MMO =
6516 DAG.getMachineFunction()
6517 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6518 MachineMemOperand::MOLoad, 8, 8);
6520 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6521 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6522 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6525 APInt FF(32, 0x5F800000ULL);
6527 // Check whether the sign bit is set.
6528 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6529 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6532 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6533 SDValue FudgePtr = DAG.getConstantPool(
6534 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6537 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6538 SDValue Zero = DAG.getIntPtrConstant(0);
6539 SDValue Four = DAG.getIntPtrConstant(4);
6540 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6542 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6544 // Load the value out, extending it from f32 to f80.
6545 // FIXME: Avoid the extend by constructing the right constant pool?
6546 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6547 FudgePtr, MachinePointerInfo::getConstantPool(),
6548 MVT::f32, false, false, 4);
6549 // Extend everything to 80 bits to force it to be done on x87.
6550 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6551 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6554 std::pair<SDValue,SDValue> X86TargetLowering::
6555 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6556 DebugLoc DL = Op.getDebugLoc();
6558 EVT DstTy = Op.getValueType();
6561 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6565 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6566 DstTy.getSimpleVT() >= MVT::i16 &&
6567 "Unknown FP_TO_SINT to lower!");
6569 // These are really Legal.
6570 if (DstTy == MVT::i32 &&
6571 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6572 return std::make_pair(SDValue(), SDValue());
6573 if (Subtarget->is64Bit() &&
6574 DstTy == MVT::i64 &&
6575 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6576 return std::make_pair(SDValue(), SDValue());
6578 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6580 MachineFunction &MF = DAG.getMachineFunction();
6581 unsigned MemSize = DstTy.getSizeInBits()/8;
6582 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6583 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6588 switch (DstTy.getSimpleVT().SimpleTy) {
6589 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6590 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6591 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6592 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6595 SDValue Chain = DAG.getEntryNode();
6596 SDValue Value = Op.getOperand(0);
6597 EVT TheVT = Op.getOperand(0).getValueType();
6598 if (isScalarFPTypeInSSEReg(TheVT)) {
6599 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6600 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6601 MachinePointerInfo::getFixedStack(SSFI),
6603 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6605 Chain, StackSlot, DAG.getValueType(TheVT)
6608 MachineMemOperand *MMO =
6609 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6610 MachineMemOperand::MOLoad, MemSize, MemSize);
6611 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6613 Chain = Value.getValue(1);
6614 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6615 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6618 MachineMemOperand *MMO =
6619 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6620 MachineMemOperand::MOStore, MemSize, MemSize);
6622 // Build the FP_TO_INT*_IN_MEM
6623 SDValue Ops[] = { Chain, Value, StackSlot };
6624 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6625 Ops, 3, DstTy, MMO);
6627 return std::make_pair(FIST, StackSlot);
6630 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6631 SelectionDAG &DAG) const {
6632 if (Op.getValueType().isVector())
6635 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6636 SDValue FIST = Vals.first, StackSlot = Vals.second;
6637 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6638 if (FIST.getNode() == 0) return Op;
6641 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6642 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6645 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6646 SelectionDAG &DAG) const {
6647 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6648 SDValue FIST = Vals.first, StackSlot = Vals.second;
6649 assert(FIST.getNode() && "Unexpected failure");
6652 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6653 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6656 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6657 SelectionDAG &DAG) const {
6658 LLVMContext *Context = DAG.getContext();
6659 DebugLoc dl = Op.getDebugLoc();
6660 EVT VT = Op.getValueType();
6663 EltVT = VT.getVectorElementType();
6664 std::vector<Constant*> CV;
6665 if (EltVT == MVT::f64) {
6666 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6670 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6676 Constant *C = ConstantVector::get(CV);
6677 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6678 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6679 MachinePointerInfo::getConstantPool(),
6681 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6684 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6685 LLVMContext *Context = DAG.getContext();
6686 DebugLoc dl = Op.getDebugLoc();
6687 EVT VT = Op.getValueType();
6690 EltVT = VT.getVectorElementType();
6691 std::vector<Constant*> CV;
6692 if (EltVT == MVT::f64) {
6693 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6697 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6703 Constant *C = ConstantVector::get(CV);
6704 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6705 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6706 MachinePointerInfo::getConstantPool(),
6708 if (VT.isVector()) {
6709 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6710 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6711 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6713 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
6715 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6719 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6720 LLVMContext *Context = DAG.getContext();
6721 SDValue Op0 = Op.getOperand(0);
6722 SDValue Op1 = Op.getOperand(1);
6723 DebugLoc dl = Op.getDebugLoc();
6724 EVT VT = Op.getValueType();
6725 EVT SrcVT = Op1.getValueType();
6727 // If second operand is smaller, extend it first.
6728 if (SrcVT.bitsLT(VT)) {
6729 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6732 // And if it is bigger, shrink it first.
6733 if (SrcVT.bitsGT(VT)) {
6734 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6738 // At this point the operands and the result should have the same
6739 // type, and that won't be f80 since that is not custom lowered.
6741 // First get the sign bit of second operand.
6742 std::vector<Constant*> CV;
6743 if (SrcVT == MVT::f64) {
6744 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6745 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6747 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6748 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6749 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6750 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6752 Constant *C = ConstantVector::get(CV);
6753 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6754 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6755 MachinePointerInfo::getConstantPool(),
6757 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6759 // Shift sign bit right or left if the two operands have different types.
6760 if (SrcVT.bitsGT(VT)) {
6761 // Op0 is MVT::f32, Op1 is MVT::f64.
6762 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6763 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6764 DAG.getConstant(32, MVT::i32));
6765 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
6766 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6767 DAG.getIntPtrConstant(0));
6770 // Clear first operand sign bit.
6772 if (VT == MVT::f64) {
6773 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6774 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6776 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6777 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6778 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6779 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6781 C = ConstantVector::get(CV);
6782 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6783 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6784 MachinePointerInfo::getConstantPool(),
6786 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6788 // Or the value with the sign bit.
6789 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6792 /// Emit nodes that will be selected as "test Op0,Op0", or something
6794 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6795 SelectionDAG &DAG) const {
6796 DebugLoc dl = Op.getDebugLoc();
6798 // CF and OF aren't always set the way we want. Determine which
6799 // of these we need.
6800 bool NeedCF = false;
6801 bool NeedOF = false;
6804 case X86::COND_A: case X86::COND_AE:
6805 case X86::COND_B: case X86::COND_BE:
6808 case X86::COND_G: case X86::COND_GE:
6809 case X86::COND_L: case X86::COND_LE:
6810 case X86::COND_O: case X86::COND_NO:
6815 // See if we can use the EFLAGS value from the operand instead of
6816 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6817 // we prove that the arithmetic won't overflow, we can't use OF or CF.
6818 if (Op.getResNo() != 0 || NeedOF || NeedCF)
6819 // Emit a CMP with 0, which is the TEST pattern.
6820 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6821 DAG.getConstant(0, Op.getValueType()));
6823 unsigned Opcode = 0;
6824 unsigned NumOperands = 0;
6825 switch (Op.getNode()->getOpcode()) {
6827 // Due to an isel shortcoming, be conservative if this add is likely to be
6828 // selected as part of a load-modify-store instruction. When the root node
6829 // in a match is a store, isel doesn't know how to remap non-chain non-flag
6830 // uses of other nodes in the match, such as the ADD in this case. This
6831 // leads to the ADD being left around and reselected, with the result being
6832 // two adds in the output. Alas, even if none our users are stores, that
6833 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
6834 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
6835 // climbing the DAG back to the root, and it doesn't seem to be worth the
6837 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6838 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6839 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6842 if (ConstantSDNode *C =
6843 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6844 // An add of one will be selected as an INC.
6845 if (C->getAPIntValue() == 1) {
6846 Opcode = X86ISD::INC;
6851 // An add of negative one (subtract of one) will be selected as a DEC.
6852 if (C->getAPIntValue().isAllOnesValue()) {
6853 Opcode = X86ISD::DEC;
6859 // Otherwise use a regular EFLAGS-setting add.
6860 Opcode = X86ISD::ADD;
6864 // If the primary and result isn't used, don't bother using X86ISD::AND,
6865 // because a TEST instruction will be better.
6866 bool NonFlagUse = false;
6867 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6868 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6870 unsigned UOpNo = UI.getOperandNo();
6871 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6872 // Look pass truncate.
6873 UOpNo = User->use_begin().getOperandNo();
6874 User = *User->use_begin();
6877 if (User->getOpcode() != ISD::BRCOND &&
6878 User->getOpcode() != ISD::SETCC &&
6879 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6892 // Due to the ISEL shortcoming noted above, be conservative if this op is
6893 // likely to be selected as part of a load-modify-store instruction.
6894 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6895 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6896 if (UI->getOpcode() == ISD::STORE)
6899 // Otherwise use a regular EFLAGS-setting instruction.
6900 switch (Op.getNode()->getOpcode()) {
6901 default: llvm_unreachable("unexpected operator!");
6902 case ISD::SUB: Opcode = X86ISD::SUB; break;
6903 case ISD::OR: Opcode = X86ISD::OR; break;
6904 case ISD::XOR: Opcode = X86ISD::XOR; break;
6905 case ISD::AND: Opcode = X86ISD::AND; break;
6917 return SDValue(Op.getNode(), 1);
6924 // Emit a CMP with 0, which is the TEST pattern.
6925 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6926 DAG.getConstant(0, Op.getValueType()));
6928 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6929 SmallVector<SDValue, 4> Ops;
6930 for (unsigned i = 0; i != NumOperands; ++i)
6931 Ops.push_back(Op.getOperand(i));
6933 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6934 DAG.ReplaceAllUsesWith(Op, New);
6935 return SDValue(New.getNode(), 1);
6938 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6940 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6941 SelectionDAG &DAG) const {
6942 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6943 if (C->getAPIntValue() == 0)
6944 return EmitTest(Op0, X86CC, DAG);
6946 DebugLoc dl = Op0.getDebugLoc();
6947 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6950 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6951 /// if it's possible.
6952 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6953 DebugLoc dl, SelectionDAG &DAG) const {
6954 SDValue Op0 = And.getOperand(0);
6955 SDValue Op1 = And.getOperand(1);
6956 if (Op0.getOpcode() == ISD::TRUNCATE)
6957 Op0 = Op0.getOperand(0);
6958 if (Op1.getOpcode() == ISD::TRUNCATE)
6959 Op1 = Op1.getOperand(0);
6962 if (Op1.getOpcode() == ISD::SHL)
6963 std::swap(Op0, Op1);
6964 if (Op0.getOpcode() == ISD::SHL) {
6965 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6966 if (And00C->getZExtValue() == 1) {
6967 // If we looked past a truncate, check that it's only truncating away
6969 unsigned BitWidth = Op0.getValueSizeInBits();
6970 unsigned AndBitWidth = And.getValueSizeInBits();
6971 if (BitWidth > AndBitWidth) {
6972 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6973 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6974 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6978 RHS = Op0.getOperand(1);
6980 } else if (Op1.getOpcode() == ISD::Constant) {
6981 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6982 SDValue AndLHS = Op0;
6983 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6984 LHS = AndLHS.getOperand(0);
6985 RHS = AndLHS.getOperand(1);
6989 if (LHS.getNode()) {
6990 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
6991 // instruction. Since the shift amount is in-range-or-undefined, we know
6992 // that doing a bittest on the i32 value is ok. We extend to i32 because
6993 // the encoding for the i16 version is larger than the i32 version.
6994 // Also promote i16 to i32 for performance / code size reason.
6995 if (LHS.getValueType() == MVT::i8 ||
6996 LHS.getValueType() == MVT::i16)
6997 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6999 // If the operand types disagree, extend the shift amount to match. Since
7000 // BT ignores high bits (like shifts) we can use anyextend.
7001 if (LHS.getValueType() != RHS.getValueType())
7002 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7004 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7005 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7006 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7007 DAG.getConstant(Cond, MVT::i8), BT);
7013 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7014 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7015 SDValue Op0 = Op.getOperand(0);
7016 SDValue Op1 = Op.getOperand(1);
7017 DebugLoc dl = Op.getDebugLoc();
7018 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7020 // Optimize to BT if possible.
7021 // Lower (X & (1 << N)) == 0 to BT(X, N).
7022 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7023 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7024 if (Op0.getOpcode() == ISD::AND &&
7026 Op1.getOpcode() == ISD::Constant &&
7027 cast<ConstantSDNode>(Op1)->isNullValue() &&
7028 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7029 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7030 if (NewSetCC.getNode())
7034 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
7035 if (Op0.getOpcode() == X86ISD::SETCC &&
7036 Op1.getOpcode() == ISD::Constant &&
7037 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7038 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7039 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7040 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7041 bool Invert = (CC == ISD::SETNE) ^
7042 cast<ConstantSDNode>(Op1)->isNullValue();
7044 CCode = X86::GetOppositeBranchCondition(CCode);
7045 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7046 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7049 bool isFP = Op1.getValueType().isFloatingPoint();
7050 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7051 if (X86CC == X86::COND_INVALID)
7054 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7056 // Use sbb x, x to materialize carry bit into a GPR.
7057 if (X86CC == X86::COND_B)
7058 return DAG.getNode(ISD::AND, dl, MVT::i8,
7059 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7060 DAG.getConstant(X86CC, MVT::i8), Cond),
7061 DAG.getConstant(1, MVT::i8));
7063 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7064 DAG.getConstant(X86CC, MVT::i8), Cond);
7067 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7069 SDValue Op0 = Op.getOperand(0);
7070 SDValue Op1 = Op.getOperand(1);
7071 SDValue CC = Op.getOperand(2);
7072 EVT VT = Op.getValueType();
7073 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7074 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7075 DebugLoc dl = Op.getDebugLoc();
7079 EVT VT0 = Op0.getValueType();
7080 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7081 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7084 switch (SetCCOpcode) {
7087 case ISD::SETEQ: SSECC = 0; break;
7089 case ISD::SETGT: Swap = true; // Fallthrough
7091 case ISD::SETOLT: SSECC = 1; break;
7093 case ISD::SETGE: Swap = true; // Fallthrough
7095 case ISD::SETOLE: SSECC = 2; break;
7096 case ISD::SETUO: SSECC = 3; break;
7098 case ISD::SETNE: SSECC = 4; break;
7099 case ISD::SETULE: Swap = true;
7100 case ISD::SETUGE: SSECC = 5; break;
7101 case ISD::SETULT: Swap = true;
7102 case ISD::SETUGT: SSECC = 6; break;
7103 case ISD::SETO: SSECC = 7; break;
7106 std::swap(Op0, Op1);
7108 // In the two special cases we can't handle, emit two comparisons.
7110 if (SetCCOpcode == ISD::SETUEQ) {
7112 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7113 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7114 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7116 else if (SetCCOpcode == ISD::SETONE) {
7118 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7119 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7120 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7122 llvm_unreachable("Illegal FP comparison");
7124 // Handle all other FP comparisons here.
7125 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7128 // We are handling one of the integer comparisons here. Since SSE only has
7129 // GT and EQ comparisons for integer, swapping operands and multiple
7130 // operations may be required for some comparisons.
7131 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7132 bool Swap = false, Invert = false, FlipSigns = false;
7134 switch (VT.getSimpleVT().SimpleTy) {
7136 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7137 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7138 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7139 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7142 switch (SetCCOpcode) {
7144 case ISD::SETNE: Invert = true;
7145 case ISD::SETEQ: Opc = EQOpc; break;
7146 case ISD::SETLT: Swap = true;
7147 case ISD::SETGT: Opc = GTOpc; break;
7148 case ISD::SETGE: Swap = true;
7149 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7150 case ISD::SETULT: Swap = true;
7151 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7152 case ISD::SETUGE: Swap = true;
7153 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7156 std::swap(Op0, Op1);
7158 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7159 // bits of the inputs before performing those operations.
7161 EVT EltVT = VT.getVectorElementType();
7162 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7164 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7165 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7167 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7168 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7171 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7173 // If the logical-not of the result is required, perform that now.
7175 Result = DAG.getNOT(dl, Result, VT);
7180 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7181 static bool isX86LogicalCmp(SDValue Op) {
7182 unsigned Opc = Op.getNode()->getOpcode();
7183 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7185 if (Op.getResNo() == 1 &&
7186 (Opc == X86ISD::ADD ||
7187 Opc == X86ISD::SUB ||
7188 Opc == X86ISD::SMUL ||
7189 Opc == X86ISD::UMUL ||
7190 Opc == X86ISD::INC ||
7191 Opc == X86ISD::DEC ||
7192 Opc == X86ISD::OR ||
7193 Opc == X86ISD::XOR ||
7194 Opc == X86ISD::AND))
7200 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7201 bool addTest = true;
7202 SDValue Cond = Op.getOperand(0);
7203 DebugLoc dl = Op.getDebugLoc();
7206 if (Cond.getOpcode() == ISD::SETCC) {
7207 SDValue NewCond = LowerSETCC(Cond, DAG);
7208 if (NewCond.getNode())
7212 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
7213 SDValue Op1 = Op.getOperand(1);
7214 SDValue Op2 = Op.getOperand(2);
7215 if (Cond.getOpcode() == X86ISD::SETCC &&
7216 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
7217 SDValue Cmp = Cond.getOperand(1);
7218 if (Cmp.getOpcode() == X86ISD::CMP) {
7219 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
7220 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7221 ConstantSDNode *RHSC =
7222 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
7223 if (N1C && N1C->isAllOnesValue() &&
7224 N2C && N2C->isNullValue() &&
7225 RHSC && RHSC->isNullValue()) {
7226 SDValue CmpOp0 = Cmp.getOperand(0);
7227 Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7228 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7229 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
7230 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7235 // Look pass (and (setcc_carry (cmp ...)), 1).
7236 if (Cond.getOpcode() == ISD::AND &&
7237 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7238 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7239 if (C && C->getAPIntValue() == 1)
7240 Cond = Cond.getOperand(0);
7243 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7244 // setting operand in place of the X86ISD::SETCC.
7245 if (Cond.getOpcode() == X86ISD::SETCC ||
7246 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7247 CC = Cond.getOperand(0);
7249 SDValue Cmp = Cond.getOperand(1);
7250 unsigned Opc = Cmp.getOpcode();
7251 EVT VT = Op.getValueType();
7253 bool IllegalFPCMov = false;
7254 if (VT.isFloatingPoint() && !VT.isVector() &&
7255 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7256 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7258 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7259 Opc == X86ISD::BT) { // FIXME
7266 // Look pass the truncate.
7267 if (Cond.getOpcode() == ISD::TRUNCATE)
7268 Cond = Cond.getOperand(0);
7270 // We know the result of AND is compared against zero. Try to match
7272 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7273 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7274 if (NewSetCC.getNode()) {
7275 CC = NewSetCC.getOperand(0);
7276 Cond = NewSetCC.getOperand(1);
7283 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7284 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7287 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7288 // condition is true.
7289 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7290 SDValue Ops[] = { Op2, Op1, CC, Cond };
7291 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
7294 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7295 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7296 // from the AND / OR.
7297 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7298 Opc = Op.getOpcode();
7299 if (Opc != ISD::OR && Opc != ISD::AND)
7301 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7302 Op.getOperand(0).hasOneUse() &&
7303 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7304 Op.getOperand(1).hasOneUse());
7307 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7308 // 1 and that the SETCC node has a single use.
7309 static bool isXor1OfSetCC(SDValue Op) {
7310 if (Op.getOpcode() != ISD::XOR)
7312 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7313 if (N1C && N1C->getAPIntValue() == 1) {
7314 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7315 Op.getOperand(0).hasOneUse();
7320 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7321 bool addTest = true;
7322 SDValue Chain = Op.getOperand(0);
7323 SDValue Cond = Op.getOperand(1);
7324 SDValue Dest = Op.getOperand(2);
7325 DebugLoc dl = Op.getDebugLoc();
7328 if (Cond.getOpcode() == ISD::SETCC) {
7329 SDValue NewCond = LowerSETCC(Cond, DAG);
7330 if (NewCond.getNode())
7334 // FIXME: LowerXALUO doesn't handle these!!
7335 else if (Cond.getOpcode() == X86ISD::ADD ||
7336 Cond.getOpcode() == X86ISD::SUB ||
7337 Cond.getOpcode() == X86ISD::SMUL ||
7338 Cond.getOpcode() == X86ISD::UMUL)
7339 Cond = LowerXALUO(Cond, DAG);
7342 // Look pass (and (setcc_carry (cmp ...)), 1).
7343 if (Cond.getOpcode() == ISD::AND &&
7344 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7345 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7346 if (C && C->getAPIntValue() == 1)
7347 Cond = Cond.getOperand(0);
7350 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7351 // setting operand in place of the X86ISD::SETCC.
7352 if (Cond.getOpcode() == X86ISD::SETCC ||
7353 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7354 CC = Cond.getOperand(0);
7356 SDValue Cmp = Cond.getOperand(1);
7357 unsigned Opc = Cmp.getOpcode();
7358 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7359 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7363 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7367 // These can only come from an arithmetic instruction with overflow,
7368 // e.g. SADDO, UADDO.
7369 Cond = Cond.getNode()->getOperand(1);
7376 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7377 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7378 if (CondOpc == ISD::OR) {
7379 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7380 // two branches instead of an explicit OR instruction with a
7382 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7383 isX86LogicalCmp(Cmp)) {
7384 CC = Cond.getOperand(0).getOperand(0);
7385 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7386 Chain, Dest, CC, Cmp);
7387 CC = Cond.getOperand(1).getOperand(0);
7391 } else { // ISD::AND
7392 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7393 // two branches instead of an explicit AND instruction with a
7394 // separate test. However, we only do this if this block doesn't
7395 // have a fall-through edge, because this requires an explicit
7396 // jmp when the condition is false.
7397 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7398 isX86LogicalCmp(Cmp) &&
7399 Op.getNode()->hasOneUse()) {
7400 X86::CondCode CCode =
7401 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7402 CCode = X86::GetOppositeBranchCondition(CCode);
7403 CC = DAG.getConstant(CCode, MVT::i8);
7404 SDNode *User = *Op.getNode()->use_begin();
7405 // Look for an unconditional branch following this conditional branch.
7406 // We need this because we need to reverse the successors in order
7407 // to implement FCMP_OEQ.
7408 if (User->getOpcode() == ISD::BR) {
7409 SDValue FalseBB = User->getOperand(1);
7411 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7412 assert(NewBR == User);
7416 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7417 Chain, Dest, CC, Cmp);
7418 X86::CondCode CCode =
7419 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7420 CCode = X86::GetOppositeBranchCondition(CCode);
7421 CC = DAG.getConstant(CCode, MVT::i8);
7427 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7428 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7429 // It should be transformed during dag combiner except when the condition
7430 // is set by a arithmetics with overflow node.
7431 X86::CondCode CCode =
7432 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7433 CCode = X86::GetOppositeBranchCondition(CCode);
7434 CC = DAG.getConstant(CCode, MVT::i8);
7435 Cond = Cond.getOperand(0).getOperand(1);
7441 // Look pass the truncate.
7442 if (Cond.getOpcode() == ISD::TRUNCATE)
7443 Cond = Cond.getOperand(0);
7445 // We know the result of AND is compared against zero. Try to match
7447 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7448 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7449 if (NewSetCC.getNode()) {
7450 CC = NewSetCC.getOperand(0);
7451 Cond = NewSetCC.getOperand(1);
7458 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7459 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7461 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7462 Chain, Dest, CC, Cond);
7466 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7467 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7468 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7469 // that the guard pages used by the OS virtual memory manager are allocated in
7470 // correct sequence.
7472 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7473 SelectionDAG &DAG) const {
7474 assert(Subtarget->isTargetCygMing() &&
7475 "This should be used only on Cygwin/Mingw targets");
7476 DebugLoc dl = Op.getDebugLoc();
7479 SDValue Chain = Op.getOperand(0);
7480 SDValue Size = Op.getOperand(1);
7481 // FIXME: Ensure alignment here
7485 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7487 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7488 Flag = Chain.getValue(1);
7490 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7492 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
7493 Flag = Chain.getValue(1);
7495 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7497 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7498 return DAG.getMergeValues(Ops1, 2, dl);
7501 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7502 MachineFunction &MF = DAG.getMachineFunction();
7503 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7505 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7506 DebugLoc DL = Op.getDebugLoc();
7508 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7509 // vastart just stores the address of the VarArgsFrameIndex slot into the
7510 // memory location argument.
7511 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7513 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7514 MachinePointerInfo(SV), false, false, 0);
7518 // gp_offset (0 - 6 * 8)
7519 // fp_offset (48 - 48 + 8 * 16)
7520 // overflow_arg_area (point to parameters coming in memory).
7522 SmallVector<SDValue, 8> MemOps;
7523 SDValue FIN = Op.getOperand(1);
7525 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7526 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7528 FIN, MachinePointerInfo(SV), false, false, 0);
7529 MemOps.push_back(Store);
7532 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7533 FIN, DAG.getIntPtrConstant(4));
7534 Store = DAG.getStore(Op.getOperand(0), DL,
7535 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7537 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7538 MemOps.push_back(Store);
7540 // Store ptr to overflow_arg_area
7541 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7542 FIN, DAG.getIntPtrConstant(4));
7543 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7545 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7546 MachinePointerInfo(SV, 8),
7548 MemOps.push_back(Store);
7550 // Store ptr to reg_save_area.
7551 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7552 FIN, DAG.getIntPtrConstant(8));
7553 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7555 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7556 MachinePointerInfo(SV, 16), false, false, 0);
7557 MemOps.push_back(Store);
7558 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7559 &MemOps[0], MemOps.size());
7562 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7563 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7564 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
7566 report_fatal_error("VAArgInst is not yet implemented for x86-64!");
7570 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7571 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7572 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7573 SDValue Chain = Op.getOperand(0);
7574 SDValue DstPtr = Op.getOperand(1);
7575 SDValue SrcPtr = Op.getOperand(2);
7576 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7577 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7578 DebugLoc DL = Op.getDebugLoc();
7580 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7581 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7583 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7587 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7588 DebugLoc dl = Op.getDebugLoc();
7589 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7591 default: return SDValue(); // Don't custom lower most intrinsics.
7592 // Comparison intrinsics.
7593 case Intrinsic::x86_sse_comieq_ss:
7594 case Intrinsic::x86_sse_comilt_ss:
7595 case Intrinsic::x86_sse_comile_ss:
7596 case Intrinsic::x86_sse_comigt_ss:
7597 case Intrinsic::x86_sse_comige_ss:
7598 case Intrinsic::x86_sse_comineq_ss:
7599 case Intrinsic::x86_sse_ucomieq_ss:
7600 case Intrinsic::x86_sse_ucomilt_ss:
7601 case Intrinsic::x86_sse_ucomile_ss:
7602 case Intrinsic::x86_sse_ucomigt_ss:
7603 case Intrinsic::x86_sse_ucomige_ss:
7604 case Intrinsic::x86_sse_ucomineq_ss:
7605 case Intrinsic::x86_sse2_comieq_sd:
7606 case Intrinsic::x86_sse2_comilt_sd:
7607 case Intrinsic::x86_sse2_comile_sd:
7608 case Intrinsic::x86_sse2_comigt_sd:
7609 case Intrinsic::x86_sse2_comige_sd:
7610 case Intrinsic::x86_sse2_comineq_sd:
7611 case Intrinsic::x86_sse2_ucomieq_sd:
7612 case Intrinsic::x86_sse2_ucomilt_sd:
7613 case Intrinsic::x86_sse2_ucomile_sd:
7614 case Intrinsic::x86_sse2_ucomigt_sd:
7615 case Intrinsic::x86_sse2_ucomige_sd:
7616 case Intrinsic::x86_sse2_ucomineq_sd: {
7618 ISD::CondCode CC = ISD::SETCC_INVALID;
7621 case Intrinsic::x86_sse_comieq_ss:
7622 case Intrinsic::x86_sse2_comieq_sd:
7626 case Intrinsic::x86_sse_comilt_ss:
7627 case Intrinsic::x86_sse2_comilt_sd:
7631 case Intrinsic::x86_sse_comile_ss:
7632 case Intrinsic::x86_sse2_comile_sd:
7636 case Intrinsic::x86_sse_comigt_ss:
7637 case Intrinsic::x86_sse2_comigt_sd:
7641 case Intrinsic::x86_sse_comige_ss:
7642 case Intrinsic::x86_sse2_comige_sd:
7646 case Intrinsic::x86_sse_comineq_ss:
7647 case Intrinsic::x86_sse2_comineq_sd:
7651 case Intrinsic::x86_sse_ucomieq_ss:
7652 case Intrinsic::x86_sse2_ucomieq_sd:
7653 Opc = X86ISD::UCOMI;
7656 case Intrinsic::x86_sse_ucomilt_ss:
7657 case Intrinsic::x86_sse2_ucomilt_sd:
7658 Opc = X86ISD::UCOMI;
7661 case Intrinsic::x86_sse_ucomile_ss:
7662 case Intrinsic::x86_sse2_ucomile_sd:
7663 Opc = X86ISD::UCOMI;
7666 case Intrinsic::x86_sse_ucomigt_ss:
7667 case Intrinsic::x86_sse2_ucomigt_sd:
7668 Opc = X86ISD::UCOMI;
7671 case Intrinsic::x86_sse_ucomige_ss:
7672 case Intrinsic::x86_sse2_ucomige_sd:
7673 Opc = X86ISD::UCOMI;
7676 case Intrinsic::x86_sse_ucomineq_ss:
7677 case Intrinsic::x86_sse2_ucomineq_sd:
7678 Opc = X86ISD::UCOMI;
7683 SDValue LHS = Op.getOperand(1);
7684 SDValue RHS = Op.getOperand(2);
7685 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7686 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7687 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7688 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7689 DAG.getConstant(X86CC, MVT::i8), Cond);
7690 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7692 // ptest and testp intrinsics. The intrinsic these come from are designed to
7693 // return an integer value, not just an instruction so lower it to the ptest
7694 // or testp pattern and a setcc for the result.
7695 case Intrinsic::x86_sse41_ptestz:
7696 case Intrinsic::x86_sse41_ptestc:
7697 case Intrinsic::x86_sse41_ptestnzc:
7698 case Intrinsic::x86_avx_ptestz_256:
7699 case Intrinsic::x86_avx_ptestc_256:
7700 case Intrinsic::x86_avx_ptestnzc_256:
7701 case Intrinsic::x86_avx_vtestz_ps:
7702 case Intrinsic::x86_avx_vtestc_ps:
7703 case Intrinsic::x86_avx_vtestnzc_ps:
7704 case Intrinsic::x86_avx_vtestz_pd:
7705 case Intrinsic::x86_avx_vtestc_pd:
7706 case Intrinsic::x86_avx_vtestnzc_pd:
7707 case Intrinsic::x86_avx_vtestz_ps_256:
7708 case Intrinsic::x86_avx_vtestc_ps_256:
7709 case Intrinsic::x86_avx_vtestnzc_ps_256:
7710 case Intrinsic::x86_avx_vtestz_pd_256:
7711 case Intrinsic::x86_avx_vtestc_pd_256:
7712 case Intrinsic::x86_avx_vtestnzc_pd_256: {
7713 bool IsTestPacked = false;
7716 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7717 case Intrinsic::x86_avx_vtestz_ps:
7718 case Intrinsic::x86_avx_vtestz_pd:
7719 case Intrinsic::x86_avx_vtestz_ps_256:
7720 case Intrinsic::x86_avx_vtestz_pd_256:
7721 IsTestPacked = true; // Fallthrough
7722 case Intrinsic::x86_sse41_ptestz:
7723 case Intrinsic::x86_avx_ptestz_256:
7725 X86CC = X86::COND_E;
7727 case Intrinsic::x86_avx_vtestc_ps:
7728 case Intrinsic::x86_avx_vtestc_pd:
7729 case Intrinsic::x86_avx_vtestc_ps_256:
7730 case Intrinsic::x86_avx_vtestc_pd_256:
7731 IsTestPacked = true; // Fallthrough
7732 case Intrinsic::x86_sse41_ptestc:
7733 case Intrinsic::x86_avx_ptestc_256:
7735 X86CC = X86::COND_B;
7737 case Intrinsic::x86_avx_vtestnzc_ps:
7738 case Intrinsic::x86_avx_vtestnzc_pd:
7739 case Intrinsic::x86_avx_vtestnzc_ps_256:
7740 case Intrinsic::x86_avx_vtestnzc_pd_256:
7741 IsTestPacked = true; // Fallthrough
7742 case Intrinsic::x86_sse41_ptestnzc:
7743 case Intrinsic::x86_avx_ptestnzc_256:
7745 X86CC = X86::COND_A;
7749 SDValue LHS = Op.getOperand(1);
7750 SDValue RHS = Op.getOperand(2);
7751 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7752 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7753 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7754 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7755 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7758 // Fix vector shift instructions where the last operand is a non-immediate
7760 case Intrinsic::x86_sse2_pslli_w:
7761 case Intrinsic::x86_sse2_pslli_d:
7762 case Intrinsic::x86_sse2_pslli_q:
7763 case Intrinsic::x86_sse2_psrli_w:
7764 case Intrinsic::x86_sse2_psrli_d:
7765 case Intrinsic::x86_sse2_psrli_q:
7766 case Intrinsic::x86_sse2_psrai_w:
7767 case Intrinsic::x86_sse2_psrai_d:
7768 case Intrinsic::x86_mmx_pslli_w:
7769 case Intrinsic::x86_mmx_pslli_d:
7770 case Intrinsic::x86_mmx_pslli_q:
7771 case Intrinsic::x86_mmx_psrli_w:
7772 case Intrinsic::x86_mmx_psrli_d:
7773 case Intrinsic::x86_mmx_psrli_q:
7774 case Intrinsic::x86_mmx_psrai_w:
7775 case Intrinsic::x86_mmx_psrai_d: {
7776 SDValue ShAmt = Op.getOperand(2);
7777 if (isa<ConstantSDNode>(ShAmt))
7780 unsigned NewIntNo = 0;
7781 EVT ShAmtVT = MVT::v4i32;
7783 case Intrinsic::x86_sse2_pslli_w:
7784 NewIntNo = Intrinsic::x86_sse2_psll_w;
7786 case Intrinsic::x86_sse2_pslli_d:
7787 NewIntNo = Intrinsic::x86_sse2_psll_d;
7789 case Intrinsic::x86_sse2_pslli_q:
7790 NewIntNo = Intrinsic::x86_sse2_psll_q;
7792 case Intrinsic::x86_sse2_psrli_w:
7793 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7795 case Intrinsic::x86_sse2_psrli_d:
7796 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7798 case Intrinsic::x86_sse2_psrli_q:
7799 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7801 case Intrinsic::x86_sse2_psrai_w:
7802 NewIntNo = Intrinsic::x86_sse2_psra_w;
7804 case Intrinsic::x86_sse2_psrai_d:
7805 NewIntNo = Intrinsic::x86_sse2_psra_d;
7808 ShAmtVT = MVT::v2i32;
7810 case Intrinsic::x86_mmx_pslli_w:
7811 NewIntNo = Intrinsic::x86_mmx_psll_w;
7813 case Intrinsic::x86_mmx_pslli_d:
7814 NewIntNo = Intrinsic::x86_mmx_psll_d;
7816 case Intrinsic::x86_mmx_pslli_q:
7817 NewIntNo = Intrinsic::x86_mmx_psll_q;
7819 case Intrinsic::x86_mmx_psrli_w:
7820 NewIntNo = Intrinsic::x86_mmx_psrl_w;
7822 case Intrinsic::x86_mmx_psrli_d:
7823 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7825 case Intrinsic::x86_mmx_psrli_q:
7826 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7828 case Intrinsic::x86_mmx_psrai_w:
7829 NewIntNo = Intrinsic::x86_mmx_psra_w;
7831 case Intrinsic::x86_mmx_psrai_d:
7832 NewIntNo = Intrinsic::x86_mmx_psra_d;
7834 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7840 // The vector shift intrinsics with scalars uses 32b shift amounts but
7841 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7845 ShOps[1] = DAG.getConstant(0, MVT::i32);
7846 if (ShAmtVT == MVT::v4i32) {
7847 ShOps[2] = DAG.getUNDEF(MVT::i32);
7848 ShOps[3] = DAG.getUNDEF(MVT::i32);
7849 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7851 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7852 // FIXME this must be lowered to get rid of the invalid type.
7855 EVT VT = Op.getValueType();
7856 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7857 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7858 DAG.getConstant(NewIntNo, MVT::i32),
7859 Op.getOperand(1), ShAmt);
7864 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7865 SelectionDAG &DAG) const {
7866 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7867 MFI->setReturnAddressIsTaken(true);
7869 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7870 DebugLoc dl = Op.getDebugLoc();
7873 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7875 DAG.getConstant(TD->getPointerSize(),
7876 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7877 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7878 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7880 MachinePointerInfo(), false, false, 0);
7883 // Just load the return address.
7884 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7885 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7886 RetAddrFI, MachinePointerInfo(), false, false, 0);
7889 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7890 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7891 MFI->setFrameAddressIsTaken(true);
7893 EVT VT = Op.getValueType();
7894 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7895 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7896 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7897 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7899 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7900 MachinePointerInfo(),
7905 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7906 SelectionDAG &DAG) const {
7907 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7910 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7911 MachineFunction &MF = DAG.getMachineFunction();
7912 SDValue Chain = Op.getOperand(0);
7913 SDValue Offset = Op.getOperand(1);
7914 SDValue Handler = Op.getOperand(2);
7915 DebugLoc dl = Op.getDebugLoc();
7917 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
7918 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7920 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7922 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
7923 DAG.getIntPtrConstant(TD->getPointerSize()));
7924 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7925 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
7927 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7928 MF.getRegInfo().addLiveOut(StoreAddrReg);
7930 return DAG.getNode(X86ISD::EH_RETURN, dl,
7932 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7935 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7936 SelectionDAG &DAG) const {
7937 SDValue Root = Op.getOperand(0);
7938 SDValue Trmp = Op.getOperand(1); // trampoline
7939 SDValue FPtr = Op.getOperand(2); // nested function
7940 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7941 DebugLoc dl = Op.getDebugLoc();
7943 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7945 if (Subtarget->is64Bit()) {
7946 SDValue OutChains[6];
7948 // Large code-model.
7949 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
7950 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7952 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7953 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7955 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7957 // Load the pointer to the nested function into R11.
7958 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7959 SDValue Addr = Trmp;
7960 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7961 Addr, MachinePointerInfo(TrmpAddr),
7964 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7965 DAG.getConstant(2, MVT::i64));
7966 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
7967 MachinePointerInfo(TrmpAddr, 2),
7970 // Load the 'nest' parameter value into R10.
7971 // R10 is specified in X86CallingConv.td
7972 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7973 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7974 DAG.getConstant(10, MVT::i64));
7975 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7976 Addr, MachinePointerInfo(TrmpAddr, 10),
7979 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7980 DAG.getConstant(12, MVT::i64));
7981 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
7982 MachinePointerInfo(TrmpAddr, 12),
7985 // Jump to the nested function.
7986 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7987 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7988 DAG.getConstant(20, MVT::i64));
7989 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7990 Addr, MachinePointerInfo(TrmpAddr, 20),
7993 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7994 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7995 DAG.getConstant(22, MVT::i64));
7996 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7997 MachinePointerInfo(TrmpAddr, 22),
8001 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8002 return DAG.getMergeValues(Ops, 2, dl);
8004 const Function *Func =
8005 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8006 CallingConv::ID CC = Func->getCallingConv();
8011 llvm_unreachable("Unsupported calling convention");
8012 case CallingConv::C:
8013 case CallingConv::X86_StdCall: {
8014 // Pass 'nest' parameter in ECX.
8015 // Must be kept in sync with X86CallingConv.td
8018 // Check that ECX wasn't needed by an 'inreg' parameter.
8019 const FunctionType *FTy = Func->getFunctionType();
8020 const AttrListPtr &Attrs = Func->getAttributes();
8022 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8023 unsigned InRegCount = 0;
8026 for (FunctionType::param_iterator I = FTy->param_begin(),
8027 E = FTy->param_end(); I != E; ++I, ++Idx)
8028 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8029 // FIXME: should only count parameters that are lowered to integers.
8030 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8032 if (InRegCount > 2) {
8033 report_fatal_error("Nest register in use - reduce number of inreg"
8039 case CallingConv::X86_FastCall:
8040 case CallingConv::X86_ThisCall:
8041 case CallingConv::Fast:
8042 // Pass 'nest' parameter in EAX.
8043 // Must be kept in sync with X86CallingConv.td
8048 SDValue OutChains[4];
8051 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8052 DAG.getConstant(10, MVT::i32));
8053 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8055 // This is storing the opcode for MOV32ri.
8056 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8057 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8058 OutChains[0] = DAG.getStore(Root, dl,
8059 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8060 Trmp, MachinePointerInfo(TrmpAddr),
8063 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8064 DAG.getConstant(1, MVT::i32));
8065 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8066 MachinePointerInfo(TrmpAddr, 1),
8069 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8070 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8071 DAG.getConstant(5, MVT::i32));
8072 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8073 MachinePointerInfo(TrmpAddr, 5),
8076 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8077 DAG.getConstant(6, MVT::i32));
8078 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8079 MachinePointerInfo(TrmpAddr, 6),
8083 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8084 return DAG.getMergeValues(Ops, 2, dl);
8088 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8089 SelectionDAG &DAG) const {
8091 The rounding mode is in bits 11:10 of FPSR, and has the following
8098 FLT_ROUNDS, on the other hand, expects the following:
8105 To perform the conversion, we do:
8106 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8109 MachineFunction &MF = DAG.getMachineFunction();
8110 const TargetMachine &TM = MF.getTarget();
8111 const TargetFrameInfo &TFI = *TM.getFrameInfo();
8112 unsigned StackAlignment = TFI.getStackAlignment();
8113 EVT VT = Op.getValueType();
8114 DebugLoc DL = Op.getDebugLoc();
8116 // Save FP Control Word to stack slot
8117 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8118 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8121 MachineMemOperand *MMO =
8122 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8123 MachineMemOperand::MOStore, 2, 2);
8125 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8126 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8127 DAG.getVTList(MVT::Other),
8128 Ops, 2, MVT::i16, MMO);
8130 // Load FP Control Word from stack slot
8131 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8132 MachinePointerInfo(), false, false, 0);
8134 // Transform as necessary
8136 DAG.getNode(ISD::SRL, DL, MVT::i16,
8137 DAG.getNode(ISD::AND, DL, MVT::i16,
8138 CWD, DAG.getConstant(0x800, MVT::i16)),
8139 DAG.getConstant(11, MVT::i8));
8141 DAG.getNode(ISD::SRL, DL, MVT::i16,
8142 DAG.getNode(ISD::AND, DL, MVT::i16,
8143 CWD, DAG.getConstant(0x400, MVT::i16)),
8144 DAG.getConstant(9, MVT::i8));
8147 DAG.getNode(ISD::AND, DL, MVT::i16,
8148 DAG.getNode(ISD::ADD, DL, MVT::i16,
8149 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8150 DAG.getConstant(1, MVT::i16)),
8151 DAG.getConstant(3, MVT::i16));
8154 return DAG.getNode((VT.getSizeInBits() < 16 ?
8155 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8158 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8159 EVT VT = Op.getValueType();
8161 unsigned NumBits = VT.getSizeInBits();
8162 DebugLoc dl = Op.getDebugLoc();
8164 Op = Op.getOperand(0);
8165 if (VT == MVT::i8) {
8166 // Zero extend to i32 since there is not an i8 bsr.
8168 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8171 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8172 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8173 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8175 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8178 DAG.getConstant(NumBits+NumBits-1, OpVT),
8179 DAG.getConstant(X86::COND_E, MVT::i8),
8182 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8184 // Finally xor with NumBits-1.
8185 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8188 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8192 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8193 EVT VT = Op.getValueType();
8195 unsigned NumBits = VT.getSizeInBits();
8196 DebugLoc dl = Op.getDebugLoc();
8198 Op = Op.getOperand(0);
8199 if (VT == MVT::i8) {
8201 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8204 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8205 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8206 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8208 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8211 DAG.getConstant(NumBits, OpVT),
8212 DAG.getConstant(X86::COND_E, MVT::i8),
8215 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8218 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8222 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8223 EVT VT = Op.getValueType();
8224 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8225 DebugLoc dl = Op.getDebugLoc();
8227 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8228 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8229 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8230 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8231 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8233 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8234 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8235 // return AloBlo + AloBhi + AhiBlo;
8237 SDValue A = Op.getOperand(0);
8238 SDValue B = Op.getOperand(1);
8240 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8241 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8242 A, DAG.getConstant(32, MVT::i32));
8243 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8244 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8245 B, DAG.getConstant(32, MVT::i32));
8246 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8247 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8249 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8250 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8252 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8253 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8255 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8256 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8257 AloBhi, DAG.getConstant(32, MVT::i32));
8258 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8259 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8260 AhiBlo, DAG.getConstant(32, MVT::i32));
8261 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8262 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8266 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8267 EVT VT = Op.getValueType();
8268 DebugLoc dl = Op.getDebugLoc();
8269 SDValue R = Op.getOperand(0);
8271 LLVMContext *Context = DAG.getContext();
8273 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8275 if (VT == MVT::v4i32) {
8276 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8277 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8278 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8280 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8282 std::vector<Constant*> CV(4, CI);
8283 Constant *C = ConstantVector::get(CV);
8284 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8285 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8286 MachinePointerInfo::getConstantPool(),
8289 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8290 Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, Op);
8291 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8292 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8294 if (VT == MVT::v16i8) {
8296 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8297 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8298 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8300 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8301 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8303 std::vector<Constant*> CVM1(16, CM1);
8304 std::vector<Constant*> CVM2(16, CM2);
8305 Constant *C = ConstantVector::get(CVM1);
8306 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8307 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8308 MachinePointerInfo::getConstantPool(),
8311 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8312 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8313 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8314 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8315 DAG.getConstant(4, MVT::i32));
8316 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8317 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8320 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8322 C = ConstantVector::get(CVM2);
8323 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8324 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8325 MachinePointerInfo::getConstantPool(),
8328 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8329 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8330 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8331 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8332 DAG.getConstant(2, MVT::i32));
8333 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8334 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8337 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8339 // return pblendv(r, r+r, a);
8340 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8341 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8342 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8348 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8349 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8350 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8351 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8352 // has only one use.
8353 SDNode *N = Op.getNode();
8354 SDValue LHS = N->getOperand(0);
8355 SDValue RHS = N->getOperand(1);
8356 unsigned BaseOp = 0;
8358 DebugLoc dl = Op.getDebugLoc();
8360 switch (Op.getOpcode()) {
8361 default: llvm_unreachable("Unknown ovf instruction!");
8363 // A subtract of one will be selected as a INC. Note that INC doesn't
8364 // set CF, so we can't do this for UADDO.
8365 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8366 if (C->getAPIntValue() == 1) {
8367 BaseOp = X86ISD::INC;
8371 BaseOp = X86ISD::ADD;
8375 BaseOp = X86ISD::ADD;
8379 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8380 // set CF, so we can't do this for USUBO.
8381 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8382 if (C->getAPIntValue() == 1) {
8383 BaseOp = X86ISD::DEC;
8387 BaseOp = X86ISD::SUB;
8391 BaseOp = X86ISD::SUB;
8395 BaseOp = X86ISD::SMUL;
8399 BaseOp = X86ISD::UMUL;
8404 // Also sets EFLAGS.
8405 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8406 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
8409 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
8410 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
8412 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8416 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8417 DebugLoc dl = Op.getDebugLoc();
8419 if (!Subtarget->hasSSE2()) {
8420 SDValue Chain = Op.getOperand(0);
8421 SDValue Zero = DAG.getConstant(0,
8422 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8424 DAG.getRegister(X86::ESP, MVT::i32), // Base
8425 DAG.getTargetConstant(1, MVT::i8), // Scale
8426 DAG.getRegister(0, MVT::i32), // Index
8427 DAG.getTargetConstant(0, MVT::i32), // Disp
8428 DAG.getRegister(0, MVT::i32), // Segment.
8433 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8434 array_lengthof(Ops));
8435 return SDValue(Res, 0);
8438 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8440 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8442 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8443 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8444 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8445 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8447 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8448 if (!Op1 && !Op2 && !Op3 && Op4)
8449 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8451 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8452 if (Op1 && !Op2 && !Op3 && !Op4)
8453 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8455 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8457 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8460 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8461 EVT T = Op.getValueType();
8462 DebugLoc DL = Op.getDebugLoc();
8465 switch(T.getSimpleVT().SimpleTy) {
8467 assert(false && "Invalid value type!");
8468 case MVT::i8: Reg = X86::AL; size = 1; break;
8469 case MVT::i16: Reg = X86::AX; size = 2; break;
8470 case MVT::i32: Reg = X86::EAX; size = 4; break;
8472 assert(Subtarget->is64Bit() && "Node not type legal!");
8473 Reg = X86::RAX; size = 8;
8476 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8477 Op.getOperand(2), SDValue());
8478 SDValue Ops[] = { cpIn.getValue(0),
8481 DAG.getTargetConstant(size, MVT::i8),
8483 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8484 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8485 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8488 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8492 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8493 SelectionDAG &DAG) const {
8494 assert(Subtarget->is64Bit() && "Result not type legalized?");
8495 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8496 SDValue TheChain = Op.getOperand(0);
8497 DebugLoc dl = Op.getDebugLoc();
8498 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8499 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8500 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8502 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8503 DAG.getConstant(32, MVT::i8));
8505 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8508 return DAG.getMergeValues(Ops, 2, dl);
8511 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
8512 SelectionDAG &DAG) const {
8513 EVT SrcVT = Op.getOperand(0).getValueType();
8514 EVT DstVT = Op.getValueType();
8515 assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8516 Subtarget->hasMMX() && !DisableMMX) &&
8517 "Unexpected custom BIT_CONVERT");
8518 assert((DstVT == MVT::i64 ||
8519 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8520 "Unexpected custom BIT_CONVERT");
8521 // i64 <=> MMX conversions are Legal.
8522 if (SrcVT==MVT::i64 && DstVT.isVector())
8524 if (DstVT==MVT::i64 && SrcVT.isVector())
8526 // MMX <=> MMX conversions are Legal.
8527 if (SrcVT.isVector() && DstVT.isVector())
8529 // All other conversions need to be expanded.
8532 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8533 SDNode *Node = Op.getNode();
8534 DebugLoc dl = Node->getDebugLoc();
8535 EVT T = Node->getValueType(0);
8536 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8537 DAG.getConstant(0, T), Node->getOperand(2));
8538 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8539 cast<AtomicSDNode>(Node)->getMemoryVT(),
8540 Node->getOperand(0),
8541 Node->getOperand(1), negOp,
8542 cast<AtomicSDNode>(Node)->getSrcValue(),
8543 cast<AtomicSDNode>(Node)->getAlignment());
8546 /// LowerOperation - Provide custom lowering hooks for some operations.
8548 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8549 switch (Op.getOpcode()) {
8550 default: llvm_unreachable("Should not custom lower this!");
8551 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
8552 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
8553 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
8554 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8555 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8556 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8557 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8558 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8559 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8560 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8561 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8562 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8563 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
8564 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8565 case ISD::SHL_PARTS:
8566 case ISD::SRA_PARTS:
8567 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
8568 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
8569 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
8570 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
8571 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
8572 case ISD::FABS: return LowerFABS(Op, DAG);
8573 case ISD::FNEG: return LowerFNEG(Op, DAG);
8574 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8575 case ISD::SETCC: return LowerSETCC(Op, DAG);
8576 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
8577 case ISD::SELECT: return LowerSELECT(Op, DAG);
8578 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8579 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8580 case ISD::VASTART: return LowerVASTART(Op, DAG);
8581 case ISD::VAARG: return LowerVAARG(Op, DAG);
8582 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
8583 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8584 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8585 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8586 case ISD::FRAME_TO_ARGS_OFFSET:
8587 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8588 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8589 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
8590 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
8591 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8592 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
8593 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
8594 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
8595 case ISD::SHL: return LowerSHL(Op, DAG);
8601 case ISD::UMULO: return LowerXALUO(Op, DAG);
8602 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
8603 case ISD::BIT_CONVERT: return LowerBIT_CONVERT(Op, DAG);
8607 void X86TargetLowering::
8608 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8609 SelectionDAG &DAG, unsigned NewOp) const {
8610 EVT T = Node->getValueType(0);
8611 DebugLoc dl = Node->getDebugLoc();
8612 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8614 SDValue Chain = Node->getOperand(0);
8615 SDValue In1 = Node->getOperand(1);
8616 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8617 Node->getOperand(2), DAG.getIntPtrConstant(0));
8618 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8619 Node->getOperand(2), DAG.getIntPtrConstant(1));
8620 SDValue Ops[] = { Chain, In1, In2L, In2H };
8621 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8623 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8624 cast<MemSDNode>(Node)->getMemOperand());
8625 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8626 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8627 Results.push_back(Result.getValue(2));
8630 /// ReplaceNodeResults - Replace a node with an illegal result type
8631 /// with a new node built out of custom code.
8632 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8633 SmallVectorImpl<SDValue>&Results,
8634 SelectionDAG &DAG) const {
8635 DebugLoc dl = N->getDebugLoc();
8636 switch (N->getOpcode()) {
8638 assert(false && "Do not know how to custom type legalize this operation!");
8640 case ISD::FP_TO_SINT: {
8641 std::pair<SDValue,SDValue> Vals =
8642 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8643 SDValue FIST = Vals.first, StackSlot = Vals.second;
8644 if (FIST.getNode() != 0) {
8645 EVT VT = N->getValueType(0);
8646 // Return a load from the stack slot.
8647 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8648 MachinePointerInfo(), false, false, 0));
8652 case ISD::READCYCLECOUNTER: {
8653 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8654 SDValue TheChain = N->getOperand(0);
8655 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8656 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8658 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8660 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8661 SDValue Ops[] = { eax, edx };
8662 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8663 Results.push_back(edx.getValue(1));
8666 case ISD::ATOMIC_CMP_SWAP: {
8667 EVT T = N->getValueType(0);
8668 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8669 SDValue cpInL, cpInH;
8670 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8671 DAG.getConstant(0, MVT::i32));
8672 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8673 DAG.getConstant(1, MVT::i32));
8674 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8675 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8677 SDValue swapInL, swapInH;
8678 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8679 DAG.getConstant(0, MVT::i32));
8680 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8681 DAG.getConstant(1, MVT::i32));
8682 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8684 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8685 swapInL.getValue(1));
8686 SDValue Ops[] = { swapInH.getValue(0),
8688 swapInH.getValue(1) };
8689 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8690 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
8691 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8692 MVT::i32, Result.getValue(1));
8693 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8694 MVT::i32, cpOutL.getValue(2));
8695 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8696 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8697 Results.push_back(cpOutH.getValue(1));
8700 case ISD::ATOMIC_LOAD_ADD:
8701 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8703 case ISD::ATOMIC_LOAD_AND:
8704 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8706 case ISD::ATOMIC_LOAD_NAND:
8707 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8709 case ISD::ATOMIC_LOAD_OR:
8710 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8712 case ISD::ATOMIC_LOAD_SUB:
8713 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8715 case ISD::ATOMIC_LOAD_XOR:
8716 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8718 case ISD::ATOMIC_SWAP:
8719 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8724 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8726 default: return NULL;
8727 case X86ISD::BSF: return "X86ISD::BSF";
8728 case X86ISD::BSR: return "X86ISD::BSR";
8729 case X86ISD::SHLD: return "X86ISD::SHLD";
8730 case X86ISD::SHRD: return "X86ISD::SHRD";
8731 case X86ISD::FAND: return "X86ISD::FAND";
8732 case X86ISD::FOR: return "X86ISD::FOR";
8733 case X86ISD::FXOR: return "X86ISD::FXOR";
8734 case X86ISD::FSRL: return "X86ISD::FSRL";
8735 case X86ISD::FILD: return "X86ISD::FILD";
8736 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
8737 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8738 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8739 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8740 case X86ISD::FLD: return "X86ISD::FLD";
8741 case X86ISD::FST: return "X86ISD::FST";
8742 case X86ISD::CALL: return "X86ISD::CALL";
8743 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
8744 case X86ISD::BT: return "X86ISD::BT";
8745 case X86ISD::CMP: return "X86ISD::CMP";
8746 case X86ISD::COMI: return "X86ISD::COMI";
8747 case X86ISD::UCOMI: return "X86ISD::UCOMI";
8748 case X86ISD::SETCC: return "X86ISD::SETCC";
8749 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
8750 case X86ISD::CMOV: return "X86ISD::CMOV";
8751 case X86ISD::BRCOND: return "X86ISD::BRCOND";
8752 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
8753 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
8754 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
8755 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
8756 case X86ISD::Wrapper: return "X86ISD::Wrapper";
8757 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
8758 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
8759 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
8760 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
8761 case X86ISD::PINSRB: return "X86ISD::PINSRB";
8762 case X86ISD::PINSRW: return "X86ISD::PINSRW";
8763 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
8764 case X86ISD::FMAX: return "X86ISD::FMAX";
8765 case X86ISD::FMIN: return "X86ISD::FMIN";
8766 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
8767 case X86ISD::FRCP: return "X86ISD::FRCP";
8768 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
8769 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
8770 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
8771 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
8772 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
8773 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
8774 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
8775 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
8776 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
8777 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
8778 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
8779 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
8780 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
8781 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
8782 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
8783 case X86ISD::VSHL: return "X86ISD::VSHL";
8784 case X86ISD::VSRL: return "X86ISD::VSRL";
8785 case X86ISD::CMPPD: return "X86ISD::CMPPD";
8786 case X86ISD::CMPPS: return "X86ISD::CMPPS";
8787 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
8788 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
8789 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
8790 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
8791 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
8792 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
8793 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
8794 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
8795 case X86ISD::ADD: return "X86ISD::ADD";
8796 case X86ISD::SUB: return "X86ISD::SUB";
8797 case X86ISD::SMUL: return "X86ISD::SMUL";
8798 case X86ISD::UMUL: return "X86ISD::UMUL";
8799 case X86ISD::INC: return "X86ISD::INC";
8800 case X86ISD::DEC: return "X86ISD::DEC";
8801 case X86ISD::OR: return "X86ISD::OR";
8802 case X86ISD::XOR: return "X86ISD::XOR";
8803 case X86ISD::AND: return "X86ISD::AND";
8804 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
8805 case X86ISD::PTEST: return "X86ISD::PTEST";
8806 case X86ISD::TESTP: return "X86ISD::TESTP";
8807 case X86ISD::PALIGN: return "X86ISD::PALIGN";
8808 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
8809 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
8810 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
8811 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
8812 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
8813 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
8814 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
8815 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
8816 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
8817 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
8818 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
8819 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
8820 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
8821 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
8822 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
8823 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
8824 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
8825 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
8826 case X86ISD::MOVSD: return "X86ISD::MOVSD";
8827 case X86ISD::MOVSS: return "X86ISD::MOVSS";
8828 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
8829 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
8830 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
8831 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
8832 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
8833 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
8834 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
8835 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
8836 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
8837 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
8838 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
8839 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
8840 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8841 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
8845 // isLegalAddressingMode - Return true if the addressing mode represented
8846 // by AM is legal for this target, for a load/store of the specified type.
8847 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8848 const Type *Ty) const {
8849 // X86 supports extremely general addressing modes.
8850 CodeModel::Model M = getTargetMachine().getCodeModel();
8851 Reloc::Model R = getTargetMachine().getRelocationModel();
8853 // X86 allows a sign-extended 32-bit immediate field as a displacement.
8854 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8859 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8861 // If a reference to this global requires an extra load, we can't fold it.
8862 if (isGlobalStubReference(GVFlags))
8865 // If BaseGV requires a register for the PIC base, we cannot also have a
8866 // BaseReg specified.
8867 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8870 // If lower 4G is not available, then we must use rip-relative addressing.
8871 if ((M != CodeModel::Small || R != Reloc::Static) &&
8872 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8882 // These scales always work.
8887 // These scales are formed with basereg+scalereg. Only accept if there is
8892 default: // Other stuff never works.
8900 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8901 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8903 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8904 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8905 if (NumBits1 <= NumBits2)
8910 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8911 if (!VT1.isInteger() || !VT2.isInteger())
8913 unsigned NumBits1 = VT1.getSizeInBits();
8914 unsigned NumBits2 = VT2.getSizeInBits();
8915 if (NumBits1 <= NumBits2)
8920 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
8921 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8922 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
8925 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8926 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8927 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
8930 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
8931 // i16 instructions are longer (0x66 prefix) and potentially slower.
8932 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
8935 /// isShuffleMaskLegal - Targets can use this to indicate that they only
8936 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8937 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8938 /// are assumed to be legal.
8940 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
8942 // Very little shuffling can be done for 64-bit vectors right now.
8943 if (VT.getSizeInBits() == 64)
8944 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
8946 // FIXME: pshufb, blends, shifts.
8947 return (VT.getVectorNumElements() == 2 ||
8948 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8949 isMOVLMask(M, VT) ||
8950 isSHUFPMask(M, VT) ||
8951 isPSHUFDMask(M, VT) ||
8952 isPSHUFHWMask(M, VT) ||
8953 isPSHUFLWMask(M, VT) ||
8954 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
8955 isUNPCKLMask(M, VT) ||
8956 isUNPCKHMask(M, VT) ||
8957 isUNPCKL_v_undef_Mask(M, VT) ||
8958 isUNPCKH_v_undef_Mask(M, VT));
8962 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
8964 unsigned NumElts = VT.getVectorNumElements();
8965 // FIXME: This collection of masks seems suspect.
8968 if (NumElts == 4 && VT.getSizeInBits() == 128) {
8969 return (isMOVLMask(Mask, VT) ||
8970 isCommutedMOVLMask(Mask, VT, true) ||
8971 isSHUFPMask(Mask, VT) ||
8972 isCommutedSHUFPMask(Mask, VT));
8977 //===----------------------------------------------------------------------===//
8978 // X86 Scheduler Hooks
8979 //===----------------------------------------------------------------------===//
8981 // private utility function
8983 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
8984 MachineBasicBlock *MBB,
8991 TargetRegisterClass *RC,
8992 bool invSrc) const {
8993 // For the atomic bitwise operator, we generate
8996 // ld t1 = [bitinstr.addr]
8997 // op t2 = t1, [bitinstr.val]
8999 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9001 // fallthrough -->nextMBB
9002 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9003 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9004 MachineFunction::iterator MBBIter = MBB;
9007 /// First build the CFG
9008 MachineFunction *F = MBB->getParent();
9009 MachineBasicBlock *thisMBB = MBB;
9010 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9011 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9012 F->insert(MBBIter, newMBB);
9013 F->insert(MBBIter, nextMBB);
9015 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9016 nextMBB->splice(nextMBB->begin(), thisMBB,
9017 llvm::next(MachineBasicBlock::iterator(bInstr)),
9019 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9021 // Update thisMBB to fall through to newMBB
9022 thisMBB->addSuccessor(newMBB);
9024 // newMBB jumps to itself and fall through to nextMBB
9025 newMBB->addSuccessor(nextMBB);
9026 newMBB->addSuccessor(newMBB);
9028 // Insert instructions into newMBB based on incoming instruction
9029 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9030 "unexpected number of operands");
9031 DebugLoc dl = bInstr->getDebugLoc();
9032 MachineOperand& destOper = bInstr->getOperand(0);
9033 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9034 int numArgs = bInstr->getNumOperands() - 1;
9035 for (int i=0; i < numArgs; ++i)
9036 argOpers[i] = &bInstr->getOperand(i+1);
9038 // x86 address has 4 operands: base, index, scale, and displacement
9039 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9040 int valArgIndx = lastAddrIndx + 1;
9042 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9043 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9044 for (int i=0; i <= lastAddrIndx; ++i)
9045 (*MIB).addOperand(*argOpers[i]);
9047 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9049 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9054 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9055 assert((argOpers[valArgIndx]->isReg() ||
9056 argOpers[valArgIndx]->isImm()) &&
9058 if (argOpers[valArgIndx]->isReg())
9059 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9061 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9063 (*MIB).addOperand(*argOpers[valArgIndx]);
9065 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9068 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9069 for (int i=0; i <= lastAddrIndx; ++i)
9070 (*MIB).addOperand(*argOpers[i]);
9072 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9073 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9074 bInstr->memoperands_end());
9076 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9080 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9082 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9086 // private utility function: 64 bit atomics on 32 bit host.
9088 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9089 MachineBasicBlock *MBB,
9094 bool invSrc) const {
9095 // For the atomic bitwise operator, we generate
9096 // thisMBB (instructions are in pairs, except cmpxchg8b)
9097 // ld t1,t2 = [bitinstr.addr]
9099 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9100 // op t5, t6 <- out1, out2, [bitinstr.val]
9101 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9102 // mov ECX, EBX <- t5, t6
9103 // mov EAX, EDX <- t1, t2
9104 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9105 // mov t3, t4 <- EAX, EDX
9107 // result in out1, out2
9108 // fallthrough -->nextMBB
9110 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9111 const unsigned LoadOpc = X86::MOV32rm;
9112 const unsigned NotOpc = X86::NOT32r;
9113 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9114 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9115 MachineFunction::iterator MBBIter = MBB;
9118 /// First build the CFG
9119 MachineFunction *F = MBB->getParent();
9120 MachineBasicBlock *thisMBB = MBB;
9121 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9122 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9123 F->insert(MBBIter, newMBB);
9124 F->insert(MBBIter, nextMBB);
9126 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9127 nextMBB->splice(nextMBB->begin(), thisMBB,
9128 llvm::next(MachineBasicBlock::iterator(bInstr)),
9130 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9132 // Update thisMBB to fall through to newMBB
9133 thisMBB->addSuccessor(newMBB);
9135 // newMBB jumps to itself and fall through to nextMBB
9136 newMBB->addSuccessor(nextMBB);
9137 newMBB->addSuccessor(newMBB);
9139 DebugLoc dl = bInstr->getDebugLoc();
9140 // Insert instructions into newMBB based on incoming instruction
9141 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9142 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9143 "unexpected number of operands");
9144 MachineOperand& dest1Oper = bInstr->getOperand(0);
9145 MachineOperand& dest2Oper = bInstr->getOperand(1);
9146 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9147 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9148 argOpers[i] = &bInstr->getOperand(i+2);
9150 // We use some of the operands multiple times, so conservatively just
9151 // clear any kill flags that might be present.
9152 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9153 argOpers[i]->setIsKill(false);
9156 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9157 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9159 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9160 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9161 for (int i=0; i <= lastAddrIndx; ++i)
9162 (*MIB).addOperand(*argOpers[i]);
9163 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9164 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9165 // add 4 to displacement.
9166 for (int i=0; i <= lastAddrIndx-2; ++i)
9167 (*MIB).addOperand(*argOpers[i]);
9168 MachineOperand newOp3 = *(argOpers[3]);
9170 newOp3.setImm(newOp3.getImm()+4);
9172 newOp3.setOffset(newOp3.getOffset()+4);
9173 (*MIB).addOperand(newOp3);
9174 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9176 // t3/4 are defined later, at the bottom of the loop
9177 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9178 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9179 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9180 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9181 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9182 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9184 // The subsequent operations should be using the destination registers of
9185 //the PHI instructions.
9187 t1 = F->getRegInfo().createVirtualRegister(RC);
9188 t2 = F->getRegInfo().createVirtualRegister(RC);
9189 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9190 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9192 t1 = dest1Oper.getReg();
9193 t2 = dest2Oper.getReg();
9196 int valArgIndx = lastAddrIndx + 1;
9197 assert((argOpers[valArgIndx]->isReg() ||
9198 argOpers[valArgIndx]->isImm()) &&
9200 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9201 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9202 if (argOpers[valArgIndx]->isReg())
9203 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9205 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9206 if (regOpcL != X86::MOV32rr)
9208 (*MIB).addOperand(*argOpers[valArgIndx]);
9209 assert(argOpers[valArgIndx + 1]->isReg() ==
9210 argOpers[valArgIndx]->isReg());
9211 assert(argOpers[valArgIndx + 1]->isImm() ==
9212 argOpers[valArgIndx]->isImm());
9213 if (argOpers[valArgIndx + 1]->isReg())
9214 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9216 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9217 if (regOpcH != X86::MOV32rr)
9219 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9221 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9223 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9226 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9228 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9231 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9232 for (int i=0; i <= lastAddrIndx; ++i)
9233 (*MIB).addOperand(*argOpers[i]);
9235 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9236 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9237 bInstr->memoperands_end());
9239 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9240 MIB.addReg(X86::EAX);
9241 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9242 MIB.addReg(X86::EDX);
9245 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9247 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9251 // private utility function
9253 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9254 MachineBasicBlock *MBB,
9255 unsigned cmovOpc) const {
9256 // For the atomic min/max operator, we generate
9259 // ld t1 = [min/max.addr]
9260 // mov t2 = [min/max.val]
9262 // cmov[cond] t2 = t1
9264 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9266 // fallthrough -->nextMBB
9268 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9269 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9270 MachineFunction::iterator MBBIter = MBB;
9273 /// First build the CFG
9274 MachineFunction *F = MBB->getParent();
9275 MachineBasicBlock *thisMBB = MBB;
9276 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9277 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9278 F->insert(MBBIter, newMBB);
9279 F->insert(MBBIter, nextMBB);
9281 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9282 nextMBB->splice(nextMBB->begin(), thisMBB,
9283 llvm::next(MachineBasicBlock::iterator(mInstr)),
9285 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9287 // Update thisMBB to fall through to newMBB
9288 thisMBB->addSuccessor(newMBB);
9290 // newMBB jumps to newMBB and fall through to nextMBB
9291 newMBB->addSuccessor(nextMBB);
9292 newMBB->addSuccessor(newMBB);
9294 DebugLoc dl = mInstr->getDebugLoc();
9295 // Insert instructions into newMBB based on incoming instruction
9296 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9297 "unexpected number of operands");
9298 MachineOperand& destOper = mInstr->getOperand(0);
9299 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9300 int numArgs = mInstr->getNumOperands() - 1;
9301 for (int i=0; i < numArgs; ++i)
9302 argOpers[i] = &mInstr->getOperand(i+1);
9304 // x86 address has 4 operands: base, index, scale, and displacement
9305 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9306 int valArgIndx = lastAddrIndx + 1;
9308 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9309 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9310 for (int i=0; i <= lastAddrIndx; ++i)
9311 (*MIB).addOperand(*argOpers[i]);
9313 // We only support register and immediate values
9314 assert((argOpers[valArgIndx]->isReg() ||
9315 argOpers[valArgIndx]->isImm()) &&
9318 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9319 if (argOpers[valArgIndx]->isReg())
9320 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9322 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9323 (*MIB).addOperand(*argOpers[valArgIndx]);
9325 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9328 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9333 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9334 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9338 // Cmp and exchange if none has modified the memory location
9339 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9340 for (int i=0; i <= lastAddrIndx; ++i)
9341 (*MIB).addOperand(*argOpers[i]);
9343 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9344 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9345 mInstr->memoperands_end());
9347 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9348 MIB.addReg(X86::EAX);
9351 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9353 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9357 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9358 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9361 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9362 unsigned numArgs, bool memArg) const {
9364 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9365 "Target must have SSE4.2 or AVX features enabled");
9367 DebugLoc dl = MI->getDebugLoc();
9368 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9372 if (!Subtarget->hasAVX()) {
9374 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9376 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9379 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9381 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9384 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
9386 for (unsigned i = 0; i < numArgs; ++i) {
9387 MachineOperand &Op = MI->getOperand(i+1);
9389 if (!(Op.isReg() && Op.isImplicit()))
9393 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9396 MI->eraseFromParent();
9402 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9404 MachineBasicBlock *MBB) const {
9405 // Emit code to save XMM registers to the stack. The ABI says that the
9406 // number of registers to save is given in %al, so it's theoretically
9407 // possible to do an indirect jump trick to avoid saving all of them,
9408 // however this code takes a simpler approach and just executes all
9409 // of the stores if %al is non-zero. It's less code, and it's probably
9410 // easier on the hardware branch predictor, and stores aren't all that
9411 // expensive anyway.
9413 // Create the new basic blocks. One block contains all the XMM stores,
9414 // and one block is the final destination regardless of whether any
9415 // stores were performed.
9416 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9417 MachineFunction *F = MBB->getParent();
9418 MachineFunction::iterator MBBIter = MBB;
9420 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9421 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9422 F->insert(MBBIter, XMMSaveMBB);
9423 F->insert(MBBIter, EndMBB);
9425 // Transfer the remainder of MBB and its successor edges to EndMBB.
9426 EndMBB->splice(EndMBB->begin(), MBB,
9427 llvm::next(MachineBasicBlock::iterator(MI)),
9429 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9431 // The original block will now fall through to the XMM save block.
9432 MBB->addSuccessor(XMMSaveMBB);
9433 // The XMMSaveMBB will fall through to the end block.
9434 XMMSaveMBB->addSuccessor(EndMBB);
9436 // Now add the instructions.
9437 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9438 DebugLoc DL = MI->getDebugLoc();
9440 unsigned CountReg = MI->getOperand(0).getReg();
9441 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9442 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9444 if (!Subtarget->isTargetWin64()) {
9445 // If %al is 0, branch around the XMM save block.
9446 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9447 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9448 MBB->addSuccessor(EndMBB);
9451 // In the XMM save block, save all the XMM argument registers.
9452 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9453 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9454 MachineMemOperand *MMO =
9455 F->getMachineMemOperand(
9456 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9457 MachineMemOperand::MOStore,
9458 /*Size=*/16, /*Align=*/16);
9459 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9460 .addFrameIndex(RegSaveFrameIndex)
9461 .addImm(/*Scale=*/1)
9462 .addReg(/*IndexReg=*/0)
9463 .addImm(/*Disp=*/Offset)
9464 .addReg(/*Segment=*/0)
9465 .addReg(MI->getOperand(i).getReg())
9466 .addMemOperand(MMO);
9469 MI->eraseFromParent(); // The pseudo instruction is gone now.
9475 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9476 MachineBasicBlock *BB) const {
9477 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9478 DebugLoc DL = MI->getDebugLoc();
9480 // To "insert" a SELECT_CC instruction, we actually have to insert the
9481 // diamond control-flow pattern. The incoming instruction knows the
9482 // destination vreg to set, the condition code register to branch on, the
9483 // true/false values to select between, and a branch opcode to use.
9484 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9485 MachineFunction::iterator It = BB;
9491 // cmpTY ccX, r1, r2
9493 // fallthrough --> copy0MBB
9494 MachineBasicBlock *thisMBB = BB;
9495 MachineFunction *F = BB->getParent();
9496 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9497 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9498 F->insert(It, copy0MBB);
9499 F->insert(It, sinkMBB);
9501 // If the EFLAGS register isn't dead in the terminator, then claim that it's
9502 // live into the sink and copy blocks.
9503 const MachineFunction *MF = BB->getParent();
9504 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9505 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9507 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9508 const MachineOperand &MO = MI->getOperand(I);
9509 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9510 unsigned Reg = MO.getReg();
9511 if (Reg != X86::EFLAGS) continue;
9512 copy0MBB->addLiveIn(Reg);
9513 sinkMBB->addLiveIn(Reg);
9516 // Transfer the remainder of BB and its successor edges to sinkMBB.
9517 sinkMBB->splice(sinkMBB->begin(), BB,
9518 llvm::next(MachineBasicBlock::iterator(MI)),
9520 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9522 // Add the true and fallthrough blocks as its successors.
9523 BB->addSuccessor(copy0MBB);
9524 BB->addSuccessor(sinkMBB);
9526 // Create the conditional branch instruction.
9528 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9529 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9532 // %FalseValue = ...
9533 // # fallthrough to sinkMBB
9534 copy0MBB->addSuccessor(sinkMBB);
9537 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9539 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9540 TII->get(X86::PHI), MI->getOperand(0).getReg())
9541 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9542 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9544 MI->eraseFromParent(); // The pseudo instruction is gone now.
9549 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
9550 MachineBasicBlock *BB) const {
9551 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9552 DebugLoc DL = MI->getDebugLoc();
9554 // The lowering is pretty easy: we're just emitting the call to _alloca. The
9555 // non-trivial part is impdef of ESP.
9556 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9559 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9560 .addExternalSymbol("_alloca")
9561 .addReg(X86::EAX, RegState::Implicit)
9562 .addReg(X86::ESP, RegState::Implicit)
9563 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9564 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9565 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9567 MI->eraseFromParent(); // The pseudo instruction is gone now.
9572 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9573 MachineBasicBlock *BB) const {
9574 // This is pretty easy. We're taking the value that we received from
9575 // our load from the relocation, sticking it in either RDI (x86-64)
9576 // or EAX and doing an indirect call. The return value will then
9577 // be in the normal return register.
9578 const X86InstrInfo *TII
9579 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9580 DebugLoc DL = MI->getDebugLoc();
9581 MachineFunction *F = BB->getParent();
9583 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
9584 assert(MI->getOperand(3).isGlobal() && "This should be a global");
9586 if (Subtarget->is64Bit()) {
9587 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9588 TII->get(X86::MOV64rm), X86::RDI)
9590 .addImm(0).addReg(0)
9591 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9592 MI->getOperand(3).getTargetFlags())
9594 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
9595 addDirectMem(MIB, X86::RDI);
9596 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
9597 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9598 TII->get(X86::MOV32rm), X86::EAX)
9600 .addImm(0).addReg(0)
9601 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9602 MI->getOperand(3).getTargetFlags())
9604 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9605 addDirectMem(MIB, X86::EAX);
9607 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9608 TII->get(X86::MOV32rm), X86::EAX)
9609 .addReg(TII->getGlobalBaseReg(F))
9610 .addImm(0).addReg(0)
9611 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9612 MI->getOperand(3).getTargetFlags())
9614 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9615 addDirectMem(MIB, X86::EAX);
9618 MI->eraseFromParent(); // The pseudo instruction is gone now.
9623 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
9624 MachineBasicBlock *BB) const {
9625 switch (MI->getOpcode()) {
9626 default: assert(false && "Unexpected instr type to insert");
9627 case X86::MINGW_ALLOCA:
9628 return EmitLoweredMingwAlloca(MI, BB);
9629 case X86::TLSCall_32:
9630 case X86::TLSCall_64:
9631 return EmitLoweredTLSCall(MI, BB);
9633 case X86::CMOV_FR32:
9634 case X86::CMOV_FR64:
9635 case X86::CMOV_V4F32:
9636 case X86::CMOV_V2F64:
9637 case X86::CMOV_V2I64:
9638 case X86::CMOV_GR16:
9639 case X86::CMOV_GR32:
9640 case X86::CMOV_RFP32:
9641 case X86::CMOV_RFP64:
9642 case X86::CMOV_RFP80:
9643 return EmitLoweredSelect(MI, BB);
9645 case X86::FP32_TO_INT16_IN_MEM:
9646 case X86::FP32_TO_INT32_IN_MEM:
9647 case X86::FP32_TO_INT64_IN_MEM:
9648 case X86::FP64_TO_INT16_IN_MEM:
9649 case X86::FP64_TO_INT32_IN_MEM:
9650 case X86::FP64_TO_INT64_IN_MEM:
9651 case X86::FP80_TO_INT16_IN_MEM:
9652 case X86::FP80_TO_INT32_IN_MEM:
9653 case X86::FP80_TO_INT64_IN_MEM: {
9654 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9655 DebugLoc DL = MI->getDebugLoc();
9657 // Change the floating point control register to use "round towards zero"
9658 // mode when truncating to an integer value.
9659 MachineFunction *F = BB->getParent();
9660 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
9661 addFrameReference(BuildMI(*BB, MI, DL,
9662 TII->get(X86::FNSTCW16m)), CWFrameIdx);
9664 // Load the old value of the high byte of the control word...
9666 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
9667 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
9670 // Set the high part to be round to zero...
9671 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
9674 // Reload the modified control word now...
9675 addFrameReference(BuildMI(*BB, MI, DL,
9676 TII->get(X86::FLDCW16m)), CWFrameIdx);
9678 // Restore the memory image of control word to original value
9679 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
9682 // Get the X86 opcode to use.
9684 switch (MI->getOpcode()) {
9685 default: llvm_unreachable("illegal opcode!");
9686 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
9687 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
9688 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
9689 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
9690 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
9691 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
9692 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
9693 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
9694 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
9698 MachineOperand &Op = MI->getOperand(0);
9700 AM.BaseType = X86AddressMode::RegBase;
9701 AM.Base.Reg = Op.getReg();
9703 AM.BaseType = X86AddressMode::FrameIndexBase;
9704 AM.Base.FrameIndex = Op.getIndex();
9706 Op = MI->getOperand(1);
9708 AM.Scale = Op.getImm();
9709 Op = MI->getOperand(2);
9711 AM.IndexReg = Op.getImm();
9712 Op = MI->getOperand(3);
9713 if (Op.isGlobal()) {
9714 AM.GV = Op.getGlobal();
9716 AM.Disp = Op.getImm();
9718 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
9719 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
9721 // Reload the original control word now.
9722 addFrameReference(BuildMI(*BB, MI, DL,
9723 TII->get(X86::FLDCW16m)), CWFrameIdx);
9725 MI->eraseFromParent(); // The pseudo instruction is gone now.
9728 // String/text processing lowering.
9729 case X86::PCMPISTRM128REG:
9730 case X86::VPCMPISTRM128REG:
9731 return EmitPCMP(MI, BB, 3, false /* in-mem */);
9732 case X86::PCMPISTRM128MEM:
9733 case X86::VPCMPISTRM128MEM:
9734 return EmitPCMP(MI, BB, 3, true /* in-mem */);
9735 case X86::PCMPESTRM128REG:
9736 case X86::VPCMPESTRM128REG:
9737 return EmitPCMP(MI, BB, 5, false /* in mem */);
9738 case X86::PCMPESTRM128MEM:
9739 case X86::VPCMPESTRM128MEM:
9740 return EmitPCMP(MI, BB, 5, true /* in mem */);
9743 case X86::ATOMAND32:
9744 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9745 X86::AND32ri, X86::MOV32rm,
9747 X86::NOT32r, X86::EAX,
9748 X86::GR32RegisterClass);
9750 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
9751 X86::OR32ri, X86::MOV32rm,
9753 X86::NOT32r, X86::EAX,
9754 X86::GR32RegisterClass);
9755 case X86::ATOMXOR32:
9756 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
9757 X86::XOR32ri, X86::MOV32rm,
9759 X86::NOT32r, X86::EAX,
9760 X86::GR32RegisterClass);
9761 case X86::ATOMNAND32:
9762 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9763 X86::AND32ri, X86::MOV32rm,
9765 X86::NOT32r, X86::EAX,
9766 X86::GR32RegisterClass, true);
9767 case X86::ATOMMIN32:
9768 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
9769 case X86::ATOMMAX32:
9770 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
9771 case X86::ATOMUMIN32:
9772 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
9773 case X86::ATOMUMAX32:
9774 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
9776 case X86::ATOMAND16:
9777 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9778 X86::AND16ri, X86::MOV16rm,
9780 X86::NOT16r, X86::AX,
9781 X86::GR16RegisterClass);
9783 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
9784 X86::OR16ri, X86::MOV16rm,
9786 X86::NOT16r, X86::AX,
9787 X86::GR16RegisterClass);
9788 case X86::ATOMXOR16:
9789 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
9790 X86::XOR16ri, X86::MOV16rm,
9792 X86::NOT16r, X86::AX,
9793 X86::GR16RegisterClass);
9794 case X86::ATOMNAND16:
9795 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9796 X86::AND16ri, X86::MOV16rm,
9798 X86::NOT16r, X86::AX,
9799 X86::GR16RegisterClass, true);
9800 case X86::ATOMMIN16:
9801 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
9802 case X86::ATOMMAX16:
9803 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
9804 case X86::ATOMUMIN16:
9805 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
9806 case X86::ATOMUMAX16:
9807 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
9810 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9811 X86::AND8ri, X86::MOV8rm,
9813 X86::NOT8r, X86::AL,
9814 X86::GR8RegisterClass);
9816 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
9817 X86::OR8ri, X86::MOV8rm,
9819 X86::NOT8r, X86::AL,
9820 X86::GR8RegisterClass);
9822 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
9823 X86::XOR8ri, X86::MOV8rm,
9825 X86::NOT8r, X86::AL,
9826 X86::GR8RegisterClass);
9827 case X86::ATOMNAND8:
9828 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9829 X86::AND8ri, X86::MOV8rm,
9831 X86::NOT8r, X86::AL,
9832 X86::GR8RegisterClass, true);
9833 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
9834 // This group is for 64-bit host.
9835 case X86::ATOMAND64:
9836 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9837 X86::AND64ri32, X86::MOV64rm,
9839 X86::NOT64r, X86::RAX,
9840 X86::GR64RegisterClass);
9842 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
9843 X86::OR64ri32, X86::MOV64rm,
9845 X86::NOT64r, X86::RAX,
9846 X86::GR64RegisterClass);
9847 case X86::ATOMXOR64:
9848 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
9849 X86::XOR64ri32, X86::MOV64rm,
9851 X86::NOT64r, X86::RAX,
9852 X86::GR64RegisterClass);
9853 case X86::ATOMNAND64:
9854 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9855 X86::AND64ri32, X86::MOV64rm,
9857 X86::NOT64r, X86::RAX,
9858 X86::GR64RegisterClass, true);
9859 case X86::ATOMMIN64:
9860 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
9861 case X86::ATOMMAX64:
9862 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
9863 case X86::ATOMUMIN64:
9864 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
9865 case X86::ATOMUMAX64:
9866 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
9868 // This group does 64-bit operations on a 32-bit host.
9869 case X86::ATOMAND6432:
9870 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9871 X86::AND32rr, X86::AND32rr,
9872 X86::AND32ri, X86::AND32ri,
9874 case X86::ATOMOR6432:
9875 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9876 X86::OR32rr, X86::OR32rr,
9877 X86::OR32ri, X86::OR32ri,
9879 case X86::ATOMXOR6432:
9880 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9881 X86::XOR32rr, X86::XOR32rr,
9882 X86::XOR32ri, X86::XOR32ri,
9884 case X86::ATOMNAND6432:
9885 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9886 X86::AND32rr, X86::AND32rr,
9887 X86::AND32ri, X86::AND32ri,
9889 case X86::ATOMADD6432:
9890 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9891 X86::ADD32rr, X86::ADC32rr,
9892 X86::ADD32ri, X86::ADC32ri,
9894 case X86::ATOMSUB6432:
9895 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9896 X86::SUB32rr, X86::SBB32rr,
9897 X86::SUB32ri, X86::SBB32ri,
9899 case X86::ATOMSWAP6432:
9900 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9901 X86::MOV32rr, X86::MOV32rr,
9902 X86::MOV32ri, X86::MOV32ri,
9904 case X86::VASTART_SAVE_XMM_REGS:
9905 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
9909 //===----------------------------------------------------------------------===//
9910 // X86 Optimization Hooks
9911 //===----------------------------------------------------------------------===//
9913 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9917 const SelectionDAG &DAG,
9918 unsigned Depth) const {
9919 unsigned Opc = Op.getOpcode();
9920 assert((Opc >= ISD::BUILTIN_OP_END ||
9921 Opc == ISD::INTRINSIC_WO_CHAIN ||
9922 Opc == ISD::INTRINSIC_W_CHAIN ||
9923 Opc == ISD::INTRINSIC_VOID) &&
9924 "Should use MaskedValueIsZero if you don't know whether Op"
9925 " is a target node!");
9927 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
9939 // These nodes' second result is a boolean.
9940 if (Op.getResNo() == 0)
9944 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
9945 Mask.getBitWidth() - 1);
9950 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
9951 unsigned Depth) const {
9952 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
9953 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
9954 return Op.getValueType().getScalarType().getSizeInBits();
9960 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
9961 /// node is a GlobalAddress + offset.
9962 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
9963 const GlobalValue* &GA,
9964 int64_t &Offset) const {
9965 if (N->getOpcode() == X86ISD::Wrapper) {
9966 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
9967 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
9968 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
9972 return TargetLowering::isGAPlusOffset(N, GA, Offset);
9975 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
9976 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
9977 /// if the load addresses are consecutive, non-overlapping, and in the right
9979 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
9980 const TargetLowering &TLI) {
9981 DebugLoc dl = N->getDebugLoc();
9982 EVT VT = N->getValueType(0);
9984 if (VT.getSizeInBits() != 128)
9987 SmallVector<SDValue, 16> Elts;
9988 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
9989 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
9991 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
9994 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
9995 /// generation and convert it from being a bunch of shuffles and extracts
9996 /// to a simple store and scalar loads to extract the elements.
9997 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
9998 const TargetLowering &TLI) {
9999 SDValue InputVector = N->getOperand(0);
10001 // Only operate on vectors of 4 elements, where the alternative shuffling
10002 // gets to be more expensive.
10003 if (InputVector.getValueType() != MVT::v4i32)
10006 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10007 // single use which is a sign-extend or zero-extend, and all elements are
10009 SmallVector<SDNode *, 4> Uses;
10010 unsigned ExtractedElements = 0;
10011 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10012 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10013 if (UI.getUse().getResNo() != InputVector.getResNo())
10016 SDNode *Extract = *UI;
10017 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10020 if (Extract->getValueType(0) != MVT::i32)
10022 if (!Extract->hasOneUse())
10024 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10025 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10027 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10030 // Record which element was extracted.
10031 ExtractedElements |=
10032 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10034 Uses.push_back(Extract);
10037 // If not all the elements were used, this may not be worthwhile.
10038 if (ExtractedElements != 15)
10041 // Ok, we've now decided to do the transformation.
10042 DebugLoc dl = InputVector.getDebugLoc();
10044 // Store the value to a temporary stack slot.
10045 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10046 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10047 MachinePointerInfo(), false, false, 0);
10049 // Replace each use (extract) with a load of the appropriate element.
10050 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10051 UE = Uses.end(); UI != UE; ++UI) {
10052 SDNode *Extract = *UI;
10054 // Compute the element's address.
10055 SDValue Idx = Extract->getOperand(1);
10057 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10058 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10059 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10061 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10062 StackPtr, OffsetVal);
10064 // Load the scalar.
10065 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10066 ScalarAddr, MachinePointerInfo(),
10069 // Replace the exact with the load.
10070 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10073 // The replacement was made in place; don't return anything.
10077 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10078 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10079 const X86Subtarget *Subtarget) {
10080 DebugLoc DL = N->getDebugLoc();
10081 SDValue Cond = N->getOperand(0);
10082 // Get the LHS/RHS of the select.
10083 SDValue LHS = N->getOperand(1);
10084 SDValue RHS = N->getOperand(2);
10086 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10087 // instructions match the semantics of the common C idiom x<y?x:y but not
10088 // x<=y?x:y, because of how they handle negative zero (which can be
10089 // ignored in unsafe-math mode).
10090 if (Subtarget->hasSSE2() &&
10091 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10092 Cond.getOpcode() == ISD::SETCC) {
10093 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10095 unsigned Opcode = 0;
10096 // Check for x CC y ? x : y.
10097 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10098 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10102 // Converting this to a min would handle NaNs incorrectly, and swapping
10103 // the operands would cause it to handle comparisons between positive
10104 // and negative zero incorrectly.
10105 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10106 if (!UnsafeFPMath &&
10107 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10109 std::swap(LHS, RHS);
10111 Opcode = X86ISD::FMIN;
10114 // Converting this to a min would handle comparisons between positive
10115 // and negative zero incorrectly.
10116 if (!UnsafeFPMath &&
10117 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10119 Opcode = X86ISD::FMIN;
10122 // Converting this to a min would handle both negative zeros and NaNs
10123 // incorrectly, but we can swap the operands to fix both.
10124 std::swap(LHS, RHS);
10128 Opcode = X86ISD::FMIN;
10132 // Converting this to a max would handle comparisons between positive
10133 // and negative zero incorrectly.
10134 if (!UnsafeFPMath &&
10135 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10137 Opcode = X86ISD::FMAX;
10140 // Converting this to a max would handle NaNs incorrectly, and swapping
10141 // the operands would cause it to handle comparisons between positive
10142 // and negative zero incorrectly.
10143 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10144 if (!UnsafeFPMath &&
10145 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10147 std::swap(LHS, RHS);
10149 Opcode = X86ISD::FMAX;
10152 // Converting this to a max would handle both negative zeros and NaNs
10153 // incorrectly, but we can swap the operands to fix both.
10154 std::swap(LHS, RHS);
10158 Opcode = X86ISD::FMAX;
10161 // Check for x CC y ? y : x -- a min/max with reversed arms.
10162 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10163 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10167 // Converting this to a min would handle comparisons between positive
10168 // and negative zero incorrectly, and swapping the operands would
10169 // cause it to handle NaNs incorrectly.
10170 if (!UnsafeFPMath &&
10171 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10172 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10174 std::swap(LHS, RHS);
10176 Opcode = X86ISD::FMIN;
10179 // Converting this to a min would handle NaNs incorrectly.
10180 if (!UnsafeFPMath &&
10181 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10183 Opcode = X86ISD::FMIN;
10186 // Converting this to a min would handle both negative zeros and NaNs
10187 // incorrectly, but we can swap the operands to fix both.
10188 std::swap(LHS, RHS);
10192 Opcode = X86ISD::FMIN;
10196 // Converting this to a max would handle NaNs incorrectly.
10197 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10199 Opcode = X86ISD::FMAX;
10202 // Converting this to a max would handle comparisons between positive
10203 // and negative zero incorrectly, and swapping the operands would
10204 // cause it to handle NaNs incorrectly.
10205 if (!UnsafeFPMath &&
10206 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10207 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10209 std::swap(LHS, RHS);
10211 Opcode = X86ISD::FMAX;
10214 // Converting this to a max would handle both negative zeros and NaNs
10215 // incorrectly, but we can swap the operands to fix both.
10216 std::swap(LHS, RHS);
10220 Opcode = X86ISD::FMAX;
10226 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10229 // If this is a select between two integer constants, try to do some
10231 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10232 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10233 // Don't do this for crazy integer types.
10234 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10235 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10236 // so that TrueC (the true value) is larger than FalseC.
10237 bool NeedsCondInvert = false;
10239 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10240 // Efficiently invertible.
10241 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
10242 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
10243 isa<ConstantSDNode>(Cond.getOperand(1))))) {
10244 NeedsCondInvert = true;
10245 std::swap(TrueC, FalseC);
10248 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
10249 if (FalseC->getAPIntValue() == 0 &&
10250 TrueC->getAPIntValue().isPowerOf2()) {
10251 if (NeedsCondInvert) // Invert the condition if needed.
10252 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10253 DAG.getConstant(1, Cond.getValueType()));
10255 // Zero extend the condition if needed.
10256 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10258 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10259 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10260 DAG.getConstant(ShAmt, MVT::i8));
10263 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10264 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10265 if (NeedsCondInvert) // Invert the condition if needed.
10266 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10267 DAG.getConstant(1, Cond.getValueType()));
10269 // Zero extend the condition if needed.
10270 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10271 FalseC->getValueType(0), Cond);
10272 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10273 SDValue(FalseC, 0));
10276 // Optimize cases that will turn into an LEA instruction. This requires
10277 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10278 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10279 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10280 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10282 bool isFastMultiplier = false;
10284 switch ((unsigned char)Diff) {
10286 case 1: // result = add base, cond
10287 case 2: // result = lea base( , cond*2)
10288 case 3: // result = lea base(cond, cond*2)
10289 case 4: // result = lea base( , cond*4)
10290 case 5: // result = lea base(cond, cond*4)
10291 case 8: // result = lea base( , cond*8)
10292 case 9: // result = lea base(cond, cond*8)
10293 isFastMultiplier = true;
10298 if (isFastMultiplier) {
10299 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10300 if (NeedsCondInvert) // Invert the condition if needed.
10301 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10302 DAG.getConstant(1, Cond.getValueType()));
10304 // Zero extend the condition if needed.
10305 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10307 // Scale the condition by the difference.
10309 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10310 DAG.getConstant(Diff, Cond.getValueType()));
10312 // Add the base if non-zero.
10313 if (FalseC->getAPIntValue() != 0)
10314 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10315 SDValue(FalseC, 0));
10325 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10326 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10327 TargetLowering::DAGCombinerInfo &DCI) {
10328 DebugLoc DL = N->getDebugLoc();
10330 // If the flag operand isn't dead, don't touch this CMOV.
10331 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10334 // If this is a select between two integer constants, try to do some
10335 // optimizations. Note that the operands are ordered the opposite of SELECT
10337 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10338 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10339 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10340 // larger than FalseC (the false value).
10341 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10343 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10344 CC = X86::GetOppositeBranchCondition(CC);
10345 std::swap(TrueC, FalseC);
10348 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
10349 // This is efficient for any integer data type (including i8/i16) and
10351 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10352 SDValue Cond = N->getOperand(3);
10353 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10354 DAG.getConstant(CC, MVT::i8), Cond);
10356 // Zero extend the condition if needed.
10357 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10359 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10360 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10361 DAG.getConstant(ShAmt, MVT::i8));
10362 if (N->getNumValues() == 2) // Dead flag value?
10363 return DCI.CombineTo(N, Cond, SDValue());
10367 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
10368 // for any integer data type, including i8/i16.
10369 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10370 SDValue Cond = N->getOperand(3);
10371 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10372 DAG.getConstant(CC, MVT::i8), Cond);
10374 // Zero extend the condition if needed.
10375 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10376 FalseC->getValueType(0), Cond);
10377 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10378 SDValue(FalseC, 0));
10380 if (N->getNumValues() == 2) // Dead flag value?
10381 return DCI.CombineTo(N, Cond, SDValue());
10385 // Optimize cases that will turn into an LEA instruction. This requires
10386 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10387 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10388 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10389 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10391 bool isFastMultiplier = false;
10393 switch ((unsigned char)Diff) {
10395 case 1: // result = add base, cond
10396 case 2: // result = lea base( , cond*2)
10397 case 3: // result = lea base(cond, cond*2)
10398 case 4: // result = lea base( , cond*4)
10399 case 5: // result = lea base(cond, cond*4)
10400 case 8: // result = lea base( , cond*8)
10401 case 9: // result = lea base(cond, cond*8)
10402 isFastMultiplier = true;
10407 if (isFastMultiplier) {
10408 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10409 SDValue Cond = N->getOperand(3);
10410 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10411 DAG.getConstant(CC, MVT::i8), Cond);
10412 // Zero extend the condition if needed.
10413 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10415 // Scale the condition by the difference.
10417 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10418 DAG.getConstant(Diff, Cond.getValueType()));
10420 // Add the base if non-zero.
10421 if (FalseC->getAPIntValue() != 0)
10422 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10423 SDValue(FalseC, 0));
10424 if (N->getNumValues() == 2) // Dead flag value?
10425 return DCI.CombineTo(N, Cond, SDValue());
10435 /// PerformMulCombine - Optimize a single multiply with constant into two
10436 /// in order to implement it with two cheaper instructions, e.g.
10437 /// LEA + SHL, LEA + LEA.
10438 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10439 TargetLowering::DAGCombinerInfo &DCI) {
10440 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10443 EVT VT = N->getValueType(0);
10444 if (VT != MVT::i64)
10447 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10450 uint64_t MulAmt = C->getZExtValue();
10451 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10454 uint64_t MulAmt1 = 0;
10455 uint64_t MulAmt2 = 0;
10456 if ((MulAmt % 9) == 0) {
10458 MulAmt2 = MulAmt / 9;
10459 } else if ((MulAmt % 5) == 0) {
10461 MulAmt2 = MulAmt / 5;
10462 } else if ((MulAmt % 3) == 0) {
10464 MulAmt2 = MulAmt / 3;
10467 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10468 DebugLoc DL = N->getDebugLoc();
10470 if (isPowerOf2_64(MulAmt2) &&
10471 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10472 // If second multiplifer is pow2, issue it first. We want the multiply by
10473 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10475 std::swap(MulAmt1, MulAmt2);
10478 if (isPowerOf2_64(MulAmt1))
10479 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10480 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10482 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10483 DAG.getConstant(MulAmt1, VT));
10485 if (isPowerOf2_64(MulAmt2))
10486 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10487 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10489 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10490 DAG.getConstant(MulAmt2, VT));
10492 // Do not add new nodes to DAG combiner worklist.
10493 DCI.CombineTo(N, NewMul, false);
10498 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10499 SDValue N0 = N->getOperand(0);
10500 SDValue N1 = N->getOperand(1);
10501 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10502 EVT VT = N0.getValueType();
10504 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10505 // since the result of setcc_c is all zero's or all ones.
10506 if (N1C && N0.getOpcode() == ISD::AND &&
10507 N0.getOperand(1).getOpcode() == ISD::Constant) {
10508 SDValue N00 = N0.getOperand(0);
10509 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10510 ((N00.getOpcode() == ISD::ANY_EXTEND ||
10511 N00.getOpcode() == ISD::ZERO_EXTEND) &&
10512 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10513 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10514 APInt ShAmt = N1C->getAPIntValue();
10515 Mask = Mask.shl(ShAmt);
10517 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10518 N00, DAG.getConstant(Mask, VT));
10525 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10527 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10528 const X86Subtarget *Subtarget) {
10529 EVT VT = N->getValueType(0);
10530 if (!VT.isVector() && VT.isInteger() &&
10531 N->getOpcode() == ISD::SHL)
10532 return PerformSHLCombine(N, DAG);
10534 // On X86 with SSE2 support, we can transform this to a vector shift if
10535 // all elements are shifted by the same amount. We can't do this in legalize
10536 // because the a constant vector is typically transformed to a constant pool
10537 // so we have no knowledge of the shift amount.
10538 if (!Subtarget->hasSSE2())
10541 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10544 SDValue ShAmtOp = N->getOperand(1);
10545 EVT EltVT = VT.getVectorElementType();
10546 DebugLoc DL = N->getDebugLoc();
10547 SDValue BaseShAmt = SDValue();
10548 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10549 unsigned NumElts = VT.getVectorNumElements();
10551 for (; i != NumElts; ++i) {
10552 SDValue Arg = ShAmtOp.getOperand(i);
10553 if (Arg.getOpcode() == ISD::UNDEF) continue;
10557 for (; i != NumElts; ++i) {
10558 SDValue Arg = ShAmtOp.getOperand(i);
10559 if (Arg.getOpcode() == ISD::UNDEF) continue;
10560 if (Arg != BaseShAmt) {
10564 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10565 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10566 SDValue InVec = ShAmtOp.getOperand(0);
10567 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10568 unsigned NumElts = InVec.getValueType().getVectorNumElements();
10570 for (; i != NumElts; ++i) {
10571 SDValue Arg = InVec.getOperand(i);
10572 if (Arg.getOpcode() == ISD::UNDEF) continue;
10576 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10577 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10578 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10579 if (C->getZExtValue() == SplatIdx)
10580 BaseShAmt = InVec.getOperand(1);
10583 if (BaseShAmt.getNode() == 0)
10584 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
10585 DAG.getIntPtrConstant(0));
10589 // The shift amount is an i32.
10590 if (EltVT.bitsGT(MVT::i32))
10591 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
10592 else if (EltVT.bitsLT(MVT::i32))
10593 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
10595 // The shift amount is identical so we can do a vector shift.
10596 SDValue ValOp = N->getOperand(0);
10597 switch (N->getOpcode()) {
10599 llvm_unreachable("Unknown shift opcode!");
10602 if (VT == MVT::v2i64)
10603 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10604 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10606 if (VT == MVT::v4i32)
10607 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10608 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10610 if (VT == MVT::v8i16)
10611 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10612 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10616 if (VT == MVT::v4i32)
10617 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10618 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10620 if (VT == MVT::v8i16)
10621 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10622 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10626 if (VT == MVT::v2i64)
10627 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10628 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10630 if (VT == MVT::v4i32)
10631 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10632 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10634 if (VT == MVT::v8i16)
10635 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10636 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10643 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
10644 TargetLowering::DAGCombinerInfo &DCI,
10645 const X86Subtarget *Subtarget) {
10646 if (DCI.isBeforeLegalizeOps())
10649 EVT VT = N->getValueType(0);
10650 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
10653 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
10654 SDValue N0 = N->getOperand(0);
10655 SDValue N1 = N->getOperand(1);
10656 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
10658 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
10660 if (!N0.hasOneUse() || !N1.hasOneUse())
10663 SDValue ShAmt0 = N0.getOperand(1);
10664 if (ShAmt0.getValueType() != MVT::i8)
10666 SDValue ShAmt1 = N1.getOperand(1);
10667 if (ShAmt1.getValueType() != MVT::i8)
10669 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
10670 ShAmt0 = ShAmt0.getOperand(0);
10671 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
10672 ShAmt1 = ShAmt1.getOperand(0);
10674 DebugLoc DL = N->getDebugLoc();
10675 unsigned Opc = X86ISD::SHLD;
10676 SDValue Op0 = N0.getOperand(0);
10677 SDValue Op1 = N1.getOperand(0);
10678 if (ShAmt0.getOpcode() == ISD::SUB) {
10679 Opc = X86ISD::SHRD;
10680 std::swap(Op0, Op1);
10681 std::swap(ShAmt0, ShAmt1);
10684 unsigned Bits = VT.getSizeInBits();
10685 if (ShAmt1.getOpcode() == ISD::SUB) {
10686 SDValue Sum = ShAmt1.getOperand(0);
10687 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
10688 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
10689 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
10690 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
10691 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
10692 return DAG.getNode(Opc, DL, VT,
10694 DAG.getNode(ISD::TRUNCATE, DL,
10697 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
10698 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
10700 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
10701 return DAG.getNode(Opc, DL, VT,
10702 N0.getOperand(0), N1.getOperand(0),
10703 DAG.getNode(ISD::TRUNCATE, DL,
10710 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
10711 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
10712 const X86Subtarget *Subtarget) {
10713 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
10714 // the FP state in cases where an emms may be missing.
10715 // A preferable solution to the general problem is to figure out the right
10716 // places to insert EMMS. This qualifies as a quick hack.
10718 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
10719 StoreSDNode *St = cast<StoreSDNode>(N);
10720 EVT VT = St->getValue().getValueType();
10721 if (VT.getSizeInBits() != 64)
10724 const Function *F = DAG.getMachineFunction().getFunction();
10725 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
10726 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
10727 && Subtarget->hasSSE2();
10728 if ((VT.isVector() ||
10729 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
10730 isa<LoadSDNode>(St->getValue()) &&
10731 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
10732 St->getChain().hasOneUse() && !St->isVolatile()) {
10733 SDNode* LdVal = St->getValue().getNode();
10734 LoadSDNode *Ld = 0;
10735 int TokenFactorIndex = -1;
10736 SmallVector<SDValue, 8> Ops;
10737 SDNode* ChainVal = St->getChain().getNode();
10738 // Must be a store of a load. We currently handle two cases: the load
10739 // is a direct child, and it's under an intervening TokenFactor. It is
10740 // possible to dig deeper under nested TokenFactors.
10741 if (ChainVal == LdVal)
10742 Ld = cast<LoadSDNode>(St->getChain());
10743 else if (St->getValue().hasOneUse() &&
10744 ChainVal->getOpcode() == ISD::TokenFactor) {
10745 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
10746 if (ChainVal->getOperand(i).getNode() == LdVal) {
10747 TokenFactorIndex = i;
10748 Ld = cast<LoadSDNode>(St->getValue());
10750 Ops.push_back(ChainVal->getOperand(i));
10754 if (!Ld || !ISD::isNormalLoad(Ld))
10757 // If this is not the MMX case, i.e. we are just turning i64 load/store
10758 // into f64 load/store, avoid the transformation if there are multiple
10759 // uses of the loaded value.
10760 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
10763 DebugLoc LdDL = Ld->getDebugLoc();
10764 DebugLoc StDL = N->getDebugLoc();
10765 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
10766 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
10768 if (Subtarget->is64Bit() || F64IsLegal) {
10769 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
10770 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
10771 Ld->getPointerInfo(), Ld->isVolatile(),
10772 Ld->isNonTemporal(), Ld->getAlignment());
10773 SDValue NewChain = NewLd.getValue(1);
10774 if (TokenFactorIndex != -1) {
10775 Ops.push_back(NewChain);
10776 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10779 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
10780 St->getPointerInfo(),
10781 St->isVolatile(), St->isNonTemporal(),
10782 St->getAlignment());
10785 // Otherwise, lower to two pairs of 32-bit loads / stores.
10786 SDValue LoAddr = Ld->getBasePtr();
10787 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
10788 DAG.getConstant(4, MVT::i32));
10790 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
10791 Ld->getPointerInfo(),
10792 Ld->isVolatile(), Ld->isNonTemporal(),
10793 Ld->getAlignment());
10794 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
10795 Ld->getPointerInfo().getWithOffset(4),
10796 Ld->isVolatile(), Ld->isNonTemporal(),
10797 MinAlign(Ld->getAlignment(), 4));
10799 SDValue NewChain = LoLd.getValue(1);
10800 if (TokenFactorIndex != -1) {
10801 Ops.push_back(LoLd);
10802 Ops.push_back(HiLd);
10803 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10807 LoAddr = St->getBasePtr();
10808 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
10809 DAG.getConstant(4, MVT::i32));
10811 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
10812 St->getPointerInfo(),
10813 St->isVolatile(), St->isNonTemporal(),
10814 St->getAlignment());
10815 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
10816 St->getPointerInfo().getWithOffset(4),
10818 St->isNonTemporal(),
10819 MinAlign(St->getAlignment(), 4));
10820 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
10825 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
10826 /// X86ISD::FXOR nodes.
10827 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
10828 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
10829 // F[X]OR(0.0, x) -> x
10830 // F[X]OR(x, 0.0) -> x
10831 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10832 if (C->getValueAPF().isPosZero())
10833 return N->getOperand(1);
10834 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10835 if (C->getValueAPF().isPosZero())
10836 return N->getOperand(0);
10840 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
10841 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
10842 // FAND(0.0, x) -> 0.0
10843 // FAND(x, 0.0) -> 0.0
10844 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10845 if (C->getValueAPF().isPosZero())
10846 return N->getOperand(0);
10847 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10848 if (C->getValueAPF().isPosZero())
10849 return N->getOperand(1);
10853 static SDValue PerformBTCombine(SDNode *N,
10855 TargetLowering::DAGCombinerInfo &DCI) {
10856 // BT ignores high bits in the bit index operand.
10857 SDValue Op1 = N->getOperand(1);
10858 if (Op1.hasOneUse()) {
10859 unsigned BitWidth = Op1.getValueSizeInBits();
10860 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
10861 APInt KnownZero, KnownOne;
10862 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10863 !DCI.isBeforeLegalizeOps());
10864 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10865 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
10866 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
10867 DCI.CommitTargetLoweringOpt(TLO);
10872 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
10873 SDValue Op = N->getOperand(0);
10874 if (Op.getOpcode() == ISD::BIT_CONVERT)
10875 Op = Op.getOperand(0);
10876 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
10877 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
10878 VT.getVectorElementType().getSizeInBits() ==
10879 OpVT.getVectorElementType().getSizeInBits()) {
10880 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
10885 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
10886 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
10887 // (and (i32 x86isd::setcc_carry), 1)
10888 // This eliminates the zext. This transformation is necessary because
10889 // ISD::SETCC is always legalized to i8.
10890 DebugLoc dl = N->getDebugLoc();
10891 SDValue N0 = N->getOperand(0);
10892 EVT VT = N->getValueType(0);
10893 if (N0.getOpcode() == ISD::AND &&
10895 N0.getOperand(0).hasOneUse()) {
10896 SDValue N00 = N0.getOperand(0);
10897 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
10899 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10900 if (!C || C->getZExtValue() != 1)
10902 return DAG.getNode(ISD::AND, dl, VT,
10903 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
10904 N00.getOperand(0), N00.getOperand(1)),
10905 DAG.getConstant(1, VT));
10911 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
10912 DAGCombinerInfo &DCI) const {
10913 SelectionDAG &DAG = DCI.DAG;
10914 switch (N->getOpcode()) {
10916 case ISD::EXTRACT_VECTOR_ELT:
10917 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
10918 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
10919 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
10920 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
10923 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
10924 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
10925 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
10927 case X86ISD::FOR: return PerformFORCombine(N, DAG);
10928 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
10929 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
10930 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
10931 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
10932 case X86ISD::SHUFPS: // Handle all target specific shuffles
10933 case X86ISD::SHUFPD:
10934 case X86ISD::PALIGN:
10935 case X86ISD::PUNPCKHBW:
10936 case X86ISD::PUNPCKHWD:
10937 case X86ISD::PUNPCKHDQ:
10938 case X86ISD::PUNPCKHQDQ:
10939 case X86ISD::UNPCKHPS:
10940 case X86ISD::UNPCKHPD:
10941 case X86ISD::PUNPCKLBW:
10942 case X86ISD::PUNPCKLWD:
10943 case X86ISD::PUNPCKLDQ:
10944 case X86ISD::PUNPCKLQDQ:
10945 case X86ISD::UNPCKLPS:
10946 case X86ISD::UNPCKLPD:
10947 case X86ISD::MOVHLPS:
10948 case X86ISD::MOVLHPS:
10949 case X86ISD::PSHUFD:
10950 case X86ISD::PSHUFHW:
10951 case X86ISD::PSHUFLW:
10952 case X86ISD::MOVSS:
10953 case X86ISD::MOVSD:
10954 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
10960 /// isTypeDesirableForOp - Return true if the target has native support for
10961 /// the specified value type and it is 'desirable' to use the type for the
10962 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
10963 /// instruction encodings are longer and some i16 instructions are slow.
10964 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
10965 if (!isTypeLegal(VT))
10967 if (VT != MVT::i16)
10974 case ISD::SIGN_EXTEND:
10975 case ISD::ZERO_EXTEND:
10976 case ISD::ANY_EXTEND:
10989 /// IsDesirableToPromoteOp - This method query the target whether it is
10990 /// beneficial for dag combiner to promote the specified node. If true, it
10991 /// should return the desired promotion type by reference.
10992 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
10993 EVT VT = Op.getValueType();
10994 if (VT != MVT::i16)
10997 bool Promote = false;
10998 bool Commute = false;
10999 switch (Op.getOpcode()) {
11002 LoadSDNode *LD = cast<LoadSDNode>(Op);
11003 // If the non-extending load has a single use and it's not live out, then it
11004 // might be folded.
11005 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11006 Op.hasOneUse()*/) {
11007 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11008 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11009 // The only case where we'd want to promote LOAD (rather then it being
11010 // promoted as an operand is when it's only use is liveout.
11011 if (UI->getOpcode() != ISD::CopyToReg)
11018 case ISD::SIGN_EXTEND:
11019 case ISD::ZERO_EXTEND:
11020 case ISD::ANY_EXTEND:
11025 SDValue N0 = Op.getOperand(0);
11026 // Look out for (store (shl (load), x)).
11027 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11040 SDValue N0 = Op.getOperand(0);
11041 SDValue N1 = Op.getOperand(1);
11042 if (!Commute && MayFoldLoad(N1))
11044 // Avoid disabling potential load folding opportunities.
11045 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11047 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11057 //===----------------------------------------------------------------------===//
11058 // X86 Inline Assembly Support
11059 //===----------------------------------------------------------------------===//
11061 static bool LowerToBSwap(CallInst *CI) {
11062 // FIXME: this should verify that we are targetting a 486 or better. If not,
11063 // we will turn this bswap into something that will be lowered to logical ops
11064 // instead of emitting the bswap asm. For now, we don't support 486 or lower
11065 // so don't worry about this.
11067 // Verify this is a simple bswap.
11068 if (CI->getNumArgOperands() != 1 ||
11069 CI->getType() != CI->getArgOperand(0)->getType() ||
11070 !CI->getType()->isIntegerTy())
11073 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11074 if (!Ty || Ty->getBitWidth() % 16 != 0)
11077 // Okay, we can do this xform, do so now.
11078 const Type *Tys[] = { Ty };
11079 Module *M = CI->getParent()->getParent()->getParent();
11080 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11082 Value *Op = CI->getArgOperand(0);
11083 Op = CallInst::Create(Int, Op, CI->getName(), CI);
11085 CI->replaceAllUsesWith(Op);
11086 CI->eraseFromParent();
11090 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11091 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11092 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
11094 std::string AsmStr = IA->getAsmString();
11096 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11097 SmallVector<StringRef, 4> AsmPieces;
11098 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
11100 switch (AsmPieces.size()) {
11101 default: return false;
11103 AsmStr = AsmPieces[0];
11105 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
11108 if (AsmPieces.size() == 2 &&
11109 (AsmPieces[0] == "bswap" ||
11110 AsmPieces[0] == "bswapq" ||
11111 AsmPieces[0] == "bswapl") &&
11112 (AsmPieces[1] == "$0" ||
11113 AsmPieces[1] == "${0:q}")) {
11114 // No need to check constraints, nothing other than the equivalent of
11115 // "=r,0" would be valid here.
11116 return LowerToBSwap(CI);
11118 // rorw $$8, ${0:w} --> llvm.bswap.i16
11119 if (CI->getType()->isIntegerTy(16) &&
11120 AsmPieces.size() == 3 &&
11121 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11122 AsmPieces[1] == "$$8," &&
11123 AsmPieces[2] == "${0:w}" &&
11124 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11126 const std::string &Constraints = IA->getConstraintString();
11127 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11128 std::sort(AsmPieces.begin(), AsmPieces.end());
11129 if (AsmPieces.size() == 4 &&
11130 AsmPieces[0] == "~{cc}" &&
11131 AsmPieces[1] == "~{dirflag}" &&
11132 AsmPieces[2] == "~{flags}" &&
11133 AsmPieces[3] == "~{fpsr}") {
11134 return LowerToBSwap(CI);
11139 if (CI->getType()->isIntegerTy(64) &&
11140 Constraints.size() >= 2 &&
11141 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11142 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11143 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
11144 SmallVector<StringRef, 4> Words;
11145 SplitString(AsmPieces[0], Words, " \t");
11146 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11148 SplitString(AsmPieces[1], Words, " \t");
11149 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11151 SplitString(AsmPieces[2], Words, " \t,");
11152 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11153 Words[2] == "%edx") {
11154 return LowerToBSwap(CI);
11166 /// getConstraintType - Given a constraint letter, return the type of
11167 /// constraint it is for this target.
11168 X86TargetLowering::ConstraintType
11169 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11170 if (Constraint.size() == 1) {
11171 switch (Constraint[0]) {
11183 return C_RegisterClass;
11191 return TargetLowering::getConstraintType(Constraint);
11194 /// Examine constraint type and operand type and determine a weight value,
11195 /// where: -1 = invalid match, and 0 = so-so match to 3 = good match.
11196 /// This object must already have been set up with the operand type
11197 /// and the current alternative constraint selected.
11198 int X86TargetLowering::getSingleConstraintMatchWeight(
11199 AsmOperandInfo &info, const char *constraint) const {
11201 Value *CallOperandVal = info.CallOperandVal;
11202 // If we don't have a value, we can't do a match,
11203 // but allow it at the lowest weight.
11204 if (CallOperandVal == NULL)
11206 // Look at the constraint type.
11207 switch (*constraint) {
11209 return TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11212 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11213 if (C->getZExtValue() <= 31)
11222 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11223 /// with another that has more specific requirements based on the type of the
11224 /// corresponding operand.
11225 const char *X86TargetLowering::
11226 LowerXConstraint(EVT ConstraintVT) const {
11227 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11228 // 'f' like normal targets.
11229 if (ConstraintVT.isFloatingPoint()) {
11230 if (Subtarget->hasSSE2())
11232 if (Subtarget->hasSSE1())
11236 return TargetLowering::LowerXConstraint(ConstraintVT);
11239 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11240 /// vector. If it is invalid, don't add anything to Ops.
11241 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11243 std::vector<SDValue>&Ops,
11244 SelectionDAG &DAG) const {
11245 SDValue Result(0, 0);
11247 switch (Constraint) {
11250 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11251 if (C->getZExtValue() <= 31) {
11252 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11258 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11259 if (C->getZExtValue() <= 63) {
11260 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11266 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11267 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11268 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11274 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11275 if (C->getZExtValue() <= 255) {
11276 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11282 // 32-bit signed value
11283 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11284 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11285 C->getSExtValue())) {
11286 // Widen to 64 bits here to get it sign extended.
11287 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11290 // FIXME gcc accepts some relocatable values here too, but only in certain
11291 // memory models; it's complicated.
11296 // 32-bit unsigned value
11297 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11298 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11299 C->getZExtValue())) {
11300 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11304 // FIXME gcc accepts some relocatable values here too, but only in certain
11305 // memory models; it's complicated.
11309 // Literal immediates are always ok.
11310 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11311 // Widen to 64 bits here to get it sign extended.
11312 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11316 // In any sort of PIC mode addresses need to be computed at runtime by
11317 // adding in a register or some sort of table lookup. These can't
11318 // be used as immediates.
11319 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11322 // If we are in non-pic codegen mode, we allow the address of a global (with
11323 // an optional displacement) to be used with 'i'.
11324 GlobalAddressSDNode *GA = 0;
11325 int64_t Offset = 0;
11327 // Match either (GA), (GA+C), (GA+C1+C2), etc.
11329 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11330 Offset += GA->getOffset();
11332 } else if (Op.getOpcode() == ISD::ADD) {
11333 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11334 Offset += C->getZExtValue();
11335 Op = Op.getOperand(0);
11338 } else if (Op.getOpcode() == ISD::SUB) {
11339 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11340 Offset += -C->getZExtValue();
11341 Op = Op.getOperand(0);
11346 // Otherwise, this isn't something we can handle, reject it.
11350 const GlobalValue *GV = GA->getGlobal();
11351 // If we require an extra load to get this address, as in PIC mode, we
11352 // can't accept it.
11353 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
11354 getTargetMachine())))
11357 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
11358 GA->getValueType(0), Offset);
11363 if (Result.getNode()) {
11364 Ops.push_back(Result);
11367 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11370 std::vector<unsigned> X86TargetLowering::
11371 getRegClassForInlineAsmConstraint(const std::string &Constraint,
11373 if (Constraint.size() == 1) {
11374 // FIXME: not handling fp-stack yet!
11375 switch (Constraint[0]) { // GCC X86 Constraint Letters
11376 default: break; // Unknown constraint letter
11377 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
11378 if (Subtarget->is64Bit()) {
11379 if (VT == MVT::i32)
11380 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
11381 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
11382 X86::R10D,X86::R11D,X86::R12D,
11383 X86::R13D,X86::R14D,X86::R15D,
11384 X86::EBP, X86::ESP, 0);
11385 else if (VT == MVT::i16)
11386 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
11387 X86::SI, X86::DI, X86::R8W,X86::R9W,
11388 X86::R10W,X86::R11W,X86::R12W,
11389 X86::R13W,X86::R14W,X86::R15W,
11390 X86::BP, X86::SP, 0);
11391 else if (VT == MVT::i8)
11392 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
11393 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
11394 X86::R10B,X86::R11B,X86::R12B,
11395 X86::R13B,X86::R14B,X86::R15B,
11396 X86::BPL, X86::SPL, 0);
11398 else if (VT == MVT::i64)
11399 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
11400 X86::RSI, X86::RDI, X86::R8, X86::R9,
11401 X86::R10, X86::R11, X86::R12,
11402 X86::R13, X86::R14, X86::R15,
11403 X86::RBP, X86::RSP, 0);
11407 // 32-bit fallthrough
11408 case 'Q': // Q_REGS
11409 if (VT == MVT::i32)
11410 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
11411 else if (VT == MVT::i16)
11412 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
11413 else if (VT == MVT::i8)
11414 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
11415 else if (VT == MVT::i64)
11416 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
11421 return std::vector<unsigned>();
11424 std::pair<unsigned, const TargetRegisterClass*>
11425 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
11427 // First, see if this is a constraint that directly corresponds to an LLVM
11429 if (Constraint.size() == 1) {
11430 // GCC Constraint Letters
11431 switch (Constraint[0]) {
11433 case 'r': // GENERAL_REGS
11434 case 'l': // INDEX_REGS
11436 return std::make_pair(0U, X86::GR8RegisterClass);
11437 if (VT == MVT::i16)
11438 return std::make_pair(0U, X86::GR16RegisterClass);
11439 if (VT == MVT::i32 || !Subtarget->is64Bit())
11440 return std::make_pair(0U, X86::GR32RegisterClass);
11441 return std::make_pair(0U, X86::GR64RegisterClass);
11442 case 'R': // LEGACY_REGS
11444 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
11445 if (VT == MVT::i16)
11446 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
11447 if (VT == MVT::i32 || !Subtarget->is64Bit())
11448 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
11449 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
11450 case 'f': // FP Stack registers.
11451 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
11452 // value to the correct fpstack register class.
11453 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
11454 return std::make_pair(0U, X86::RFP32RegisterClass);
11455 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
11456 return std::make_pair(0U, X86::RFP64RegisterClass);
11457 return std::make_pair(0U, X86::RFP80RegisterClass);
11458 case 'y': // MMX_REGS if MMX allowed.
11459 if (!Subtarget->hasMMX()) break;
11460 return std::make_pair(0U, X86::VR64RegisterClass);
11461 case 'Y': // SSE_REGS if SSE2 allowed
11462 if (!Subtarget->hasSSE2()) break;
11464 case 'x': // SSE_REGS if SSE1 allowed
11465 if (!Subtarget->hasSSE1()) break;
11467 switch (VT.getSimpleVT().SimpleTy) {
11469 // Scalar SSE types.
11472 return std::make_pair(0U, X86::FR32RegisterClass);
11475 return std::make_pair(0U, X86::FR64RegisterClass);
11483 return std::make_pair(0U, X86::VR128RegisterClass);
11489 // Use the default implementation in TargetLowering to convert the register
11490 // constraint into a member of a register class.
11491 std::pair<unsigned, const TargetRegisterClass*> Res;
11492 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
11494 // Not found as a standard register?
11495 if (Res.second == 0) {
11496 // Map st(0) -> st(7) -> ST0
11497 if (Constraint.size() == 7 && Constraint[0] == '{' &&
11498 tolower(Constraint[1]) == 's' &&
11499 tolower(Constraint[2]) == 't' &&
11500 Constraint[3] == '(' &&
11501 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
11502 Constraint[5] == ')' &&
11503 Constraint[6] == '}') {
11505 Res.first = X86::ST0+Constraint[4]-'0';
11506 Res.second = X86::RFP80RegisterClass;
11510 // GCC allows "st(0)" to be called just plain "st".
11511 if (StringRef("{st}").equals_lower(Constraint)) {
11512 Res.first = X86::ST0;
11513 Res.second = X86::RFP80RegisterClass;
11518 if (StringRef("{flags}").equals_lower(Constraint)) {
11519 Res.first = X86::EFLAGS;
11520 Res.second = X86::CCRRegisterClass;
11524 // 'A' means EAX + EDX.
11525 if (Constraint == "A") {
11526 Res.first = X86::EAX;
11527 Res.second = X86::GR32_ADRegisterClass;
11533 // Otherwise, check to see if this is a register class of the wrong value
11534 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
11535 // turn into {ax},{dx}.
11536 if (Res.second->hasType(VT))
11537 return Res; // Correct type already, nothing to do.
11539 // All of the single-register GCC register classes map their values onto
11540 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
11541 // really want an 8-bit or 32-bit register, map to the appropriate register
11542 // class and return the appropriate register.
11543 if (Res.second == X86::GR16RegisterClass) {
11544 if (VT == MVT::i8) {
11545 unsigned DestReg = 0;
11546 switch (Res.first) {
11548 case X86::AX: DestReg = X86::AL; break;
11549 case X86::DX: DestReg = X86::DL; break;
11550 case X86::CX: DestReg = X86::CL; break;
11551 case X86::BX: DestReg = X86::BL; break;
11554 Res.first = DestReg;
11555 Res.second = X86::GR8RegisterClass;
11557 } else if (VT == MVT::i32) {
11558 unsigned DestReg = 0;
11559 switch (Res.first) {
11561 case X86::AX: DestReg = X86::EAX; break;
11562 case X86::DX: DestReg = X86::EDX; break;
11563 case X86::CX: DestReg = X86::ECX; break;
11564 case X86::BX: DestReg = X86::EBX; break;
11565 case X86::SI: DestReg = X86::ESI; break;
11566 case X86::DI: DestReg = X86::EDI; break;
11567 case X86::BP: DestReg = X86::EBP; break;
11568 case X86::SP: DestReg = X86::ESP; break;
11571 Res.first = DestReg;
11572 Res.second = X86::GR32RegisterClass;
11574 } else if (VT == MVT::i64) {
11575 unsigned DestReg = 0;
11576 switch (Res.first) {
11578 case X86::AX: DestReg = X86::RAX; break;
11579 case X86::DX: DestReg = X86::RDX; break;
11580 case X86::CX: DestReg = X86::RCX; break;
11581 case X86::BX: DestReg = X86::RBX; break;
11582 case X86::SI: DestReg = X86::RSI; break;
11583 case X86::DI: DestReg = X86::RDI; break;
11584 case X86::BP: DestReg = X86::RBP; break;
11585 case X86::SP: DestReg = X86::RSP; break;
11588 Res.first = DestReg;
11589 Res.second = X86::GR64RegisterClass;
11592 } else if (Res.second == X86::FR32RegisterClass ||
11593 Res.second == X86::FR64RegisterClass ||
11594 Res.second == X86::VR128RegisterClass) {
11595 // Handle references to XMM physical registers that got mapped into the
11596 // wrong class. This can happen with constraints like {xmm0} where the
11597 // target independent register mapper will just pick the first match it can
11598 // find, ignoring the required type.
11599 if (VT == MVT::f32)
11600 Res.second = X86::FR32RegisterClass;
11601 else if (VT == MVT::f64)
11602 Res.second = X86::FR64RegisterClass;
11603 else if (X86::VR128RegisterClass->hasType(VT))
11604 Res.second = X86::VR128RegisterClass;