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 FuncInfo->setRegSaveFrameIndex(
1705 MFI->CreateFixedObject(1, NumIntRegs * 8, false));
1706 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1708 // For X86-64, if there are vararg parameters that are passed via
1709 // registers, then we must store them to their spots on the stack so they
1710 // may be loaded by deferencing the result of va_next.
1711 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1712 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1713 FuncInfo->setRegSaveFrameIndex(
1714 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1718 // Store the integer parameter registers.
1719 SmallVector<SDValue, 8> MemOps;
1720 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1722 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1723 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1724 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1725 DAG.getIntPtrConstant(Offset));
1726 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1727 X86::GR64RegisterClass);
1728 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1730 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1731 MachinePointerInfo::getFixedStack(
1732 FuncInfo->getRegSaveFrameIndex(), Offset),
1734 MemOps.push_back(Store);
1738 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1739 // Now store the XMM (fp + vector) parameter registers.
1740 SmallVector<SDValue, 11> SaveXMMOps;
1741 SaveXMMOps.push_back(Chain);
1743 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1744 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1745 SaveXMMOps.push_back(ALVal);
1747 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1748 FuncInfo->getRegSaveFrameIndex()));
1749 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1750 FuncInfo->getVarArgsFPOffset()));
1752 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1753 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1754 X86::VR128RegisterClass);
1755 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1756 SaveXMMOps.push_back(Val);
1758 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1760 &SaveXMMOps[0], SaveXMMOps.size()));
1763 if (!MemOps.empty())
1764 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1765 &MemOps[0], MemOps.size());
1769 // Some CCs need callee pop.
1770 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1771 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1773 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1774 // If this is an sret function, the return should pop the hidden pointer.
1775 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1776 FuncInfo->setBytesToPopOnReturn(4);
1780 // RegSaveFrameIndex is X86-64 only.
1781 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1782 if (CallConv == CallingConv::X86_FastCall ||
1783 CallConv == CallingConv::X86_ThisCall)
1784 // fastcc functions can't have varargs.
1785 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1792 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1793 SDValue StackPtr, SDValue Arg,
1794 DebugLoc dl, SelectionDAG &DAG,
1795 const CCValAssign &VA,
1796 ISD::ArgFlagsTy Flags) const {
1797 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1798 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1799 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1800 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1801 if (Flags.isByVal())
1802 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1804 return DAG.getStore(Chain, dl, Arg, PtrOff,
1805 MachinePointerInfo::getStack(LocMemOffset),
1809 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1810 /// optimization is performed and it is required.
1812 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1813 SDValue &OutRetAddr, SDValue Chain,
1814 bool IsTailCall, bool Is64Bit,
1815 int FPDiff, DebugLoc dl) const {
1816 // Adjust the Return address stack slot.
1817 EVT VT = getPointerTy();
1818 OutRetAddr = getReturnAddressFrameIndex(DAG);
1820 // Load the "old" Return address.
1821 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1823 return SDValue(OutRetAddr.getNode(), 1);
1826 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1827 /// optimization is performed and it is required (FPDiff!=0).
1829 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1830 SDValue Chain, SDValue RetAddrFrIdx,
1831 bool Is64Bit, int FPDiff, DebugLoc dl) {
1832 // Store the return address to the appropriate stack slot.
1833 if (!FPDiff) return Chain;
1834 // Calculate the new stack slot for the return address.
1835 int SlotSize = Is64Bit ? 8 : 4;
1836 int NewReturnAddrFI =
1837 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1838 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1839 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1840 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1841 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1847 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1848 CallingConv::ID CallConv, bool isVarArg,
1850 const SmallVectorImpl<ISD::OutputArg> &Outs,
1851 const SmallVectorImpl<SDValue> &OutVals,
1852 const SmallVectorImpl<ISD::InputArg> &Ins,
1853 DebugLoc dl, SelectionDAG &DAG,
1854 SmallVectorImpl<SDValue> &InVals) const {
1855 MachineFunction &MF = DAG.getMachineFunction();
1856 bool Is64Bit = Subtarget->is64Bit();
1857 bool IsStructRet = CallIsStructReturn(Outs);
1858 bool IsSibcall = false;
1861 // Check if it's really possible to do a tail call.
1862 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1863 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1864 Outs, OutVals, Ins, DAG);
1866 // Sibcalls are automatically detected tailcalls which do not require
1868 if (!GuaranteedTailCallOpt && isTailCall)
1875 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1876 "Var args not supported with calling convention fastcc or ghc");
1878 // Analyze operands of the call, assigning locations to each operand.
1879 SmallVector<CCValAssign, 16> ArgLocs;
1880 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1881 ArgLocs, *DAG.getContext());
1882 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1884 // Get a count of how many bytes are to be pushed on the stack.
1885 unsigned NumBytes = CCInfo.getNextStackOffset();
1887 // This is a sibcall. The memory operands are available in caller's
1888 // own caller's stack.
1890 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1891 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1894 if (isTailCall && !IsSibcall) {
1895 // Lower arguments at fp - stackoffset + fpdiff.
1896 unsigned NumBytesCallerPushed =
1897 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1898 FPDiff = NumBytesCallerPushed - NumBytes;
1900 // Set the delta of movement of the returnaddr stackslot.
1901 // But only set if delta is greater than previous delta.
1902 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1903 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1907 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1909 SDValue RetAddrFrIdx;
1910 // Load return adress for tail calls.
1911 if (isTailCall && FPDiff)
1912 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1913 Is64Bit, FPDiff, dl);
1915 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1916 SmallVector<SDValue, 8> MemOpChains;
1919 // Walk the register/memloc assignments, inserting copies/loads. In the case
1920 // of tail call optimization arguments are handle later.
1921 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1922 CCValAssign &VA = ArgLocs[i];
1923 EVT RegVT = VA.getLocVT();
1924 SDValue Arg = OutVals[i];
1925 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1926 bool isByVal = Flags.isByVal();
1928 // Promote the value if needed.
1929 switch (VA.getLocInfo()) {
1930 default: llvm_unreachable("Unknown loc info!");
1931 case CCValAssign::Full: break;
1932 case CCValAssign::SExt:
1933 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1935 case CCValAssign::ZExt:
1936 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1938 case CCValAssign::AExt:
1939 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1940 // Special case: passing MMX values in XMM registers.
1941 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1942 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1943 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1945 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1947 case CCValAssign::BCvt:
1948 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1950 case CCValAssign::Indirect: {
1951 // Store the argument.
1952 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1953 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1954 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1955 MachinePointerInfo::getFixedStack(FI),
1962 if (VA.isRegLoc()) {
1963 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1964 if (isVarArg && Subtarget->isTargetWin64()) {
1965 // Win64 ABI requires argument XMM reg to be copied to the corresponding
1966 // shadow reg if callee is a varargs function.
1967 unsigned ShadowReg = 0;
1968 switch (VA.getLocReg()) {
1969 case X86::XMM0: ShadowReg = X86::RCX; break;
1970 case X86::XMM1: ShadowReg = X86::RDX; break;
1971 case X86::XMM2: ShadowReg = X86::R8; break;
1972 case X86::XMM3: ShadowReg = X86::R9; break;
1975 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1977 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1978 assert(VA.isMemLoc());
1979 if (StackPtr.getNode() == 0)
1980 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1981 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1982 dl, DAG, VA, Flags));
1986 if (!MemOpChains.empty())
1987 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1988 &MemOpChains[0], MemOpChains.size());
1990 // Build a sequence of copy-to-reg nodes chained together with token chain
1991 // and flag operands which copy the outgoing args into registers.
1993 // Tail call byval lowering might overwrite argument registers so in case of
1994 // tail call optimization the copies to registers are lowered later.
1996 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1997 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1998 RegsToPass[i].second, InFlag);
1999 InFlag = Chain.getValue(1);
2002 if (Subtarget->isPICStyleGOT()) {
2003 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2006 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2007 DAG.getNode(X86ISD::GlobalBaseReg,
2008 DebugLoc(), getPointerTy()),
2010 InFlag = Chain.getValue(1);
2012 // If we are tail calling and generating PIC/GOT style code load the
2013 // address of the callee into ECX. The value in ecx is used as target of
2014 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2015 // for tail calls on PIC/GOT architectures. Normally we would just put the
2016 // address of GOT into ebx and then call target@PLT. But for tail calls
2017 // ebx would be restored (since ebx is callee saved) before jumping to the
2020 // Note: The actual moving to ECX is done further down.
2021 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2022 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2023 !G->getGlobal()->hasProtectedVisibility())
2024 Callee = LowerGlobalAddress(Callee, DAG);
2025 else if (isa<ExternalSymbolSDNode>(Callee))
2026 Callee = LowerExternalSymbol(Callee, DAG);
2030 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2031 // From AMD64 ABI document:
2032 // For calls that may call functions that use varargs or stdargs
2033 // (prototype-less calls or calls to functions containing ellipsis (...) in
2034 // the declaration) %al is used as hidden argument to specify the number
2035 // of SSE registers used. The contents of %al do not need to match exactly
2036 // the number of registers, but must be an ubound on the number of SSE
2037 // registers used and is in the range 0 - 8 inclusive.
2039 // Count the number of XMM registers allocated.
2040 static const unsigned XMMArgRegs[] = {
2041 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2042 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2044 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2045 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2046 && "SSE registers cannot be used when SSE is disabled");
2048 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2049 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2050 InFlag = Chain.getValue(1);
2054 // For tail calls lower the arguments to the 'real' stack slot.
2056 // Force all the incoming stack arguments to be loaded from the stack
2057 // before any new outgoing arguments are stored to the stack, because the
2058 // outgoing stack slots may alias the incoming argument stack slots, and
2059 // the alias isn't otherwise explicit. This is slightly more conservative
2060 // than necessary, because it means that each store effectively depends
2061 // on every argument instead of just those arguments it would clobber.
2062 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2064 SmallVector<SDValue, 8> MemOpChains2;
2067 // Do not flag preceeding copytoreg stuff together with the following stuff.
2069 if (GuaranteedTailCallOpt) {
2070 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2071 CCValAssign &VA = ArgLocs[i];
2074 assert(VA.isMemLoc());
2075 SDValue Arg = OutVals[i];
2076 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2077 // Create frame index.
2078 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2079 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2080 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2081 FIN = DAG.getFrameIndex(FI, getPointerTy());
2083 if (Flags.isByVal()) {
2084 // Copy relative to framepointer.
2085 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2086 if (StackPtr.getNode() == 0)
2087 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2089 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2091 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2095 // Store relative to framepointer.
2096 MemOpChains2.push_back(
2097 DAG.getStore(ArgChain, dl, Arg, FIN,
2098 MachinePointerInfo::getFixedStack(FI),
2104 if (!MemOpChains2.empty())
2105 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2106 &MemOpChains2[0], MemOpChains2.size());
2108 // Copy arguments to their registers.
2109 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2110 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2111 RegsToPass[i].second, InFlag);
2112 InFlag = Chain.getValue(1);
2116 // Store the return address to the appropriate stack slot.
2117 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2121 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2122 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2123 // In the 64-bit large code model, we have to make all calls
2124 // through a register, since the call instruction's 32-bit
2125 // pc-relative offset may not be large enough to hold the whole
2127 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2128 // If the callee is a GlobalAddress node (quite common, every direct call
2129 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2132 // We should use extra load for direct calls to dllimported functions in
2134 const GlobalValue *GV = G->getGlobal();
2135 if (!GV->hasDLLImportLinkage()) {
2136 unsigned char OpFlags = 0;
2138 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2139 // external symbols most go through the PLT in PIC mode. If the symbol
2140 // has hidden or protected visibility, or if it is static or local, then
2141 // we don't need to use the PLT - we can directly call it.
2142 if (Subtarget->isTargetELF() &&
2143 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2144 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2145 OpFlags = X86II::MO_PLT;
2146 } else if (Subtarget->isPICStyleStubAny() &&
2147 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2148 Subtarget->getDarwinVers() < 9) {
2149 // PC-relative references to external symbols should go through $stub,
2150 // unless we're building with the leopard linker or later, which
2151 // automatically synthesizes these stubs.
2152 OpFlags = X86II::MO_DARWIN_STUB;
2155 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2156 G->getOffset(), OpFlags);
2158 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2159 unsigned char OpFlags = 0;
2161 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2162 // symbols should go through the PLT.
2163 if (Subtarget->isTargetELF() &&
2164 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2165 OpFlags = X86II::MO_PLT;
2166 } else if (Subtarget->isPICStyleStubAny() &&
2167 Subtarget->getDarwinVers() < 9) {
2168 // PC-relative references to external symbols should go through $stub,
2169 // unless we're building with the leopard linker or later, which
2170 // automatically synthesizes these stubs.
2171 OpFlags = X86II::MO_DARWIN_STUB;
2174 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2178 // Returns a chain & a flag for retval copy to use.
2179 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2180 SmallVector<SDValue, 8> Ops;
2182 if (!IsSibcall && isTailCall) {
2183 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2184 DAG.getIntPtrConstant(0, true), InFlag);
2185 InFlag = Chain.getValue(1);
2188 Ops.push_back(Chain);
2189 Ops.push_back(Callee);
2192 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2194 // Add argument registers to the end of the list so that they are known live
2196 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2197 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2198 RegsToPass[i].second.getValueType()));
2200 // Add an implicit use GOT pointer in EBX.
2201 if (!isTailCall && Subtarget->isPICStyleGOT())
2202 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2204 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2205 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2206 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2208 if (InFlag.getNode())
2209 Ops.push_back(InFlag);
2213 //// If this is the first return lowered for this function, add the regs
2214 //// to the liveout set for the function.
2215 // This isn't right, although it's probably harmless on x86; liveouts
2216 // should be computed from returns not tail calls. Consider a void
2217 // function making a tail call to a function returning int.
2218 return DAG.getNode(X86ISD::TC_RETURN, dl,
2219 NodeTys, &Ops[0], Ops.size());
2222 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2223 InFlag = Chain.getValue(1);
2225 // Create the CALLSEQ_END node.
2226 unsigned NumBytesForCalleeToPush;
2227 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2228 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2229 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2230 // If this is a call to a struct-return function, the callee
2231 // pops the hidden struct pointer, so we have to push it back.
2232 // This is common for Darwin/X86, Linux & Mingw32 targets.
2233 NumBytesForCalleeToPush = 4;
2235 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2237 // Returns a flag for retval copy to use.
2239 Chain = DAG.getCALLSEQ_END(Chain,
2240 DAG.getIntPtrConstant(NumBytes, true),
2241 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2244 InFlag = Chain.getValue(1);
2247 // Handle result values, copying them out of physregs into vregs that we
2249 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2250 Ins, dl, DAG, InVals);
2254 //===----------------------------------------------------------------------===//
2255 // Fast Calling Convention (tail call) implementation
2256 //===----------------------------------------------------------------------===//
2258 // Like std call, callee cleans arguments, convention except that ECX is
2259 // reserved for storing the tail called function address. Only 2 registers are
2260 // free for argument passing (inreg). Tail call optimization is performed
2262 // * tailcallopt is enabled
2263 // * caller/callee are fastcc
2264 // On X86_64 architecture with GOT-style position independent code only local
2265 // (within module) calls are supported at the moment.
2266 // To keep the stack aligned according to platform abi the function
2267 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2268 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2269 // If a tail called function callee has more arguments than the caller the
2270 // caller needs to make sure that there is room to move the RETADDR to. This is
2271 // achieved by reserving an area the size of the argument delta right after the
2272 // original REtADDR, but before the saved framepointer or the spilled registers
2273 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2285 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2286 /// for a 16 byte align requirement.
2288 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2289 SelectionDAG& DAG) const {
2290 MachineFunction &MF = DAG.getMachineFunction();
2291 const TargetMachine &TM = MF.getTarget();
2292 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2293 unsigned StackAlignment = TFI.getStackAlignment();
2294 uint64_t AlignMask = StackAlignment - 1;
2295 int64_t Offset = StackSize;
2296 uint64_t SlotSize = TD->getPointerSize();
2297 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2298 // Number smaller than 12 so just add the difference.
2299 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2301 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2302 Offset = ((~AlignMask) & Offset) + StackAlignment +
2303 (StackAlignment-SlotSize);
2308 /// MatchingStackOffset - Return true if the given stack call argument is
2309 /// already available in the same position (relatively) of the caller's
2310 /// incoming argument stack.
2312 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2313 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2314 const X86InstrInfo *TII) {
2315 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2317 if (Arg.getOpcode() == ISD::CopyFromReg) {
2318 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2319 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2321 MachineInstr *Def = MRI->getVRegDef(VR);
2324 if (!Flags.isByVal()) {
2325 if (!TII->isLoadFromStackSlot(Def, FI))
2328 unsigned Opcode = Def->getOpcode();
2329 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2330 Def->getOperand(1).isFI()) {
2331 FI = Def->getOperand(1).getIndex();
2332 Bytes = Flags.getByValSize();
2336 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2337 if (Flags.isByVal())
2338 // ByVal argument is passed in as a pointer but it's now being
2339 // dereferenced. e.g.
2340 // define @foo(%struct.X* %A) {
2341 // tail call @bar(%struct.X* byval %A)
2344 SDValue Ptr = Ld->getBasePtr();
2345 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2348 FI = FINode->getIndex();
2352 assert(FI != INT_MAX);
2353 if (!MFI->isFixedObjectIndex(FI))
2355 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2358 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2359 /// for tail call optimization. Targets which want to do tail call
2360 /// optimization should implement this function.
2362 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2363 CallingConv::ID CalleeCC,
2365 bool isCalleeStructRet,
2366 bool isCallerStructRet,
2367 const SmallVectorImpl<ISD::OutputArg> &Outs,
2368 const SmallVectorImpl<SDValue> &OutVals,
2369 const SmallVectorImpl<ISD::InputArg> &Ins,
2370 SelectionDAG& DAG) const {
2371 if (!IsTailCallConvention(CalleeCC) &&
2372 CalleeCC != CallingConv::C)
2375 // If -tailcallopt is specified, make fastcc functions tail-callable.
2376 const MachineFunction &MF = DAG.getMachineFunction();
2377 const Function *CallerF = DAG.getMachineFunction().getFunction();
2378 CallingConv::ID CallerCC = CallerF->getCallingConv();
2379 bool CCMatch = CallerCC == CalleeCC;
2381 if (GuaranteedTailCallOpt) {
2382 if (IsTailCallConvention(CalleeCC) && CCMatch)
2387 // Look for obvious safe cases to perform tail call optimization that do not
2388 // require ABI changes. This is what gcc calls sibcall.
2390 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2391 // emit a special epilogue.
2392 if (RegInfo->needsStackRealignment(MF))
2395 // Do not sibcall optimize vararg calls unless the call site is not passing
2397 if (isVarArg && !Outs.empty())
2400 // Also avoid sibcall optimization if either caller or callee uses struct
2401 // return semantics.
2402 if (isCalleeStructRet || isCallerStructRet)
2405 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2406 // Therefore if it's not used by the call it is not safe to optimize this into
2408 bool Unused = false;
2409 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2416 SmallVector<CCValAssign, 16> RVLocs;
2417 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2418 RVLocs, *DAG.getContext());
2419 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2420 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2421 CCValAssign &VA = RVLocs[i];
2422 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2427 // If the calling conventions do not match, then we'd better make sure the
2428 // results are returned in the same way as what the caller expects.
2430 SmallVector<CCValAssign, 16> RVLocs1;
2431 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2432 RVLocs1, *DAG.getContext());
2433 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2435 SmallVector<CCValAssign, 16> RVLocs2;
2436 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2437 RVLocs2, *DAG.getContext());
2438 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2440 if (RVLocs1.size() != RVLocs2.size())
2442 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2443 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2445 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2447 if (RVLocs1[i].isRegLoc()) {
2448 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2451 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2457 // If the callee takes no arguments then go on to check the results of the
2459 if (!Outs.empty()) {
2460 // Check if stack adjustment is needed. For now, do not do this if any
2461 // argument is passed on the stack.
2462 SmallVector<CCValAssign, 16> ArgLocs;
2463 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2464 ArgLocs, *DAG.getContext());
2465 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2466 if (CCInfo.getNextStackOffset()) {
2467 MachineFunction &MF = DAG.getMachineFunction();
2468 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2470 if (Subtarget->isTargetWin64())
2471 // Win64 ABI has additional complications.
2474 // Check if the arguments are already laid out in the right way as
2475 // the caller's fixed stack objects.
2476 MachineFrameInfo *MFI = MF.getFrameInfo();
2477 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2478 const X86InstrInfo *TII =
2479 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2480 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2481 CCValAssign &VA = ArgLocs[i];
2482 SDValue Arg = OutVals[i];
2483 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2484 if (VA.getLocInfo() == CCValAssign::Indirect)
2486 if (!VA.isRegLoc()) {
2487 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2494 // If the tailcall address may be in a register, then make sure it's
2495 // possible to register allocate for it. In 32-bit, the call address can
2496 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2497 // callee-saved registers are restored. These happen to be the same
2498 // registers used to pass 'inreg' arguments so watch out for those.
2499 if (!Subtarget->is64Bit() &&
2500 !isa<GlobalAddressSDNode>(Callee) &&
2501 !isa<ExternalSymbolSDNode>(Callee)) {
2502 unsigned NumInRegs = 0;
2503 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2504 CCValAssign &VA = ArgLocs[i];
2507 unsigned Reg = VA.getLocReg();
2510 case X86::EAX: case X86::EDX: case X86::ECX:
2511 if (++NumInRegs == 3)
2523 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2524 return X86::createFastISel(funcInfo);
2528 //===----------------------------------------------------------------------===//
2529 // Other Lowering Hooks
2530 //===----------------------------------------------------------------------===//
2532 static bool MayFoldLoad(SDValue Op) {
2533 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2536 static bool MayFoldIntoStore(SDValue Op) {
2537 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2540 static bool isTargetShuffle(unsigned Opcode) {
2542 default: return false;
2543 case X86ISD::PSHUFD:
2544 case X86ISD::PSHUFHW:
2545 case X86ISD::PSHUFLW:
2546 case X86ISD::SHUFPD:
2547 case X86ISD::PALIGN:
2548 case X86ISD::SHUFPS:
2549 case X86ISD::MOVLHPS:
2550 case X86ISD::MOVLHPD:
2551 case X86ISD::MOVHLPS:
2552 case X86ISD::MOVLPS:
2553 case X86ISD::MOVLPD:
2554 case X86ISD::MOVSHDUP:
2555 case X86ISD::MOVSLDUP:
2556 case X86ISD::MOVDDUP:
2559 case X86ISD::UNPCKLPS:
2560 case X86ISD::UNPCKLPD:
2561 case X86ISD::PUNPCKLWD:
2562 case X86ISD::PUNPCKLBW:
2563 case X86ISD::PUNPCKLDQ:
2564 case X86ISD::PUNPCKLQDQ:
2565 case X86ISD::UNPCKHPS:
2566 case X86ISD::UNPCKHPD:
2567 case X86ISD::PUNPCKHWD:
2568 case X86ISD::PUNPCKHBW:
2569 case X86ISD::PUNPCKHDQ:
2570 case X86ISD::PUNPCKHQDQ:
2576 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2577 SDValue V1, SelectionDAG &DAG) {
2579 default: llvm_unreachable("Unknown x86 shuffle node");
2580 case X86ISD::MOVSHDUP:
2581 case X86ISD::MOVSLDUP:
2582 case X86ISD::MOVDDUP:
2583 return DAG.getNode(Opc, dl, VT, V1);
2589 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2590 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2592 default: llvm_unreachable("Unknown x86 shuffle node");
2593 case X86ISD::PSHUFD:
2594 case X86ISD::PSHUFHW:
2595 case X86ISD::PSHUFLW:
2596 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2602 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2603 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2605 default: llvm_unreachable("Unknown x86 shuffle node");
2606 case X86ISD::PALIGN:
2607 case X86ISD::SHUFPD:
2608 case X86ISD::SHUFPS:
2609 return DAG.getNode(Opc, dl, VT, V1, V2,
2610 DAG.getConstant(TargetMask, MVT::i8));
2615 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2616 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2618 default: llvm_unreachable("Unknown x86 shuffle node");
2619 case X86ISD::MOVLHPS:
2620 case X86ISD::MOVLHPD:
2621 case X86ISD::MOVHLPS:
2622 case X86ISD::MOVLPS:
2623 case X86ISD::MOVLPD:
2626 case X86ISD::UNPCKLPS:
2627 case X86ISD::UNPCKLPD:
2628 case X86ISD::PUNPCKLWD:
2629 case X86ISD::PUNPCKLBW:
2630 case X86ISD::PUNPCKLDQ:
2631 case X86ISD::PUNPCKLQDQ:
2632 case X86ISD::UNPCKHPS:
2633 case X86ISD::UNPCKHPD:
2634 case X86ISD::PUNPCKHWD:
2635 case X86ISD::PUNPCKHBW:
2636 case X86ISD::PUNPCKHDQ:
2637 case X86ISD::PUNPCKHQDQ:
2638 return DAG.getNode(Opc, dl, VT, V1, V2);
2643 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2644 MachineFunction &MF = DAG.getMachineFunction();
2645 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2646 int ReturnAddrIndex = FuncInfo->getRAIndex();
2648 if (ReturnAddrIndex == 0) {
2649 // Set up a frame object for the return address.
2650 uint64_t SlotSize = TD->getPointerSize();
2651 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2653 FuncInfo->setRAIndex(ReturnAddrIndex);
2656 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2660 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2661 bool hasSymbolicDisplacement) {
2662 // Offset should fit into 32 bit immediate field.
2663 if (!isInt<32>(Offset))
2666 // If we don't have a symbolic displacement - we don't have any extra
2668 if (!hasSymbolicDisplacement)
2671 // FIXME: Some tweaks might be needed for medium code model.
2672 if (M != CodeModel::Small && M != CodeModel::Kernel)
2675 // For small code model we assume that latest object is 16MB before end of 31
2676 // bits boundary. We may also accept pretty large negative constants knowing
2677 // that all objects are in the positive half of address space.
2678 if (M == CodeModel::Small && Offset < 16*1024*1024)
2681 // For kernel code model we know that all object resist in the negative half
2682 // of 32bits address space. We may not accept negative offsets, since they may
2683 // be just off and we may accept pretty large positive ones.
2684 if (M == CodeModel::Kernel && Offset > 0)
2690 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2691 /// specific condition code, returning the condition code and the LHS/RHS of the
2692 /// comparison to make.
2693 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2694 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2696 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2697 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2698 // X > -1 -> X == 0, jump !sign.
2699 RHS = DAG.getConstant(0, RHS.getValueType());
2700 return X86::COND_NS;
2701 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2702 // X < 0 -> X == 0, jump on sign.
2704 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2706 RHS = DAG.getConstant(0, RHS.getValueType());
2707 return X86::COND_LE;
2711 switch (SetCCOpcode) {
2712 default: llvm_unreachable("Invalid integer condition!");
2713 case ISD::SETEQ: return X86::COND_E;
2714 case ISD::SETGT: return X86::COND_G;
2715 case ISD::SETGE: return X86::COND_GE;
2716 case ISD::SETLT: return X86::COND_L;
2717 case ISD::SETLE: return X86::COND_LE;
2718 case ISD::SETNE: return X86::COND_NE;
2719 case ISD::SETULT: return X86::COND_B;
2720 case ISD::SETUGT: return X86::COND_A;
2721 case ISD::SETULE: return X86::COND_BE;
2722 case ISD::SETUGE: return X86::COND_AE;
2726 // First determine if it is required or is profitable to flip the operands.
2728 // If LHS is a foldable load, but RHS is not, flip the condition.
2729 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2730 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2731 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2732 std::swap(LHS, RHS);
2735 switch (SetCCOpcode) {
2741 std::swap(LHS, RHS);
2745 // On a floating point condition, the flags are set as follows:
2747 // 0 | 0 | 0 | X > Y
2748 // 0 | 0 | 1 | X < Y
2749 // 1 | 0 | 0 | X == Y
2750 // 1 | 1 | 1 | unordered
2751 switch (SetCCOpcode) {
2752 default: llvm_unreachable("Condcode should be pre-legalized away");
2754 case ISD::SETEQ: return X86::COND_E;
2755 case ISD::SETOLT: // flipped
2757 case ISD::SETGT: return X86::COND_A;
2758 case ISD::SETOLE: // flipped
2760 case ISD::SETGE: return X86::COND_AE;
2761 case ISD::SETUGT: // flipped
2763 case ISD::SETLT: return X86::COND_B;
2764 case ISD::SETUGE: // flipped
2766 case ISD::SETLE: return X86::COND_BE;
2768 case ISD::SETNE: return X86::COND_NE;
2769 case ISD::SETUO: return X86::COND_P;
2770 case ISD::SETO: return X86::COND_NP;
2772 case ISD::SETUNE: return X86::COND_INVALID;
2776 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2777 /// code. Current x86 isa includes the following FP cmov instructions:
2778 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2779 static bool hasFPCMov(unsigned X86CC) {
2795 /// isFPImmLegal - Returns true if the target can instruction select the
2796 /// specified FP immediate natively. If false, the legalizer will
2797 /// materialize the FP immediate as a load from a constant pool.
2798 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2799 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2800 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2806 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2807 /// the specified range (L, H].
2808 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2809 return (Val < 0) || (Val >= Low && Val < Hi);
2812 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2813 /// specified value.
2814 static bool isUndefOrEqual(int Val, int CmpVal) {
2815 if (Val < 0 || Val == CmpVal)
2820 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2821 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2822 /// the second operand.
2823 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2824 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2825 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2826 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2827 return (Mask[0] < 2 && Mask[1] < 2);
2831 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2832 SmallVector<int, 8> M;
2834 return ::isPSHUFDMask(M, N->getValueType(0));
2837 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2838 /// is suitable for input to PSHUFHW.
2839 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2840 if (VT != MVT::v8i16)
2843 // Lower quadword copied in order or undef.
2844 for (int i = 0; i != 4; ++i)
2845 if (Mask[i] >= 0 && Mask[i] != i)
2848 // Upper quadword shuffled.
2849 for (int i = 4; i != 8; ++i)
2850 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2856 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2857 SmallVector<int, 8> M;
2859 return ::isPSHUFHWMask(M, N->getValueType(0));
2862 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2863 /// is suitable for input to PSHUFLW.
2864 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2865 if (VT != MVT::v8i16)
2868 // Upper quadword copied in order.
2869 for (int i = 4; i != 8; ++i)
2870 if (Mask[i] >= 0 && Mask[i] != i)
2873 // Lower quadword shuffled.
2874 for (int i = 0; i != 4; ++i)
2881 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2882 SmallVector<int, 8> M;
2884 return ::isPSHUFLWMask(M, N->getValueType(0));
2887 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2888 /// is suitable for input to PALIGNR.
2889 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2891 int i, e = VT.getVectorNumElements();
2893 // Do not handle v2i64 / v2f64 shuffles with palignr.
2894 if (e < 4 || !hasSSSE3)
2897 for (i = 0; i != e; ++i)
2901 // All undef, not a palignr.
2905 // Determine if it's ok to perform a palignr with only the LHS, since we
2906 // don't have access to the actual shuffle elements to see if RHS is undef.
2907 bool Unary = Mask[i] < (int)e;
2908 bool NeedsUnary = false;
2910 int s = Mask[i] - i;
2912 // Check the rest of the elements to see if they are consecutive.
2913 for (++i; i != e; ++i) {
2918 Unary = Unary && (m < (int)e);
2919 NeedsUnary = NeedsUnary || (m < s);
2921 if (NeedsUnary && !Unary)
2923 if (Unary && m != ((s+i) & (e-1)))
2925 if (!Unary && m != (s+i))
2931 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2932 SmallVector<int, 8> M;
2934 return ::isPALIGNRMask(M, N->getValueType(0), true);
2937 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2938 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2939 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2940 int NumElems = VT.getVectorNumElements();
2941 if (NumElems != 2 && NumElems != 4)
2944 int Half = NumElems / 2;
2945 for (int i = 0; i < Half; ++i)
2946 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2948 for (int i = Half; i < NumElems; ++i)
2949 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2955 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2956 SmallVector<int, 8> M;
2958 return ::isSHUFPMask(M, N->getValueType(0));
2961 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2962 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2963 /// half elements to come from vector 1 (which would equal the dest.) and
2964 /// the upper half to come from vector 2.
2965 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2966 int NumElems = VT.getVectorNumElements();
2968 if (NumElems != 2 && NumElems != 4)
2971 int Half = NumElems / 2;
2972 for (int i = 0; i < Half; ++i)
2973 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2975 for (int i = Half; i < NumElems; ++i)
2976 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2981 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2982 SmallVector<int, 8> M;
2984 return isCommutedSHUFPMask(M, N->getValueType(0));
2987 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2988 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2989 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2990 if (N->getValueType(0).getVectorNumElements() != 4)
2993 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2994 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2995 isUndefOrEqual(N->getMaskElt(1), 7) &&
2996 isUndefOrEqual(N->getMaskElt(2), 2) &&
2997 isUndefOrEqual(N->getMaskElt(3), 3);
3000 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3001 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3003 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3004 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3009 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3010 isUndefOrEqual(N->getMaskElt(1), 3) &&
3011 isUndefOrEqual(N->getMaskElt(2), 2) &&
3012 isUndefOrEqual(N->getMaskElt(3), 3);
3015 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3016 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3017 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3018 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3020 if (NumElems != 2 && NumElems != 4)
3023 for (unsigned i = 0; i < NumElems/2; ++i)
3024 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3027 for (unsigned i = NumElems/2; i < NumElems; ++i)
3028 if (!isUndefOrEqual(N->getMaskElt(i), i))
3034 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3035 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3036 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3037 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3039 if (NumElems != 2 && NumElems != 4)
3042 for (unsigned i = 0; i < NumElems/2; ++i)
3043 if (!isUndefOrEqual(N->getMaskElt(i), i))
3046 for (unsigned i = 0; i < NumElems/2; ++i)
3047 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3053 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3054 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3055 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3056 bool V2IsSplat = false) {
3057 int NumElts = VT.getVectorNumElements();
3058 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3061 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3063 int BitI1 = Mask[i+1];
3064 if (!isUndefOrEqual(BitI, j))
3067 if (!isUndefOrEqual(BitI1, NumElts))
3070 if (!isUndefOrEqual(BitI1, j + NumElts))
3077 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3078 SmallVector<int, 8> M;
3080 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3083 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3084 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3085 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3086 bool V2IsSplat = false) {
3087 int NumElts = VT.getVectorNumElements();
3088 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3091 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3093 int BitI1 = Mask[i+1];
3094 if (!isUndefOrEqual(BitI, j + NumElts/2))
3097 if (isUndefOrEqual(BitI1, NumElts))
3100 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3107 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3108 SmallVector<int, 8> M;
3110 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3113 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3114 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3116 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3117 int NumElems = VT.getVectorNumElements();
3118 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3121 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3123 int BitI1 = Mask[i+1];
3124 if (!isUndefOrEqual(BitI, j))
3126 if (!isUndefOrEqual(BitI1, j))
3132 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3133 SmallVector<int, 8> M;
3135 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3138 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3139 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3141 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3142 int NumElems = VT.getVectorNumElements();
3143 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3146 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3148 int BitI1 = Mask[i+1];
3149 if (!isUndefOrEqual(BitI, j))
3151 if (!isUndefOrEqual(BitI1, j))
3157 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3158 SmallVector<int, 8> M;
3160 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3163 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3164 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3165 /// MOVSD, and MOVD, i.e. setting the lowest element.
3166 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3167 if (VT.getVectorElementType().getSizeInBits() < 32)
3170 int NumElts = VT.getVectorNumElements();
3172 if (!isUndefOrEqual(Mask[0], NumElts))
3175 for (int i = 1; i < NumElts; ++i)
3176 if (!isUndefOrEqual(Mask[i], i))
3182 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3183 SmallVector<int, 8> M;
3185 return ::isMOVLMask(M, N->getValueType(0));
3188 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3189 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3190 /// element of vector 2 and the other elements to come from vector 1 in order.
3191 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3192 bool V2IsSplat = false, bool V2IsUndef = false) {
3193 int NumOps = VT.getVectorNumElements();
3194 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3197 if (!isUndefOrEqual(Mask[0], 0))
3200 for (int i = 1; i < NumOps; ++i)
3201 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3202 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3203 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3209 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3210 bool V2IsUndef = false) {
3211 SmallVector<int, 8> M;
3213 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3216 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3217 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3218 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3219 if (N->getValueType(0).getVectorNumElements() != 4)
3222 // Expect 1, 1, 3, 3
3223 for (unsigned i = 0; i < 2; ++i) {
3224 int Elt = N->getMaskElt(i);
3225 if (Elt >= 0 && Elt != 1)
3230 for (unsigned i = 2; i < 4; ++i) {
3231 int Elt = N->getMaskElt(i);
3232 if (Elt >= 0 && Elt != 3)
3237 // Don't use movshdup if it can be done with a shufps.
3238 // FIXME: verify that matching u, u, 3, 3 is what we want.
3242 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3243 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3244 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3245 if (N->getValueType(0).getVectorNumElements() != 4)
3248 // Expect 0, 0, 2, 2
3249 for (unsigned i = 0; i < 2; ++i)
3250 if (N->getMaskElt(i) > 0)
3254 for (unsigned i = 2; i < 4; ++i) {
3255 int Elt = N->getMaskElt(i);
3256 if (Elt >= 0 && Elt != 2)
3261 // Don't use movsldup if it can be done with a shufps.
3265 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3266 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3267 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3268 int e = N->getValueType(0).getVectorNumElements() / 2;
3270 for (int i = 0; i < e; ++i)
3271 if (!isUndefOrEqual(N->getMaskElt(i), i))
3273 for (int i = 0; i < e; ++i)
3274 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3279 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3280 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3281 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3282 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3283 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3285 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3287 for (int i = 0; i < NumOperands; ++i) {
3288 int Val = SVOp->getMaskElt(NumOperands-i-1);
3289 if (Val < 0) Val = 0;
3290 if (Val >= NumOperands) Val -= NumOperands;
3292 if (i != NumOperands - 1)
3298 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3299 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3300 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3301 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3303 // 8 nodes, but we only care about the last 4.
3304 for (unsigned i = 7; i >= 4; --i) {
3305 int Val = SVOp->getMaskElt(i);
3314 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3315 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3316 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3317 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3319 // 8 nodes, but we only care about the first 4.
3320 for (int i = 3; i >= 0; --i) {
3321 int Val = SVOp->getMaskElt(i);
3330 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3331 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3332 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3333 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3334 EVT VVT = N->getValueType(0);
3335 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3339 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3340 Val = SVOp->getMaskElt(i);
3344 return (Val - i) * EltSize;
3347 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3349 bool X86::isZeroNode(SDValue Elt) {
3350 return ((isa<ConstantSDNode>(Elt) &&
3351 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3352 (isa<ConstantFPSDNode>(Elt) &&
3353 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3356 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3357 /// their permute mask.
3358 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3359 SelectionDAG &DAG) {
3360 EVT VT = SVOp->getValueType(0);
3361 unsigned NumElems = VT.getVectorNumElements();
3362 SmallVector<int, 8> MaskVec;
3364 for (unsigned i = 0; i != NumElems; ++i) {
3365 int idx = SVOp->getMaskElt(i);
3367 MaskVec.push_back(idx);
3368 else if (idx < (int)NumElems)
3369 MaskVec.push_back(idx + NumElems);
3371 MaskVec.push_back(idx - NumElems);
3373 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3374 SVOp->getOperand(0), &MaskVec[0]);
3377 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3378 /// the two vector operands have swapped position.
3379 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3380 unsigned NumElems = VT.getVectorNumElements();
3381 for (unsigned i = 0; i != NumElems; ++i) {
3385 else if (idx < (int)NumElems)
3386 Mask[i] = idx + NumElems;
3388 Mask[i] = idx - NumElems;
3392 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3393 /// match movhlps. The lower half elements should come from upper half of
3394 /// V1 (and in order), and the upper half elements should come from the upper
3395 /// half of V2 (and in order).
3396 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3397 if (Op->getValueType(0).getVectorNumElements() != 4)
3399 for (unsigned i = 0, e = 2; i != e; ++i)
3400 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3402 for (unsigned i = 2; i != 4; ++i)
3403 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3408 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3409 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3411 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3412 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3414 N = N->getOperand(0).getNode();
3415 if (!ISD::isNON_EXTLoad(N))
3418 *LD = cast<LoadSDNode>(N);
3422 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3423 /// match movlp{s|d}. The lower half elements should come from lower half of
3424 /// V1 (and in order), and the upper half elements should come from the upper
3425 /// half of V2 (and in order). And since V1 will become the source of the
3426 /// MOVLP, it must be either a vector load or a scalar load to vector.
3427 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3428 ShuffleVectorSDNode *Op) {
3429 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3431 // Is V2 is a vector load, don't do this transformation. We will try to use
3432 // load folding shufps op.
3433 if (ISD::isNON_EXTLoad(V2))
3436 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3438 if (NumElems != 2 && NumElems != 4)
3440 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3441 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3443 for (unsigned i = NumElems/2; i != NumElems; ++i)
3444 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3449 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3451 static bool isSplatVector(SDNode *N) {
3452 if (N->getOpcode() != ISD::BUILD_VECTOR)
3455 SDValue SplatValue = N->getOperand(0);
3456 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3457 if (N->getOperand(i) != SplatValue)
3462 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3463 /// to an zero vector.
3464 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3465 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3466 SDValue V1 = N->getOperand(0);
3467 SDValue V2 = N->getOperand(1);
3468 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3469 for (unsigned i = 0; i != NumElems; ++i) {
3470 int Idx = N->getMaskElt(i);
3471 if (Idx >= (int)NumElems) {
3472 unsigned Opc = V2.getOpcode();
3473 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3475 if (Opc != ISD::BUILD_VECTOR ||
3476 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3478 } else if (Idx >= 0) {
3479 unsigned Opc = V1.getOpcode();
3480 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3482 if (Opc != ISD::BUILD_VECTOR ||
3483 !X86::isZeroNode(V1.getOperand(Idx)))
3490 /// getZeroVector - Returns a vector of specified type with all zero elements.
3492 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3494 assert(VT.isVector() && "Expected a vector type");
3496 // Always build SSE zero vectors as <4 x i32> bitcasted
3497 // to their dest type. This ensures they get CSE'd.
3499 if (VT.getSizeInBits() == 128) { // SSE
3500 if (HasSSE2) { // SSE2
3501 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3502 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3504 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3505 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3507 } else if (VT.getSizeInBits() == 256) { // AVX
3508 // 256-bit logic and arithmetic instructions in AVX are
3509 // all floating-point, no support for integer ops. Default
3510 // to emitting fp zeroed vectors then.
3511 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3512 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3513 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3515 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3518 /// getOnesVector - Returns a vector of specified type with all bits set.
3520 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3521 assert(VT.isVector() && "Expected a vector type");
3523 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3524 // type. This ensures they get CSE'd.
3525 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3527 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3528 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3532 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3533 /// that point to V2 points to its first element.
3534 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3535 EVT VT = SVOp->getValueType(0);
3536 unsigned NumElems = VT.getVectorNumElements();
3538 bool Changed = false;
3539 SmallVector<int, 8> MaskVec;
3540 SVOp->getMask(MaskVec);
3542 for (unsigned i = 0; i != NumElems; ++i) {
3543 if (MaskVec[i] > (int)NumElems) {
3544 MaskVec[i] = NumElems;
3549 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3550 SVOp->getOperand(1), &MaskVec[0]);
3551 return SDValue(SVOp, 0);
3554 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3555 /// operation of specified width.
3556 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3558 unsigned NumElems = VT.getVectorNumElements();
3559 SmallVector<int, 8> Mask;
3560 Mask.push_back(NumElems);
3561 for (unsigned i = 1; i != NumElems; ++i)
3563 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3566 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3567 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3569 unsigned NumElems = VT.getVectorNumElements();
3570 SmallVector<int, 8> Mask;
3571 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3573 Mask.push_back(i + NumElems);
3575 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3578 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3579 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3581 unsigned NumElems = VT.getVectorNumElements();
3582 unsigned Half = NumElems/2;
3583 SmallVector<int, 8> Mask;
3584 for (unsigned i = 0; i != Half; ++i) {
3585 Mask.push_back(i + Half);
3586 Mask.push_back(i + NumElems + Half);
3588 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3591 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3592 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3593 EVT PVT = MVT::v4f32;
3594 EVT VT = SV->getValueType(0);
3595 DebugLoc dl = SV->getDebugLoc();
3596 SDValue V1 = SV->getOperand(0);
3597 int NumElems = VT.getVectorNumElements();
3598 int EltNo = SV->getSplatIndex();
3600 // unpack elements to the correct location
3601 while (NumElems > 4) {
3602 if (EltNo < NumElems/2) {
3603 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3605 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3606 EltNo -= NumElems/2;
3611 // Perform the splat.
3612 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3613 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3614 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3615 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3618 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3619 /// vector of zero or undef vector. This produces a shuffle where the low
3620 /// element of V2 is swizzled into the zero/undef vector, landing at element
3621 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3622 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3623 bool isZero, bool HasSSE2,
3624 SelectionDAG &DAG) {
3625 EVT VT = V2.getValueType();
3627 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3628 unsigned NumElems = VT.getVectorNumElements();
3629 SmallVector<int, 16> MaskVec;
3630 for (unsigned i = 0; i != NumElems; ++i)
3631 // If this is the insertion idx, put the low elt of V2 here.
3632 MaskVec.push_back(i == Idx ? NumElems : i);
3633 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3636 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3637 /// element of the result of the vector shuffle.
3638 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3641 return SDValue(); // Limit search depth.
3643 SDValue V = SDValue(N, 0);
3644 EVT VT = V.getValueType();
3645 unsigned Opcode = V.getOpcode();
3647 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3648 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3649 Index = SV->getMaskElt(Index);
3652 return DAG.getUNDEF(VT.getVectorElementType());
3654 int NumElems = VT.getVectorNumElements();
3655 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3656 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3659 // Recurse into target specific vector shuffles to find scalars.
3660 if (isTargetShuffle(Opcode)) {
3661 int NumElems = VT.getVectorNumElements();
3662 SmallVector<unsigned, 16> ShuffleMask;
3666 case X86ISD::SHUFPS:
3667 case X86ISD::SHUFPD:
3668 ImmN = N->getOperand(N->getNumOperands()-1);
3669 DecodeSHUFPSMask(NumElems,
3670 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3673 case X86ISD::PUNPCKHBW:
3674 case X86ISD::PUNPCKHWD:
3675 case X86ISD::PUNPCKHDQ:
3676 case X86ISD::PUNPCKHQDQ:
3677 DecodePUNPCKHMask(NumElems, ShuffleMask);
3679 case X86ISD::UNPCKHPS:
3680 case X86ISD::UNPCKHPD:
3681 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3683 case X86ISD::PUNPCKLBW:
3684 case X86ISD::PUNPCKLWD:
3685 case X86ISD::PUNPCKLDQ:
3686 case X86ISD::PUNPCKLQDQ:
3687 DecodePUNPCKLMask(NumElems, ShuffleMask);
3689 case X86ISD::UNPCKLPS:
3690 case X86ISD::UNPCKLPD:
3691 DecodeUNPCKLPMask(NumElems, ShuffleMask);
3693 case X86ISD::MOVHLPS:
3694 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3696 case X86ISD::MOVLHPS:
3697 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3699 case X86ISD::PSHUFD:
3700 ImmN = N->getOperand(N->getNumOperands()-1);
3701 DecodePSHUFMask(NumElems,
3702 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3705 case X86ISD::PSHUFHW:
3706 ImmN = N->getOperand(N->getNumOperands()-1);
3707 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3710 case X86ISD::PSHUFLW:
3711 ImmN = N->getOperand(N->getNumOperands()-1);
3712 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3716 case X86ISD::MOVSD: {
3717 // The index 0 always comes from the first element of the second source,
3718 // this is why MOVSS and MOVSD are used in the first place. The other
3719 // elements come from the other positions of the first source vector.
3720 unsigned OpNum = (Index == 0) ? 1 : 0;
3721 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3725 assert("not implemented for target shuffle node");
3729 Index = ShuffleMask[Index];
3731 return DAG.getUNDEF(VT.getVectorElementType());
3733 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3734 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3738 // Actual nodes that may contain scalar elements
3739 if (Opcode == ISD::BIT_CONVERT) {
3740 V = V.getOperand(0);
3741 EVT SrcVT = V.getValueType();
3742 unsigned NumElems = VT.getVectorNumElements();
3744 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3748 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3749 return (Index == 0) ? V.getOperand(0)
3750 : DAG.getUNDEF(VT.getVectorElementType());
3752 if (V.getOpcode() == ISD::BUILD_VECTOR)
3753 return V.getOperand(Index);
3758 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3759 /// shuffle operation which come from a consecutively from a zero. The
3760 /// search can start in two diferent directions, from left or right.
3762 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3763 bool ZerosFromLeft, SelectionDAG &DAG) {
3766 while (i < NumElems) {
3767 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3768 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3769 if (!(Elt.getNode() &&
3770 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3778 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3779 /// MaskE correspond consecutively to elements from one of the vector operands,
3780 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3782 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3783 int OpIdx, int NumElems, unsigned &OpNum) {
3784 bool SeenV1 = false;
3785 bool SeenV2 = false;
3787 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3788 int Idx = SVOp->getMaskElt(i);
3789 // Ignore undef indicies
3798 // Only accept consecutive elements from the same vector
3799 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3803 OpNum = SeenV1 ? 0 : 1;
3807 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3808 /// logical left shift of a vector.
3809 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3810 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3811 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3812 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3813 false /* check zeros from right */, DAG);
3819 // Considering the elements in the mask that are not consecutive zeros,
3820 // check if they consecutively come from only one of the source vectors.
3822 // V1 = {X, A, B, C} 0
3824 // vector_shuffle V1, V2 <1, 2, 3, X>
3826 if (!isShuffleMaskConsecutive(SVOp,
3827 0, // Mask Start Index
3828 NumElems-NumZeros-1, // Mask End Index
3829 NumZeros, // Where to start looking in the src vector
3830 NumElems, // Number of elements in vector
3831 OpSrc)) // Which source operand ?
3836 ShVal = SVOp->getOperand(OpSrc);
3840 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3841 /// logical left shift of a vector.
3842 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3843 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3844 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3845 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3846 true /* check zeros from left */, DAG);
3852 // Considering the elements in the mask that are not consecutive zeros,
3853 // check if they consecutively come from only one of the source vectors.
3855 // 0 { A, B, X, X } = V2
3857 // vector_shuffle V1, V2 <X, X, 4, 5>
3859 if (!isShuffleMaskConsecutive(SVOp,
3860 NumZeros, // Mask Start Index
3861 NumElems-1, // Mask End Index
3862 0, // Where to start looking in the src vector
3863 NumElems, // Number of elements in vector
3864 OpSrc)) // Which source operand ?
3869 ShVal = SVOp->getOperand(OpSrc);
3873 /// isVectorShift - Returns true if the shuffle can be implemented as a
3874 /// logical left or right shift of a vector.
3875 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3876 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3877 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3878 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3884 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3886 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3887 unsigned NumNonZero, unsigned NumZero,
3889 const TargetLowering &TLI) {
3893 DebugLoc dl = Op.getDebugLoc();
3896 for (unsigned i = 0; i < 16; ++i) {
3897 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3898 if (ThisIsNonZero && First) {
3900 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3902 V = DAG.getUNDEF(MVT::v8i16);
3907 SDValue ThisElt(0, 0), LastElt(0, 0);
3908 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3909 if (LastIsNonZero) {
3910 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3911 MVT::i16, Op.getOperand(i-1));
3913 if (ThisIsNonZero) {
3914 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3915 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3916 ThisElt, DAG.getConstant(8, MVT::i8));
3918 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3922 if (ThisElt.getNode())
3923 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3924 DAG.getIntPtrConstant(i/2));
3928 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3931 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3933 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3934 unsigned NumNonZero, unsigned NumZero,
3936 const TargetLowering &TLI) {
3940 DebugLoc dl = Op.getDebugLoc();
3943 for (unsigned i = 0; i < 8; ++i) {
3944 bool isNonZero = (NonZeros & (1 << i)) != 0;
3948 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3950 V = DAG.getUNDEF(MVT::v8i16);
3953 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3954 MVT::v8i16, V, Op.getOperand(i),
3955 DAG.getIntPtrConstant(i));
3962 /// getVShift - Return a vector logical shift node.
3964 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3965 unsigned NumBits, SelectionDAG &DAG,
3966 const TargetLowering &TLI, DebugLoc dl) {
3967 EVT ShVT = MVT::v2i64;
3968 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3969 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3970 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3971 DAG.getNode(Opc, dl, ShVT, SrcOp,
3972 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3976 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3977 SelectionDAG &DAG) const {
3979 // Check if the scalar load can be widened into a vector load. And if
3980 // the address is "base + cst" see if the cst can be "absorbed" into
3981 // the shuffle mask.
3982 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3983 SDValue Ptr = LD->getBasePtr();
3984 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3986 EVT PVT = LD->getValueType(0);
3987 if (PVT != MVT::i32 && PVT != MVT::f32)
3992 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3993 FI = FINode->getIndex();
3995 } else if (Ptr.getOpcode() == ISD::ADD &&
3996 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3997 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3998 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3999 Offset = Ptr.getConstantOperandVal(1);
4000 Ptr = Ptr.getOperand(0);
4005 SDValue Chain = LD->getChain();
4006 // Make sure the stack object alignment is at least 16.
4007 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4008 if (DAG.InferPtrAlignment(Ptr) < 16) {
4009 if (MFI->isFixedObjectIndex(FI)) {
4010 // Can't change the alignment. FIXME: It's possible to compute
4011 // the exact stack offset and reference FI + adjust offset instead.
4012 // If someone *really* cares about this. That's the way to implement it.
4015 MFI->setObjectAlignment(FI, 16);
4019 // (Offset % 16) must be multiple of 4. Then address is then
4020 // Ptr + (Offset & ~15).
4023 if ((Offset % 16) & 3)
4025 int64_t StartOffset = Offset & ~15;
4027 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4028 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4030 int EltNo = (Offset - StartOffset) >> 2;
4031 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4032 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4033 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4034 LD->getPointerInfo().getWithOffset(StartOffset),
4036 // Canonicalize it to a v4i32 shuffle.
4037 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
4038 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4039 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4040 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4046 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4047 /// vector of type 'VT', see if the elements can be replaced by a single large
4048 /// load which has the same value as a build_vector whose operands are 'elts'.
4050 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4052 /// FIXME: we'd also like to handle the case where the last elements are zero
4053 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4054 /// There's even a handy isZeroNode for that purpose.
4055 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4056 DebugLoc &DL, SelectionDAG &DAG) {
4057 EVT EltVT = VT.getVectorElementType();
4058 unsigned NumElems = Elts.size();
4060 LoadSDNode *LDBase = NULL;
4061 unsigned LastLoadedElt = -1U;
4063 // For each element in the initializer, see if we've found a load or an undef.
4064 // If we don't find an initial load element, or later load elements are
4065 // non-consecutive, bail out.
4066 for (unsigned i = 0; i < NumElems; ++i) {
4067 SDValue Elt = Elts[i];
4069 if (!Elt.getNode() ||
4070 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4073 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4075 LDBase = cast<LoadSDNode>(Elt.getNode());
4079 if (Elt.getOpcode() == ISD::UNDEF)
4082 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4083 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4088 // If we have found an entire vector of loads and undefs, then return a large
4089 // load of the entire vector width starting at the base pointer. If we found
4090 // consecutive loads for the low half, generate a vzext_load node.
4091 if (LastLoadedElt == NumElems - 1) {
4092 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4093 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4094 LDBase->getPointerInfo(),
4095 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4096 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4097 LDBase->getPointerInfo(),
4098 LDBase->isVolatile(), LDBase->isNonTemporal(),
4099 LDBase->getAlignment());
4100 } else if (NumElems == 4 && LastLoadedElt == 1) {
4101 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4102 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4103 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4105 LDBase->getMemOperand());
4106 return DAG.getNode(ISD::BIT_CONVERT, DL, VT, ResNode);
4112 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4113 DebugLoc dl = Op.getDebugLoc();
4114 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4115 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4116 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4117 // is present, so AllOnes is ignored.
4118 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4119 (Op.getValueType().getSizeInBits() != 256 &&
4120 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4121 // Canonicalize this to <4 x i32> (SSE) to
4122 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4123 // eliminated on x86-32 hosts.
4124 if (Op.getValueType() == MVT::v4i32)
4127 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4128 return getOnesVector(Op.getValueType(), DAG, dl);
4129 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4132 EVT VT = Op.getValueType();
4133 EVT ExtVT = VT.getVectorElementType();
4134 unsigned EVTBits = ExtVT.getSizeInBits();
4136 unsigned NumElems = Op.getNumOperands();
4137 unsigned NumZero = 0;
4138 unsigned NumNonZero = 0;
4139 unsigned NonZeros = 0;
4140 bool IsAllConstants = true;
4141 SmallSet<SDValue, 8> Values;
4142 for (unsigned i = 0; i < NumElems; ++i) {
4143 SDValue Elt = Op.getOperand(i);
4144 if (Elt.getOpcode() == ISD::UNDEF)
4147 if (Elt.getOpcode() != ISD::Constant &&
4148 Elt.getOpcode() != ISD::ConstantFP)
4149 IsAllConstants = false;
4150 if (X86::isZeroNode(Elt))
4153 NonZeros |= (1 << i);
4158 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4159 if (NumNonZero == 0)
4160 return DAG.getUNDEF(VT);
4162 // Special case for single non-zero, non-undef, element.
4163 if (NumNonZero == 1) {
4164 unsigned Idx = CountTrailingZeros_32(NonZeros);
4165 SDValue Item = Op.getOperand(Idx);
4167 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4168 // the value are obviously zero, truncate the value to i32 and do the
4169 // insertion that way. Only do this if the value is non-constant or if the
4170 // value is a constant being inserted into element 0. It is cheaper to do
4171 // a constant pool load than it is to do a movd + shuffle.
4172 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4173 (!IsAllConstants || Idx == 0)) {
4174 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4176 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4177 EVT VecVT = MVT::v4i32;
4178 unsigned VecElts = 4;
4180 // Truncate the value (which may itself be a constant) to i32, and
4181 // convert it to a vector with movd (S2V+shuffle to zero extend).
4182 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4183 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4184 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4185 Subtarget->hasSSE2(), DAG);
4187 // Now we have our 32-bit value zero extended in the low element of
4188 // a vector. If Idx != 0, swizzle it into place.
4190 SmallVector<int, 4> Mask;
4191 Mask.push_back(Idx);
4192 for (unsigned i = 1; i != VecElts; ++i)
4194 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4195 DAG.getUNDEF(Item.getValueType()),
4198 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
4202 // If we have a constant or non-constant insertion into the low element of
4203 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4204 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4205 // depending on what the source datatype is.
4208 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4209 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4210 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4211 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4212 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4213 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4215 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4216 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4217 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4218 EVT MiddleVT = MVT::v4i32;
4219 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4220 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4221 Subtarget->hasSSE2(), DAG);
4222 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
4226 // Is it a vector logical left shift?
4227 if (NumElems == 2 && Idx == 1 &&
4228 X86::isZeroNode(Op.getOperand(0)) &&
4229 !X86::isZeroNode(Op.getOperand(1))) {
4230 unsigned NumBits = VT.getSizeInBits();
4231 return getVShift(true, VT,
4232 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4233 VT, Op.getOperand(1)),
4234 NumBits/2, DAG, *this, dl);
4237 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4240 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4241 // is a non-constant being inserted into an element other than the low one,
4242 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4243 // movd/movss) to move this into the low element, then shuffle it into
4245 if (EVTBits == 32) {
4246 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4248 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4249 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4250 Subtarget->hasSSE2(), DAG);
4251 SmallVector<int, 8> MaskVec;
4252 for (unsigned i = 0; i < NumElems; i++)
4253 MaskVec.push_back(i == Idx ? 0 : 1);
4254 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4258 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4259 if (Values.size() == 1) {
4260 if (EVTBits == 32) {
4261 // Instead of a shuffle like this:
4262 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4263 // Check if it's possible to issue this instead.
4264 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4265 unsigned Idx = CountTrailingZeros_32(NonZeros);
4266 SDValue Item = Op.getOperand(Idx);
4267 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4268 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4273 // A vector full of immediates; various special cases are already
4274 // handled, so this is best done with a single constant-pool load.
4278 // Let legalizer expand 2-wide build_vectors.
4279 if (EVTBits == 64) {
4280 if (NumNonZero == 1) {
4281 // One half is zero or undef.
4282 unsigned Idx = CountTrailingZeros_32(NonZeros);
4283 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4284 Op.getOperand(Idx));
4285 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4286 Subtarget->hasSSE2(), DAG);
4291 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4292 if (EVTBits == 8 && NumElems == 16) {
4293 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4295 if (V.getNode()) return V;
4298 if (EVTBits == 16 && NumElems == 8) {
4299 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4301 if (V.getNode()) return V;
4304 // If element VT is == 32 bits, turn it into a number of shuffles.
4305 SmallVector<SDValue, 8> V;
4307 if (NumElems == 4 && NumZero > 0) {
4308 for (unsigned i = 0; i < 4; ++i) {
4309 bool isZero = !(NonZeros & (1 << i));
4311 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4313 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4316 for (unsigned i = 0; i < 2; ++i) {
4317 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4320 V[i] = V[i*2]; // Must be a zero vector.
4323 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4326 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4329 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4334 SmallVector<int, 8> MaskVec;
4335 bool Reverse = (NonZeros & 0x3) == 2;
4336 for (unsigned i = 0; i < 2; ++i)
4337 MaskVec.push_back(Reverse ? 1-i : i);
4338 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4339 for (unsigned i = 0; i < 2; ++i)
4340 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4341 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4344 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4345 // Check for a build vector of consecutive loads.
4346 for (unsigned i = 0; i < NumElems; ++i)
4347 V[i] = Op.getOperand(i);
4349 // Check for elements which are consecutive loads.
4350 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4354 // For SSE 4.1, use insertps to put the high elements into the low element.
4355 if (getSubtarget()->hasSSE41()) {
4357 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4358 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4360 Result = DAG.getUNDEF(VT);
4362 for (unsigned i = 1; i < NumElems; ++i) {
4363 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4364 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4365 Op.getOperand(i), DAG.getIntPtrConstant(i));
4370 // Otherwise, expand into a number of unpckl*, start by extending each of
4371 // our (non-undef) elements to the full vector width with the element in the
4372 // bottom slot of the vector (which generates no code for SSE).
4373 for (unsigned i = 0; i < NumElems; ++i) {
4374 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4375 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4377 V[i] = DAG.getUNDEF(VT);
4380 // Next, we iteratively mix elements, e.g. for v4f32:
4381 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4382 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4383 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4384 unsigned EltStride = NumElems >> 1;
4385 while (EltStride != 0) {
4386 for (unsigned i = 0; i < EltStride; ++i) {
4387 // If V[i+EltStride] is undef and this is the first round of mixing,
4388 // then it is safe to just drop this shuffle: V[i] is already in the
4389 // right place, the one element (since it's the first round) being
4390 // inserted as undef can be dropped. This isn't safe for successive
4391 // rounds because they will permute elements within both vectors.
4392 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4393 EltStride == NumElems/2)
4396 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4406 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4407 // We support concatenate two MMX registers and place them in a MMX
4408 // register. This is better than doing a stack convert.
4409 DebugLoc dl = Op.getDebugLoc();
4410 EVT ResVT = Op.getValueType();
4411 assert(Op.getNumOperands() == 2);
4412 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4413 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4415 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4416 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4417 InVec = Op.getOperand(1);
4418 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4419 unsigned NumElts = ResVT.getVectorNumElements();
4420 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4421 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4422 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4424 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4425 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4426 Mask[0] = 0; Mask[1] = 2;
4427 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4429 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4432 // v8i16 shuffles - Prefer shuffles in the following order:
4433 // 1. [all] pshuflw, pshufhw, optional move
4434 // 2. [ssse3] 1 x pshufb
4435 // 3. [ssse3] 2 x pshufb + 1 x por
4436 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4438 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4439 SelectionDAG &DAG) const {
4440 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4441 SDValue V1 = SVOp->getOperand(0);
4442 SDValue V2 = SVOp->getOperand(1);
4443 DebugLoc dl = SVOp->getDebugLoc();
4444 SmallVector<int, 8> MaskVals;
4446 // Determine if more than 1 of the words in each of the low and high quadwords
4447 // of the result come from the same quadword of one of the two inputs. Undef
4448 // mask values count as coming from any quadword, for better codegen.
4449 SmallVector<unsigned, 4> LoQuad(4);
4450 SmallVector<unsigned, 4> HiQuad(4);
4451 BitVector InputQuads(4);
4452 for (unsigned i = 0; i < 8; ++i) {
4453 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4454 int EltIdx = SVOp->getMaskElt(i);
4455 MaskVals.push_back(EltIdx);
4464 InputQuads.set(EltIdx / 4);
4467 int BestLoQuad = -1;
4468 unsigned MaxQuad = 1;
4469 for (unsigned i = 0; i < 4; ++i) {
4470 if (LoQuad[i] > MaxQuad) {
4472 MaxQuad = LoQuad[i];
4476 int BestHiQuad = -1;
4478 for (unsigned i = 0; i < 4; ++i) {
4479 if (HiQuad[i] > MaxQuad) {
4481 MaxQuad = HiQuad[i];
4485 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4486 // of the two input vectors, shuffle them into one input vector so only a
4487 // single pshufb instruction is necessary. If There are more than 2 input
4488 // quads, disable the next transformation since it does not help SSSE3.
4489 bool V1Used = InputQuads[0] || InputQuads[1];
4490 bool V2Used = InputQuads[2] || InputQuads[3];
4491 if (Subtarget->hasSSSE3()) {
4492 if (InputQuads.count() == 2 && V1Used && V2Used) {
4493 BestLoQuad = InputQuads.find_first();
4494 BestHiQuad = InputQuads.find_next(BestLoQuad);
4496 if (InputQuads.count() > 2) {
4502 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4503 // the shuffle mask. If a quad is scored as -1, that means that it contains
4504 // words from all 4 input quadwords.
4506 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4507 SmallVector<int, 8> MaskV;
4508 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4509 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4510 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4511 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4512 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4513 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4515 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4516 // source words for the shuffle, to aid later transformations.
4517 bool AllWordsInNewV = true;
4518 bool InOrder[2] = { true, true };
4519 for (unsigned i = 0; i != 8; ++i) {
4520 int idx = MaskVals[i];
4522 InOrder[i/4] = false;
4523 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4525 AllWordsInNewV = false;
4529 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4530 if (AllWordsInNewV) {
4531 for (int i = 0; i != 8; ++i) {
4532 int idx = MaskVals[i];
4535 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4536 if ((idx != i) && idx < 4)
4538 if ((idx != i) && idx > 3)
4547 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4548 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4549 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4550 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4551 unsigned TargetMask = 0;
4552 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4553 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4554 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4555 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4556 V1 = NewV.getOperand(0);
4557 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4561 // If we have SSSE3, and all words of the result are from 1 input vector,
4562 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4563 // is present, fall back to case 4.
4564 if (Subtarget->hasSSSE3()) {
4565 SmallVector<SDValue,16> pshufbMask;
4567 // If we have elements from both input vectors, set the high bit of the
4568 // shuffle mask element to zero out elements that come from V2 in the V1
4569 // mask, and elements that come from V1 in the V2 mask, so that the two
4570 // results can be OR'd together.
4571 bool TwoInputs = V1Used && V2Used;
4572 for (unsigned i = 0; i != 8; ++i) {
4573 int EltIdx = MaskVals[i] * 2;
4574 if (TwoInputs && (EltIdx >= 16)) {
4575 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4576 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4579 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4580 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4582 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4583 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4584 DAG.getNode(ISD::BUILD_VECTOR, dl,
4585 MVT::v16i8, &pshufbMask[0], 16));
4587 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4589 // Calculate the shuffle mask for the second input, shuffle it, and
4590 // OR it with the first shuffled input.
4592 for (unsigned i = 0; i != 8; ++i) {
4593 int EltIdx = MaskVals[i] * 2;
4595 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4596 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4599 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4600 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4602 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4603 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4604 DAG.getNode(ISD::BUILD_VECTOR, dl,
4605 MVT::v16i8, &pshufbMask[0], 16));
4606 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4607 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4610 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4611 // and update MaskVals with new element order.
4612 BitVector InOrder(8);
4613 if (BestLoQuad >= 0) {
4614 SmallVector<int, 8> MaskV;
4615 for (int i = 0; i != 4; ++i) {
4616 int idx = MaskVals[i];
4618 MaskV.push_back(-1);
4620 } else if ((idx / 4) == BestLoQuad) {
4621 MaskV.push_back(idx & 3);
4624 MaskV.push_back(-1);
4627 for (unsigned i = 4; i != 8; ++i)
4629 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4632 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4633 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4635 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4639 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4640 // and update MaskVals with the new element order.
4641 if (BestHiQuad >= 0) {
4642 SmallVector<int, 8> MaskV;
4643 for (unsigned i = 0; i != 4; ++i)
4645 for (unsigned i = 4; i != 8; ++i) {
4646 int idx = MaskVals[i];
4648 MaskV.push_back(-1);
4650 } else if ((idx / 4) == BestHiQuad) {
4651 MaskV.push_back((idx & 3) + 4);
4654 MaskV.push_back(-1);
4657 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4660 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4661 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4663 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4667 // In case BestHi & BestLo were both -1, which means each quadword has a word
4668 // from each of the four input quadwords, calculate the InOrder bitvector now
4669 // before falling through to the insert/extract cleanup.
4670 if (BestLoQuad == -1 && BestHiQuad == -1) {
4672 for (int i = 0; i != 8; ++i)
4673 if (MaskVals[i] < 0 || MaskVals[i] == i)
4677 // The other elements are put in the right place using pextrw and pinsrw.
4678 for (unsigned i = 0; i != 8; ++i) {
4681 int EltIdx = MaskVals[i];
4684 SDValue ExtOp = (EltIdx < 8)
4685 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4686 DAG.getIntPtrConstant(EltIdx))
4687 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4688 DAG.getIntPtrConstant(EltIdx - 8));
4689 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4690 DAG.getIntPtrConstant(i));
4695 // v16i8 shuffles - Prefer shuffles in the following order:
4696 // 1. [ssse3] 1 x pshufb
4697 // 2. [ssse3] 2 x pshufb + 1 x por
4698 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4700 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4702 const X86TargetLowering &TLI) {
4703 SDValue V1 = SVOp->getOperand(0);
4704 SDValue V2 = SVOp->getOperand(1);
4705 DebugLoc dl = SVOp->getDebugLoc();
4706 SmallVector<int, 16> MaskVals;
4707 SVOp->getMask(MaskVals);
4709 // If we have SSSE3, case 1 is generated when all result bytes come from
4710 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4711 // present, fall back to case 3.
4712 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4715 for (unsigned i = 0; i < 16; ++i) {
4716 int EltIdx = MaskVals[i];
4725 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4726 if (TLI.getSubtarget()->hasSSSE3()) {
4727 SmallVector<SDValue,16> pshufbMask;
4729 // If all result elements are from one input vector, then only translate
4730 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4732 // Otherwise, we have elements from both input vectors, and must zero out
4733 // elements that come from V2 in the first mask, and V1 in the second mask
4734 // so that we can OR them together.
4735 bool TwoInputs = !(V1Only || V2Only);
4736 for (unsigned i = 0; i != 16; ++i) {
4737 int EltIdx = MaskVals[i];
4738 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4739 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4742 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4744 // If all the elements are from V2, assign it to V1 and return after
4745 // building the first pshufb.
4748 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4749 DAG.getNode(ISD::BUILD_VECTOR, dl,
4750 MVT::v16i8, &pshufbMask[0], 16));
4754 // Calculate the shuffle mask for the second input, shuffle it, and
4755 // OR it with the first shuffled input.
4757 for (unsigned i = 0; i != 16; ++i) {
4758 int EltIdx = MaskVals[i];
4760 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4763 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4765 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4766 DAG.getNode(ISD::BUILD_VECTOR, dl,
4767 MVT::v16i8, &pshufbMask[0], 16));
4768 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4771 // No SSSE3 - Calculate in place words and then fix all out of place words
4772 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4773 // the 16 different words that comprise the two doublequadword input vectors.
4774 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4775 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4776 SDValue NewV = V2Only ? V2 : V1;
4777 for (int i = 0; i != 8; ++i) {
4778 int Elt0 = MaskVals[i*2];
4779 int Elt1 = MaskVals[i*2+1];
4781 // This word of the result is all undef, skip it.
4782 if (Elt0 < 0 && Elt1 < 0)
4785 // This word of the result is already in the correct place, skip it.
4786 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4788 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4791 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4792 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4795 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4796 // using a single extract together, load it and store it.
4797 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4798 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4799 DAG.getIntPtrConstant(Elt1 / 2));
4800 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4801 DAG.getIntPtrConstant(i));
4805 // If Elt1 is defined, extract it from the appropriate source. If the
4806 // source byte is not also odd, shift the extracted word left 8 bits
4807 // otherwise clear the bottom 8 bits if we need to do an or.
4809 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4810 DAG.getIntPtrConstant(Elt1 / 2));
4811 if ((Elt1 & 1) == 0)
4812 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4813 DAG.getConstant(8, TLI.getShiftAmountTy()));
4815 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4816 DAG.getConstant(0xFF00, MVT::i16));
4818 // If Elt0 is defined, extract it from the appropriate source. If the
4819 // source byte is not also even, shift the extracted word right 8 bits. If
4820 // Elt1 was also defined, OR the extracted values together before
4821 // inserting them in the result.
4823 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4824 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4825 if ((Elt0 & 1) != 0)
4826 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4827 DAG.getConstant(8, TLI.getShiftAmountTy()));
4829 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4830 DAG.getConstant(0x00FF, MVT::i16));
4831 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4834 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4835 DAG.getIntPtrConstant(i));
4837 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4840 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4841 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4842 /// done when every pair / quad of shuffle mask elements point to elements in
4843 /// the right sequence. e.g.
4844 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4846 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4847 SelectionDAG &DAG, DebugLoc dl) {
4848 EVT VT = SVOp->getValueType(0);
4849 SDValue V1 = SVOp->getOperand(0);
4850 SDValue V2 = SVOp->getOperand(1);
4851 unsigned NumElems = VT.getVectorNumElements();
4852 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4854 switch (VT.getSimpleVT().SimpleTy) {
4855 default: assert(false && "Unexpected!");
4856 case MVT::v4f32: NewVT = MVT::v2f64; break;
4857 case MVT::v4i32: NewVT = MVT::v2i64; break;
4858 case MVT::v8i16: NewVT = MVT::v4i32; break;
4859 case MVT::v16i8: NewVT = MVT::v4i32; break;
4862 int Scale = NumElems / NewWidth;
4863 SmallVector<int, 8> MaskVec;
4864 for (unsigned i = 0; i < NumElems; i += Scale) {
4866 for (int j = 0; j < Scale; ++j) {
4867 int EltIdx = SVOp->getMaskElt(i+j);
4871 StartIdx = EltIdx - (EltIdx % Scale);
4872 if (EltIdx != StartIdx + j)
4876 MaskVec.push_back(-1);
4878 MaskVec.push_back(StartIdx / Scale);
4881 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4882 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4883 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4886 /// getVZextMovL - Return a zero-extending vector move low node.
4888 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4889 SDValue SrcOp, SelectionDAG &DAG,
4890 const X86Subtarget *Subtarget, DebugLoc dl) {
4891 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4892 LoadSDNode *LD = NULL;
4893 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4894 LD = dyn_cast<LoadSDNode>(SrcOp);
4896 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4898 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4899 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4900 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4901 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4902 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4904 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4905 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4906 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4907 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4915 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4916 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4917 DAG.getNode(ISD::BIT_CONVERT, dl,
4921 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4924 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4925 SDValue V1 = SVOp->getOperand(0);
4926 SDValue V2 = SVOp->getOperand(1);
4927 DebugLoc dl = SVOp->getDebugLoc();
4928 EVT VT = SVOp->getValueType(0);
4930 SmallVector<std::pair<int, int>, 8> Locs;
4932 SmallVector<int, 8> Mask1(4U, -1);
4933 SmallVector<int, 8> PermMask;
4934 SVOp->getMask(PermMask);
4938 for (unsigned i = 0; i != 4; ++i) {
4939 int Idx = PermMask[i];
4941 Locs[i] = std::make_pair(-1, -1);
4943 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4945 Locs[i] = std::make_pair(0, NumLo);
4949 Locs[i] = std::make_pair(1, NumHi);
4951 Mask1[2+NumHi] = Idx;
4957 if (NumLo <= 2 && NumHi <= 2) {
4958 // If no more than two elements come from either vector. This can be
4959 // implemented with two shuffles. First shuffle gather the elements.
4960 // The second shuffle, which takes the first shuffle as both of its
4961 // vector operands, put the elements into the right order.
4962 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4964 SmallVector<int, 8> Mask2(4U, -1);
4966 for (unsigned i = 0; i != 4; ++i) {
4967 if (Locs[i].first == -1)
4970 unsigned Idx = (i < 2) ? 0 : 4;
4971 Idx += Locs[i].first * 2 + Locs[i].second;
4976 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4977 } else if (NumLo == 3 || NumHi == 3) {
4978 // Otherwise, we must have three elements from one vector, call it X, and
4979 // one element from the other, call it Y. First, use a shufps to build an
4980 // intermediate vector with the one element from Y and the element from X
4981 // that will be in the same half in the final destination (the indexes don't
4982 // matter). Then, use a shufps to build the final vector, taking the half
4983 // containing the element from Y from the intermediate, and the other half
4986 // Normalize it so the 3 elements come from V1.
4987 CommuteVectorShuffleMask(PermMask, VT);
4991 // Find the element from V2.
4993 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4994 int Val = PermMask[HiIndex];
5001 Mask1[0] = PermMask[HiIndex];
5003 Mask1[2] = PermMask[HiIndex^1];
5005 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5008 Mask1[0] = PermMask[0];
5009 Mask1[1] = PermMask[1];
5010 Mask1[2] = HiIndex & 1 ? 6 : 4;
5011 Mask1[3] = HiIndex & 1 ? 4 : 6;
5012 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5014 Mask1[0] = HiIndex & 1 ? 2 : 0;
5015 Mask1[1] = HiIndex & 1 ? 0 : 2;
5016 Mask1[2] = PermMask[2];
5017 Mask1[3] = PermMask[3];
5022 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5026 // Break it into (shuffle shuffle_hi, shuffle_lo).
5028 SmallVector<int,8> LoMask(4U, -1);
5029 SmallVector<int,8> HiMask(4U, -1);
5031 SmallVector<int,8> *MaskPtr = &LoMask;
5032 unsigned MaskIdx = 0;
5035 for (unsigned i = 0; i != 4; ++i) {
5042 int Idx = PermMask[i];
5044 Locs[i] = std::make_pair(-1, -1);
5045 } else if (Idx < 4) {
5046 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5047 (*MaskPtr)[LoIdx] = Idx;
5050 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5051 (*MaskPtr)[HiIdx] = Idx;
5056 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5057 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5058 SmallVector<int, 8> MaskOps;
5059 for (unsigned i = 0; i != 4; ++i) {
5060 if (Locs[i].first == -1) {
5061 MaskOps.push_back(-1);
5063 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5064 MaskOps.push_back(Idx);
5067 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5070 static bool MayFoldVectorLoad(SDValue V) {
5071 if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5072 V = V.getOperand(0);
5073 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5074 V = V.getOperand(0);
5080 // FIXME: the version above should always be used. Since there's
5081 // a bug where several vector shuffles can't be folded because the
5082 // DAG is not updated during lowering and a node claims to have two
5083 // uses while it only has one, use this version, and let isel match
5084 // another instruction if the load really happens to have more than
5085 // one use. Remove this version after this bug get fixed.
5086 // rdar://8434668, PR8156
5087 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5088 if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5089 V = V.getOperand(0);
5090 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5091 V = V.getOperand(0);
5092 if (ISD::isNormalLoad(V.getNode()))
5097 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5098 /// a vector extract, and if both can be later optimized into a single load.
5099 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5100 /// here because otherwise a target specific shuffle node is going to be
5101 /// emitted for this shuffle, and the optimization not done.
5102 /// FIXME: This is probably not the best approach, but fix the problem
5103 /// until the right path is decided.
5105 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5106 const TargetLowering &TLI) {
5107 EVT VT = V.getValueType();
5108 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5110 // Be sure that the vector shuffle is present in a pattern like this:
5111 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5115 SDNode *N = *V.getNode()->use_begin();
5116 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5119 SDValue EltNo = N->getOperand(1);
5120 if (!isa<ConstantSDNode>(EltNo))
5123 // If the bit convert changed the number of elements, it is unsafe
5124 // to examine the mask.
5125 bool HasShuffleIntoBitcast = false;
5126 if (V.getOpcode() == ISD::BIT_CONVERT) {
5127 EVT SrcVT = V.getOperand(0).getValueType();
5128 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5130 V = V.getOperand(0);
5131 HasShuffleIntoBitcast = true;
5134 // Select the input vector, guarding against out of range extract vector.
5135 unsigned NumElems = VT.getVectorNumElements();
5136 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5137 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5138 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5140 // Skip one more bit_convert if necessary
5141 if (V.getOpcode() == ISD::BIT_CONVERT)
5142 V = V.getOperand(0);
5144 if (ISD::isNormalLoad(V.getNode())) {
5145 // Is the original load suitable?
5146 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5148 // FIXME: avoid the multi-use bug that is preventing lots of
5149 // of foldings to be detected, this is still wrong of course, but
5150 // give the temporary desired behavior, and if it happens that
5151 // the load has real more uses, during isel it will not fold, and
5152 // will generate poor code.
5153 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5156 if (!HasShuffleIntoBitcast)
5159 // If there's a bitcast before the shuffle, check if the load type and
5160 // alignment is valid.
5161 unsigned Align = LN0->getAlignment();
5163 TLI.getTargetData()->getABITypeAlignment(
5164 VT.getTypeForEVT(*DAG.getContext()));
5166 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5174 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5175 EVT VT = Op.getValueType();
5177 // Canonizalize to v2f64.
5178 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, V1);
5179 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5180 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5185 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5187 SDValue V1 = Op.getOperand(0);
5188 SDValue V2 = Op.getOperand(1);
5189 EVT VT = Op.getValueType();
5191 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5193 if (HasSSE2 && VT == MVT::v2f64)
5194 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5197 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5201 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5202 SDValue V1 = Op.getOperand(0);
5203 SDValue V2 = Op.getOperand(1);
5204 EVT VT = Op.getValueType();
5206 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5207 "unsupported shuffle type");
5209 if (V2.getOpcode() == ISD::UNDEF)
5213 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5217 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5218 SDValue V1 = Op.getOperand(0);
5219 SDValue V2 = Op.getOperand(1);
5220 EVT VT = Op.getValueType();
5221 unsigned NumElems = VT.getVectorNumElements();
5223 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5224 // operand of these instructions is only memory, so check if there's a
5225 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5227 bool CanFoldLoad = false;
5229 // Trivial case, when V2 comes from a load.
5230 if (MayFoldVectorLoad(V2))
5233 // When V1 is a load, it can be folded later into a store in isel, example:
5234 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5236 // (MOVLPSmr addr:$src1, VR128:$src2)
5237 // So, recognize this potential and also use MOVLPS or MOVLPD
5238 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5242 if (HasSSE2 && NumElems == 2)
5243 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5246 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5249 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5250 // movl and movlp will both match v2i64, but v2i64 is never matched by
5251 // movl earlier because we make it strict to avoid messing with the movlp load
5252 // folding logic (see the code above getMOVLP call). Match it here then,
5253 // this is horrible, but will stay like this until we move all shuffle
5254 // matching to x86 specific nodes. Note that for the 1st condition all
5255 // types are matched with movsd.
5256 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5257 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5259 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5262 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5264 // Invert the operand order and use SHUFPS to match it.
5265 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5266 X86::getShuffleSHUFImmediate(SVOp), DAG);
5269 static inline unsigned getUNPCKLOpcode(EVT VT) {
5270 switch(VT.getSimpleVT().SimpleTy) {
5271 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5272 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5273 case MVT::v4f32: return X86ISD::UNPCKLPS;
5274 case MVT::v2f64: return X86ISD::UNPCKLPD;
5275 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5276 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5278 llvm_unreachable("Unknow type for unpckl");
5283 static inline unsigned getUNPCKHOpcode(EVT VT) {
5284 switch(VT.getSimpleVT().SimpleTy) {
5285 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5286 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5287 case MVT::v4f32: return X86ISD::UNPCKHPS;
5288 case MVT::v2f64: return X86ISD::UNPCKHPD;
5289 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5290 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5292 llvm_unreachable("Unknow type for unpckh");
5298 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5299 const TargetLowering &TLI,
5300 const X86Subtarget *Subtarget) {
5301 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5302 EVT VT = Op.getValueType();
5303 DebugLoc dl = Op.getDebugLoc();
5304 SDValue V1 = Op.getOperand(0);
5305 SDValue V2 = Op.getOperand(1);
5307 if (isZeroShuffle(SVOp))
5308 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5310 // Handle splat operations
5311 if (SVOp->isSplat()) {
5312 // Special case, this is the only place now where it's
5313 // allowed to return a vector_shuffle operation without
5314 // using a target specific node, because *hopefully* it
5315 // will be optimized away by the dag combiner.
5316 if (VT.getVectorNumElements() <= 4 &&
5317 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5320 // Handle splats by matching through known masks
5321 if (VT.getVectorNumElements() <= 4)
5324 // Canonicalize all of the remaining to v4f32.
5325 return PromoteSplat(SVOp, DAG);
5328 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5330 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5331 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5332 if (NewOp.getNode())
5333 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, NewOp);
5334 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5335 // FIXME: Figure out a cleaner way to do this.
5336 // Try to make use of movq to zero out the top part.
5337 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5338 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5339 if (NewOp.getNode()) {
5340 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5341 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5342 DAG, Subtarget, dl);
5344 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5345 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5346 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5347 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5348 DAG, Subtarget, dl);
5355 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5356 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5357 SDValue V1 = Op.getOperand(0);
5358 SDValue V2 = Op.getOperand(1);
5359 EVT VT = Op.getValueType();
5360 DebugLoc dl = Op.getDebugLoc();
5361 unsigned NumElems = VT.getVectorNumElements();
5362 bool isMMX = VT.getSizeInBits() == 64;
5363 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5364 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5365 bool V1IsSplat = false;
5366 bool V2IsSplat = false;
5367 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5368 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5369 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5370 MachineFunction &MF = DAG.getMachineFunction();
5371 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5373 // Shuffle operations on MMX not supported.
5377 // Vector shuffle lowering takes 3 steps:
5379 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5380 // narrowing and commutation of operands should be handled.
5381 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5383 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5384 // so the shuffle can be broken into other shuffles and the legalizer can
5385 // try the lowering again.
5387 // The general ideia is that no vector_shuffle operation should be left to
5388 // be matched during isel, all of them must be converted to a target specific
5391 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5392 // narrowing and commutation of operands should be handled. The actual code
5393 // doesn't include all of those, work in progress...
5394 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5395 if (NewOp.getNode())
5398 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5399 // unpckh_undef). Only use pshufd if speed is more important than size.
5400 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5401 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5402 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5403 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5404 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5405 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5407 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5408 RelaxedMayFoldVectorLoad(V1))
5409 return getMOVDDup(Op, dl, V1, DAG);
5411 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5412 return getMOVHighToLow(Op, dl, DAG);
5414 // Use to match splats
5415 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5416 (VT == MVT::v2f64 || VT == MVT::v2i64))
5417 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5419 if (X86::isPSHUFDMask(SVOp)) {
5420 // The actual implementation will match the mask in the if above and then
5421 // during isel it can match several different instructions, not only pshufd
5422 // as its name says, sad but true, emulate the behavior for now...
5423 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5424 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5426 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5428 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5429 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5431 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5432 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5435 if (VT == MVT::v4f32)
5436 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5440 // Check if this can be converted into a logical shift.
5441 bool isLeft = false;
5444 bool isShift = getSubtarget()->hasSSE2() &&
5445 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5446 if (isShift && ShVal.hasOneUse()) {
5447 // If the shifted value has multiple uses, it may be cheaper to use
5448 // v_set0 + movlhps or movhlps, etc.
5449 EVT EltVT = VT.getVectorElementType();
5450 ShAmt *= EltVT.getSizeInBits();
5451 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5454 if (X86::isMOVLMask(SVOp)) {
5457 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5458 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5459 if (!X86::isMOVLPMask(SVOp)) {
5460 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5461 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5463 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5464 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5468 // FIXME: fold these into legal mask.
5469 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5470 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5472 if (X86::isMOVHLPSMask(SVOp))
5473 return getMOVHighToLow(Op, dl, DAG);
5475 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5476 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5478 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5479 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5481 if (X86::isMOVLPMask(SVOp))
5482 return getMOVLP(Op, dl, DAG, HasSSE2);
5484 if (ShouldXformToMOVHLPS(SVOp) ||
5485 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5486 return CommuteVectorShuffle(SVOp, DAG);
5489 // No better options. Use a vshl / vsrl.
5490 EVT EltVT = VT.getVectorElementType();
5491 ShAmt *= EltVT.getSizeInBits();
5492 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5495 bool Commuted = false;
5496 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5497 // 1,1,1,1 -> v8i16 though.
5498 V1IsSplat = isSplatVector(V1.getNode());
5499 V2IsSplat = isSplatVector(V2.getNode());
5501 // Canonicalize the splat or undef, if present, to be on the RHS.
5502 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5503 Op = CommuteVectorShuffle(SVOp, DAG);
5504 SVOp = cast<ShuffleVectorSDNode>(Op);
5505 V1 = SVOp->getOperand(0);
5506 V2 = SVOp->getOperand(1);
5507 std::swap(V1IsSplat, V2IsSplat);
5508 std::swap(V1IsUndef, V2IsUndef);
5512 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5513 // Shuffling low element of v1 into undef, just return v1.
5516 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5517 // the instruction selector will not match, so get a canonical MOVL with
5518 // swapped operands to undo the commute.
5519 return getMOVL(DAG, dl, VT, V2, V1);
5522 if (X86::isUNPCKLMask(SVOp))
5523 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5525 if (X86::isUNPCKHMask(SVOp))
5526 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5529 // Normalize mask so all entries that point to V2 points to its first
5530 // element then try to match unpck{h|l} again. If match, return a
5531 // new vector_shuffle with the corrected mask.
5532 SDValue NewMask = NormalizeMask(SVOp, DAG);
5533 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5534 if (NSVOp != SVOp) {
5535 if (X86::isUNPCKLMask(NSVOp, true)) {
5537 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5544 // Commute is back and try unpck* again.
5545 // FIXME: this seems wrong.
5546 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5547 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5549 if (X86::isUNPCKLMask(NewSVOp))
5550 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5552 if (X86::isUNPCKHMask(NewSVOp))
5553 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5556 // Normalize the node to match x86 shuffle ops if needed
5557 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5558 return CommuteVectorShuffle(SVOp, DAG);
5560 // The checks below are all present in isShuffleMaskLegal, but they are
5561 // inlined here right now to enable us to directly emit target specific
5562 // nodes, and remove one by one until they don't return Op anymore.
5563 SmallVector<int, 16> M;
5566 if (isPALIGNRMask(M, VT, HasSSSE3))
5567 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5568 X86::getShufflePALIGNRImmediate(SVOp),
5571 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5572 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5573 if (VT == MVT::v2f64)
5574 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5575 if (VT == MVT::v2i64)
5576 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5579 if (isPSHUFHWMask(M, VT))
5580 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5581 X86::getShufflePSHUFHWImmediate(SVOp),
5584 if (isPSHUFLWMask(M, VT))
5585 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5586 X86::getShufflePSHUFLWImmediate(SVOp),
5589 if (isSHUFPMask(M, VT)) {
5590 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5591 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5592 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5594 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5595 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5599 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5600 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5601 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5602 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5603 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5604 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5606 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5607 if (VT == MVT::v8i16) {
5608 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5609 if (NewOp.getNode())
5613 if (VT == MVT::v16i8) {
5614 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5615 if (NewOp.getNode())
5619 // Handle all 4 wide cases with a number of shuffles.
5621 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5627 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5628 SelectionDAG &DAG) const {
5629 EVT VT = Op.getValueType();
5630 DebugLoc dl = Op.getDebugLoc();
5631 if (VT.getSizeInBits() == 8) {
5632 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5633 Op.getOperand(0), Op.getOperand(1));
5634 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5635 DAG.getValueType(VT));
5636 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5637 } else if (VT.getSizeInBits() == 16) {
5638 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5639 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5641 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5642 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5643 DAG.getNode(ISD::BIT_CONVERT, dl,
5647 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5648 Op.getOperand(0), Op.getOperand(1));
5649 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5650 DAG.getValueType(VT));
5651 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5652 } else if (VT == MVT::f32) {
5653 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5654 // the result back to FR32 register. It's only worth matching if the
5655 // result has a single use which is a store or a bitcast to i32. And in
5656 // the case of a store, it's not worth it if the index is a constant 0,
5657 // because a MOVSSmr can be used instead, which is smaller and faster.
5658 if (!Op.hasOneUse())
5660 SDNode *User = *Op.getNode()->use_begin();
5661 if ((User->getOpcode() != ISD::STORE ||
5662 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5663 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5664 (User->getOpcode() != ISD::BIT_CONVERT ||
5665 User->getValueType(0) != MVT::i32))
5667 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5668 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
5671 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
5672 } else if (VT == MVT::i32) {
5673 // ExtractPS works with constant index.
5674 if (isa<ConstantSDNode>(Op.getOperand(1)))
5682 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5683 SelectionDAG &DAG) const {
5684 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5687 if (Subtarget->hasSSE41()) {
5688 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5693 EVT VT = Op.getValueType();
5694 DebugLoc dl = Op.getDebugLoc();
5695 // TODO: handle v16i8.
5696 if (VT.getSizeInBits() == 16) {
5697 SDValue Vec = Op.getOperand(0);
5698 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5700 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5701 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5702 DAG.getNode(ISD::BIT_CONVERT, dl,
5705 // Transform it so it match pextrw which produces a 32-bit result.
5706 EVT EltVT = MVT::i32;
5707 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5708 Op.getOperand(0), Op.getOperand(1));
5709 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5710 DAG.getValueType(VT));
5711 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5712 } else if (VT.getSizeInBits() == 32) {
5713 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5717 // SHUFPS the element to the lowest double word, then movss.
5718 int Mask[4] = { Idx, -1, -1, -1 };
5719 EVT VVT = Op.getOperand(0).getValueType();
5720 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5721 DAG.getUNDEF(VVT), Mask);
5722 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5723 DAG.getIntPtrConstant(0));
5724 } else if (VT.getSizeInBits() == 64) {
5725 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5726 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5727 // to match extract_elt for f64.
5728 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5732 // UNPCKHPD the element to the lowest double word, then movsd.
5733 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5734 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5735 int Mask[2] = { 1, -1 };
5736 EVT VVT = Op.getOperand(0).getValueType();
5737 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5738 DAG.getUNDEF(VVT), Mask);
5739 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5740 DAG.getIntPtrConstant(0));
5747 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5748 SelectionDAG &DAG) const {
5749 EVT VT = Op.getValueType();
5750 EVT EltVT = VT.getVectorElementType();
5751 DebugLoc dl = Op.getDebugLoc();
5753 SDValue N0 = Op.getOperand(0);
5754 SDValue N1 = Op.getOperand(1);
5755 SDValue N2 = Op.getOperand(2);
5757 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5758 isa<ConstantSDNode>(N2)) {
5760 if (VT == MVT::v8i16)
5761 Opc = X86ISD::PINSRW;
5762 else if (VT == MVT::v16i8)
5763 Opc = X86ISD::PINSRB;
5765 Opc = X86ISD::PINSRB;
5767 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5769 if (N1.getValueType() != MVT::i32)
5770 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5771 if (N2.getValueType() != MVT::i32)
5772 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5773 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5774 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5775 // Bits [7:6] of the constant are the source select. This will always be
5776 // zero here. The DAG Combiner may combine an extract_elt index into these
5777 // bits. For example (insert (extract, 3), 2) could be matched by putting
5778 // the '3' into bits [7:6] of X86ISD::INSERTPS.
5779 // Bits [5:4] of the constant are the destination select. This is the
5780 // value of the incoming immediate.
5781 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
5782 // combine either bitwise AND or insert of float 0.0 to set these bits.
5783 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5784 // Create this as a scalar to vector..
5785 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5786 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5787 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5788 // PINSR* works with constant index.
5795 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5796 EVT VT = Op.getValueType();
5797 EVT EltVT = VT.getVectorElementType();
5799 if (Subtarget->hasSSE41())
5800 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5802 if (EltVT == MVT::i8)
5805 DebugLoc dl = Op.getDebugLoc();
5806 SDValue N0 = Op.getOperand(0);
5807 SDValue N1 = Op.getOperand(1);
5808 SDValue N2 = Op.getOperand(2);
5810 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5811 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5812 // as its second argument.
5813 if (N1.getValueType() != MVT::i32)
5814 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5815 if (N2.getValueType() != MVT::i32)
5816 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5817 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5823 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5824 DebugLoc dl = Op.getDebugLoc();
5826 if (Op.getValueType() == MVT::v1i64 &&
5827 Op.getOperand(0).getValueType() == MVT::i64)
5828 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5830 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5831 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5832 "Expected an SSE type!");
5833 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5834 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5837 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5838 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5839 // one of the above mentioned nodes. It has to be wrapped because otherwise
5840 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5841 // be used to form addressing mode. These wrapped nodes will be selected
5844 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5845 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5847 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5849 unsigned char OpFlag = 0;
5850 unsigned WrapperKind = X86ISD::Wrapper;
5851 CodeModel::Model M = getTargetMachine().getCodeModel();
5853 if (Subtarget->isPICStyleRIPRel() &&
5854 (M == CodeModel::Small || M == CodeModel::Kernel))
5855 WrapperKind = X86ISD::WrapperRIP;
5856 else if (Subtarget->isPICStyleGOT())
5857 OpFlag = X86II::MO_GOTOFF;
5858 else if (Subtarget->isPICStyleStubPIC())
5859 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5861 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5863 CP->getOffset(), OpFlag);
5864 DebugLoc DL = CP->getDebugLoc();
5865 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5866 // With PIC, the address is actually $g + Offset.
5868 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5869 DAG.getNode(X86ISD::GlobalBaseReg,
5870 DebugLoc(), getPointerTy()),
5877 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5878 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5880 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5882 unsigned char OpFlag = 0;
5883 unsigned WrapperKind = X86ISD::Wrapper;
5884 CodeModel::Model M = getTargetMachine().getCodeModel();
5886 if (Subtarget->isPICStyleRIPRel() &&
5887 (M == CodeModel::Small || M == CodeModel::Kernel))
5888 WrapperKind = X86ISD::WrapperRIP;
5889 else if (Subtarget->isPICStyleGOT())
5890 OpFlag = X86II::MO_GOTOFF;
5891 else if (Subtarget->isPICStyleStubPIC())
5892 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5894 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5896 DebugLoc DL = JT->getDebugLoc();
5897 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5899 // With PIC, the address is actually $g + Offset.
5901 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5902 DAG.getNode(X86ISD::GlobalBaseReg,
5903 DebugLoc(), getPointerTy()),
5911 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5912 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5914 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5916 unsigned char OpFlag = 0;
5917 unsigned WrapperKind = X86ISD::Wrapper;
5918 CodeModel::Model M = getTargetMachine().getCodeModel();
5920 if (Subtarget->isPICStyleRIPRel() &&
5921 (M == CodeModel::Small || M == CodeModel::Kernel))
5922 WrapperKind = X86ISD::WrapperRIP;
5923 else if (Subtarget->isPICStyleGOT())
5924 OpFlag = X86II::MO_GOTOFF;
5925 else if (Subtarget->isPICStyleStubPIC())
5926 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5928 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5930 DebugLoc DL = Op.getDebugLoc();
5931 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5934 // With PIC, the address is actually $g + Offset.
5935 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5936 !Subtarget->is64Bit()) {
5937 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5938 DAG.getNode(X86ISD::GlobalBaseReg,
5939 DebugLoc(), getPointerTy()),
5947 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5948 // Create the TargetBlockAddressAddress node.
5949 unsigned char OpFlags =
5950 Subtarget->ClassifyBlockAddressReference();
5951 CodeModel::Model M = getTargetMachine().getCodeModel();
5952 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5953 DebugLoc dl = Op.getDebugLoc();
5954 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5955 /*isTarget=*/true, OpFlags);
5957 if (Subtarget->isPICStyleRIPRel() &&
5958 (M == CodeModel::Small || M == CodeModel::Kernel))
5959 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5961 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5963 // With PIC, the address is actually $g + Offset.
5964 if (isGlobalRelativeToPICBase(OpFlags)) {
5965 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5966 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5974 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5976 SelectionDAG &DAG) const {
5977 // Create the TargetGlobalAddress node, folding in the constant
5978 // offset if it is legal.
5979 unsigned char OpFlags =
5980 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5981 CodeModel::Model M = getTargetMachine().getCodeModel();
5983 if (OpFlags == X86II::MO_NO_FLAG &&
5984 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5985 // A direct static reference to a global.
5986 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5989 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5992 if (Subtarget->isPICStyleRIPRel() &&
5993 (M == CodeModel::Small || M == CodeModel::Kernel))
5994 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5996 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5998 // With PIC, the address is actually $g + Offset.
5999 if (isGlobalRelativeToPICBase(OpFlags)) {
6000 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6001 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6005 // For globals that require a load from a stub to get the address, emit the
6007 if (isGlobalStubReference(OpFlags))
6008 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6009 MachinePointerInfo::getGOT(), false, false, 0);
6011 // If there was a non-zero offset that we didn't fold, create an explicit
6014 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6015 DAG.getConstant(Offset, getPointerTy()));
6021 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6022 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6023 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6024 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6028 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6029 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6030 unsigned char OperandFlags) {
6031 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6032 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6033 DebugLoc dl = GA->getDebugLoc();
6034 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6035 GA->getValueType(0),
6039 SDValue Ops[] = { Chain, TGA, *InFlag };
6040 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6042 SDValue Ops[] = { Chain, TGA };
6043 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6046 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6047 MFI->setAdjustsStack(true);
6049 SDValue Flag = Chain.getValue(1);
6050 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6053 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6055 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6058 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6059 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6060 DAG.getNode(X86ISD::GlobalBaseReg,
6061 DebugLoc(), PtrVT), InFlag);
6062 InFlag = Chain.getValue(1);
6064 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6067 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6069 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6071 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6072 X86::RAX, X86II::MO_TLSGD);
6075 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6076 // "local exec" model.
6077 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6078 const EVT PtrVT, TLSModel::Model model,
6080 DebugLoc dl = GA->getDebugLoc();
6082 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6083 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6084 is64Bit ? 257 : 256));
6086 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6087 DAG.getIntPtrConstant(0),
6088 MachinePointerInfo(Ptr), false, false, 0);
6090 unsigned char OperandFlags = 0;
6091 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6093 unsigned WrapperKind = X86ISD::Wrapper;
6094 if (model == TLSModel::LocalExec) {
6095 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6096 } else if (is64Bit) {
6097 assert(model == TLSModel::InitialExec);
6098 OperandFlags = X86II::MO_GOTTPOFF;
6099 WrapperKind = X86ISD::WrapperRIP;
6101 assert(model == TLSModel::InitialExec);
6102 OperandFlags = X86II::MO_INDNTPOFF;
6105 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6107 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6108 GA->getValueType(0),
6109 GA->getOffset(), OperandFlags);
6110 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6112 if (model == TLSModel::InitialExec)
6113 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6114 MachinePointerInfo::getGOT(), false, false, 0);
6116 // The address of the thread local variable is the add of the thread
6117 // pointer with the offset of the variable.
6118 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6122 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6124 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6125 const GlobalValue *GV = GA->getGlobal();
6127 if (Subtarget->isTargetELF()) {
6128 // TODO: implement the "local dynamic" model
6129 // TODO: implement the "initial exec"model for pic executables
6131 // If GV is an alias then use the aliasee for determining
6132 // thread-localness.
6133 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6134 GV = GA->resolveAliasedGlobal(false);
6136 TLSModel::Model model
6137 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6140 case TLSModel::GeneralDynamic:
6141 case TLSModel::LocalDynamic: // not implemented
6142 if (Subtarget->is64Bit())
6143 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6144 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6146 case TLSModel::InitialExec:
6147 case TLSModel::LocalExec:
6148 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6149 Subtarget->is64Bit());
6151 } else if (Subtarget->isTargetDarwin()) {
6152 // Darwin only has one model of TLS. Lower to that.
6153 unsigned char OpFlag = 0;
6154 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6155 X86ISD::WrapperRIP : X86ISD::Wrapper;
6157 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6159 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6160 !Subtarget->is64Bit();
6162 OpFlag = X86II::MO_TLVP_PIC_BASE;
6164 OpFlag = X86II::MO_TLVP;
6165 DebugLoc DL = Op.getDebugLoc();
6166 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6168 GA->getOffset(), OpFlag);
6169 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6171 // With PIC32, the address is actually $g + Offset.
6173 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6174 DAG.getNode(X86ISD::GlobalBaseReg,
6175 DebugLoc(), getPointerTy()),
6178 // Lowering the machine isd will make sure everything is in the right
6180 SDValue Args[] = { Offset };
6181 SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
6183 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6184 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6185 MFI->setAdjustsStack(true);
6187 // And our return value (tls address) is in the standard call return value
6189 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6190 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6194 "TLS not implemented for this target.");
6196 llvm_unreachable("Unreachable");
6201 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6202 /// take a 2 x i32 value to shift plus a shift amount.
6203 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6204 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6205 EVT VT = Op.getValueType();
6206 unsigned VTBits = VT.getSizeInBits();
6207 DebugLoc dl = Op.getDebugLoc();
6208 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6209 SDValue ShOpLo = Op.getOperand(0);
6210 SDValue ShOpHi = Op.getOperand(1);
6211 SDValue ShAmt = Op.getOperand(2);
6212 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6213 DAG.getConstant(VTBits - 1, MVT::i8))
6214 : DAG.getConstant(0, VT);
6217 if (Op.getOpcode() == ISD::SHL_PARTS) {
6218 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6219 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6221 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6222 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6225 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6226 DAG.getConstant(VTBits, MVT::i8));
6227 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6228 AndNode, DAG.getConstant(0, MVT::i8));
6231 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6232 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6233 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6235 if (Op.getOpcode() == ISD::SHL_PARTS) {
6236 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6237 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6239 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6240 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6243 SDValue Ops[2] = { Lo, Hi };
6244 return DAG.getMergeValues(Ops, 2, dl);
6247 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6248 SelectionDAG &DAG) const {
6249 EVT SrcVT = Op.getOperand(0).getValueType();
6251 if (SrcVT.isVector())
6254 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6255 "Unknown SINT_TO_FP to lower!");
6257 // These are really Legal; return the operand so the caller accepts it as
6259 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6261 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6262 Subtarget->is64Bit()) {
6266 DebugLoc dl = Op.getDebugLoc();
6267 unsigned Size = SrcVT.getSizeInBits()/8;
6268 MachineFunction &MF = DAG.getMachineFunction();
6269 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6270 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6271 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6273 MachinePointerInfo::getFixedStack(SSFI),
6275 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6278 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6280 SelectionDAG &DAG) const {
6282 DebugLoc DL = Op.getDebugLoc();
6284 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6286 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6288 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6290 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6292 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6293 MachineMemOperand *MMO =
6294 DAG.getMachineFunction()
6295 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6296 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6298 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6299 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6301 Tys, Ops, array_lengthof(Ops),
6305 Chain = Result.getValue(1);
6306 SDValue InFlag = Result.getValue(2);
6308 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6309 // shouldn't be necessary except that RFP cannot be live across
6310 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6311 MachineFunction &MF = DAG.getMachineFunction();
6312 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6313 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6314 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6315 Tys = DAG.getVTList(MVT::Other);
6317 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6319 MachineMemOperand *MMO =
6320 DAG.getMachineFunction()
6321 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6322 MachineMemOperand::MOStore, SSFISize, SSFISize);
6324 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6325 Ops, array_lengthof(Ops),
6326 Op.getValueType(), MMO);
6327 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6328 MachinePointerInfo::getFixedStack(SSFI),
6335 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6336 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6337 SelectionDAG &DAG) const {
6338 // This algorithm is not obvious. Here it is in C code, more or less:
6340 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6341 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6342 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6344 // Copy ints to xmm registers.
6345 __m128i xh = _mm_cvtsi32_si128( hi );
6346 __m128i xl = _mm_cvtsi32_si128( lo );
6348 // Combine into low half of a single xmm register.
6349 __m128i x = _mm_unpacklo_epi32( xh, xl );
6353 // Merge in appropriate exponents to give the integer bits the right
6355 x = _mm_unpacklo_epi32( x, exp );
6357 // Subtract away the biases to deal with the IEEE-754 double precision
6359 d = _mm_sub_pd( (__m128d) x, bias );
6361 // All conversions up to here are exact. The correctly rounded result is
6362 // calculated using the current rounding mode using the following
6364 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6365 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6366 // store doesn't really need to be here (except
6367 // maybe to zero the other double)
6372 DebugLoc dl = Op.getDebugLoc();
6373 LLVMContext *Context = DAG.getContext();
6375 // Build some magic constants.
6376 std::vector<Constant*> CV0;
6377 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6378 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6379 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6380 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6381 Constant *C0 = ConstantVector::get(CV0);
6382 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6384 std::vector<Constant*> CV1;
6386 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6388 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6389 Constant *C1 = ConstantVector::get(CV1);
6390 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6392 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6393 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6395 DAG.getIntPtrConstant(1)));
6396 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6397 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6399 DAG.getIntPtrConstant(0)));
6400 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6401 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6402 MachinePointerInfo::getConstantPool(),
6404 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6405 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
6406 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6407 MachinePointerInfo::getConstantPool(),
6409 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6411 // Add the halves; easiest way is to swap them into another reg first.
6412 int ShufMask[2] = { 1, -1 };
6413 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6414 DAG.getUNDEF(MVT::v2f64), ShufMask);
6415 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6416 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6417 DAG.getIntPtrConstant(0));
6420 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6421 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6422 SelectionDAG &DAG) const {
6423 DebugLoc dl = Op.getDebugLoc();
6424 // FP constant to bias correct the final result.
6425 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6428 // Load the 32-bit value into an XMM register.
6429 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6430 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6432 DAG.getIntPtrConstant(0)));
6434 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6435 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
6436 DAG.getIntPtrConstant(0));
6438 // Or the load with the bias.
6439 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6440 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6441 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6443 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6444 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6445 MVT::v2f64, Bias)));
6446 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6447 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
6448 DAG.getIntPtrConstant(0));
6450 // Subtract the bias.
6451 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6453 // Handle final rounding.
6454 EVT DestVT = Op.getValueType();
6456 if (DestVT.bitsLT(MVT::f64)) {
6457 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6458 DAG.getIntPtrConstant(0));
6459 } else if (DestVT.bitsGT(MVT::f64)) {
6460 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6463 // Handle final rounding.
6467 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6468 SelectionDAG &DAG) const {
6469 SDValue N0 = Op.getOperand(0);
6470 DebugLoc dl = Op.getDebugLoc();
6472 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6473 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6474 // the optimization here.
6475 if (DAG.SignBitIsZero(N0))
6476 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6478 EVT SrcVT = N0.getValueType();
6479 EVT DstVT = Op.getValueType();
6480 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6481 return LowerUINT_TO_FP_i64(Op, DAG);
6482 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6483 return LowerUINT_TO_FP_i32(Op, DAG);
6485 // Make a 64-bit buffer, and use it to build an FILD.
6486 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6487 if (SrcVT == MVT::i32) {
6488 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6489 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6490 getPointerTy(), StackSlot, WordOff);
6491 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6492 StackSlot, MachinePointerInfo(),
6494 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6495 OffsetSlot, MachinePointerInfo(),
6497 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6501 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6502 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6503 StackSlot, MachinePointerInfo(),
6505 // For i64 source, we need to add the appropriate power of 2 if the input
6506 // was negative. This is the same as the optimization in
6507 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6508 // we must be careful to do the computation in x87 extended precision, not
6509 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6510 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6511 MachineMemOperand *MMO =
6512 DAG.getMachineFunction()
6513 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6514 MachineMemOperand::MOLoad, 8, 8);
6516 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6517 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6518 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6521 APInt FF(32, 0x5F800000ULL);
6523 // Check whether the sign bit is set.
6524 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6525 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6528 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6529 SDValue FudgePtr = DAG.getConstantPool(
6530 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6533 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6534 SDValue Zero = DAG.getIntPtrConstant(0);
6535 SDValue Four = DAG.getIntPtrConstant(4);
6536 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6538 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6540 // Load the value out, extending it from f32 to f80.
6541 // FIXME: Avoid the extend by constructing the right constant pool?
6542 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6543 FudgePtr, MachinePointerInfo::getConstantPool(),
6544 MVT::f32, false, false, 4);
6545 // Extend everything to 80 bits to force it to be done on x87.
6546 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6547 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6550 std::pair<SDValue,SDValue> X86TargetLowering::
6551 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6552 DebugLoc DL = Op.getDebugLoc();
6554 EVT DstTy = Op.getValueType();
6557 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6561 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6562 DstTy.getSimpleVT() >= MVT::i16 &&
6563 "Unknown FP_TO_SINT to lower!");
6565 // These are really Legal.
6566 if (DstTy == MVT::i32 &&
6567 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6568 return std::make_pair(SDValue(), SDValue());
6569 if (Subtarget->is64Bit() &&
6570 DstTy == MVT::i64 &&
6571 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6572 return std::make_pair(SDValue(), SDValue());
6574 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6576 MachineFunction &MF = DAG.getMachineFunction();
6577 unsigned MemSize = DstTy.getSizeInBits()/8;
6578 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6579 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6584 switch (DstTy.getSimpleVT().SimpleTy) {
6585 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6586 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6587 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6588 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6591 SDValue Chain = DAG.getEntryNode();
6592 SDValue Value = Op.getOperand(0);
6593 EVT TheVT = Op.getOperand(0).getValueType();
6594 if (isScalarFPTypeInSSEReg(TheVT)) {
6595 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6596 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6597 MachinePointerInfo::getFixedStack(SSFI),
6599 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6601 Chain, StackSlot, DAG.getValueType(TheVT)
6604 MachineMemOperand *MMO =
6605 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6606 MachineMemOperand::MOLoad, MemSize, MemSize);
6607 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6609 Chain = Value.getValue(1);
6610 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6611 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6614 MachineMemOperand *MMO =
6615 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6616 MachineMemOperand::MOStore, MemSize, MemSize);
6618 // Build the FP_TO_INT*_IN_MEM
6619 SDValue Ops[] = { Chain, Value, StackSlot };
6620 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6621 Ops, 3, DstTy, MMO);
6623 return std::make_pair(FIST, StackSlot);
6626 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6627 SelectionDAG &DAG) const {
6628 if (Op.getValueType().isVector())
6631 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6632 SDValue FIST = Vals.first, StackSlot = Vals.second;
6633 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6634 if (FIST.getNode() == 0) return Op;
6637 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6638 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6641 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6642 SelectionDAG &DAG) const {
6643 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6644 SDValue FIST = Vals.first, StackSlot = Vals.second;
6645 assert(FIST.getNode() && "Unexpected failure");
6648 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6649 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6652 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6653 SelectionDAG &DAG) const {
6654 LLVMContext *Context = DAG.getContext();
6655 DebugLoc dl = Op.getDebugLoc();
6656 EVT VT = Op.getValueType();
6659 EltVT = VT.getVectorElementType();
6660 std::vector<Constant*> CV;
6661 if (EltVT == MVT::f64) {
6662 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6666 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6672 Constant *C = ConstantVector::get(CV);
6673 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6674 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6675 MachinePointerInfo::getConstantPool(),
6677 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6680 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6681 LLVMContext *Context = DAG.getContext();
6682 DebugLoc dl = Op.getDebugLoc();
6683 EVT VT = Op.getValueType();
6686 EltVT = VT.getVectorElementType();
6687 std::vector<Constant*> CV;
6688 if (EltVT == MVT::f64) {
6689 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6693 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6699 Constant *C = ConstantVector::get(CV);
6700 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6701 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6702 MachinePointerInfo::getConstantPool(),
6704 if (VT.isVector()) {
6705 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6706 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6707 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6709 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
6711 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6715 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6716 LLVMContext *Context = DAG.getContext();
6717 SDValue Op0 = Op.getOperand(0);
6718 SDValue Op1 = Op.getOperand(1);
6719 DebugLoc dl = Op.getDebugLoc();
6720 EVT VT = Op.getValueType();
6721 EVT SrcVT = Op1.getValueType();
6723 // If second operand is smaller, extend it first.
6724 if (SrcVT.bitsLT(VT)) {
6725 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6728 // And if it is bigger, shrink it first.
6729 if (SrcVT.bitsGT(VT)) {
6730 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6734 // At this point the operands and the result should have the same
6735 // type, and that won't be f80 since that is not custom lowered.
6737 // First get the sign bit of second operand.
6738 std::vector<Constant*> CV;
6739 if (SrcVT == MVT::f64) {
6740 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6741 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6743 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6744 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6745 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6746 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6748 Constant *C = ConstantVector::get(CV);
6749 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6750 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6751 MachinePointerInfo::getConstantPool(),
6753 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6755 // Shift sign bit right or left if the two operands have different types.
6756 if (SrcVT.bitsGT(VT)) {
6757 // Op0 is MVT::f32, Op1 is MVT::f64.
6758 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6759 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6760 DAG.getConstant(32, MVT::i32));
6761 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
6762 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6763 DAG.getIntPtrConstant(0));
6766 // Clear first operand sign bit.
6768 if (VT == MVT::f64) {
6769 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6770 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6772 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6773 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6774 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6775 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6777 C = ConstantVector::get(CV);
6778 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6779 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6780 MachinePointerInfo::getConstantPool(),
6782 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6784 // Or the value with the sign bit.
6785 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6788 /// Emit nodes that will be selected as "test Op0,Op0", or something
6790 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6791 SelectionDAG &DAG) const {
6792 DebugLoc dl = Op.getDebugLoc();
6794 // CF and OF aren't always set the way we want. Determine which
6795 // of these we need.
6796 bool NeedCF = false;
6797 bool NeedOF = false;
6800 case X86::COND_A: case X86::COND_AE:
6801 case X86::COND_B: case X86::COND_BE:
6804 case X86::COND_G: case X86::COND_GE:
6805 case X86::COND_L: case X86::COND_LE:
6806 case X86::COND_O: case X86::COND_NO:
6811 // See if we can use the EFLAGS value from the operand instead of
6812 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6813 // we prove that the arithmetic won't overflow, we can't use OF or CF.
6814 if (Op.getResNo() != 0 || NeedOF || NeedCF)
6815 // Emit a CMP with 0, which is the TEST pattern.
6816 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6817 DAG.getConstant(0, Op.getValueType()));
6819 unsigned Opcode = 0;
6820 unsigned NumOperands = 0;
6821 switch (Op.getNode()->getOpcode()) {
6823 // Due to an isel shortcoming, be conservative if this add is likely to be
6824 // selected as part of a load-modify-store instruction. When the root node
6825 // in a match is a store, isel doesn't know how to remap non-chain non-flag
6826 // uses of other nodes in the match, such as the ADD in this case. This
6827 // leads to the ADD being left around and reselected, with the result being
6828 // two adds in the output. Alas, even if none our users are stores, that
6829 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
6830 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
6831 // climbing the DAG back to the root, and it doesn't seem to be worth the
6833 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6834 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6835 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6838 if (ConstantSDNode *C =
6839 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6840 // An add of one will be selected as an INC.
6841 if (C->getAPIntValue() == 1) {
6842 Opcode = X86ISD::INC;
6847 // An add of negative one (subtract of one) will be selected as a DEC.
6848 if (C->getAPIntValue().isAllOnesValue()) {
6849 Opcode = X86ISD::DEC;
6855 // Otherwise use a regular EFLAGS-setting add.
6856 Opcode = X86ISD::ADD;
6860 // If the primary and result isn't used, don't bother using X86ISD::AND,
6861 // because a TEST instruction will be better.
6862 bool NonFlagUse = false;
6863 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6864 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6866 unsigned UOpNo = UI.getOperandNo();
6867 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6868 // Look pass truncate.
6869 UOpNo = User->use_begin().getOperandNo();
6870 User = *User->use_begin();
6873 if (User->getOpcode() != ISD::BRCOND &&
6874 User->getOpcode() != ISD::SETCC &&
6875 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6888 // Due to the ISEL shortcoming noted above, be conservative if this op is
6889 // likely to be selected as part of a load-modify-store instruction.
6890 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6891 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6892 if (UI->getOpcode() == ISD::STORE)
6895 // Otherwise use a regular EFLAGS-setting instruction.
6896 switch (Op.getNode()->getOpcode()) {
6897 default: llvm_unreachable("unexpected operator!");
6898 case ISD::SUB: Opcode = X86ISD::SUB; break;
6899 case ISD::OR: Opcode = X86ISD::OR; break;
6900 case ISD::XOR: Opcode = X86ISD::XOR; break;
6901 case ISD::AND: Opcode = X86ISD::AND; break;
6913 return SDValue(Op.getNode(), 1);
6920 // Emit a CMP with 0, which is the TEST pattern.
6921 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6922 DAG.getConstant(0, Op.getValueType()));
6924 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6925 SmallVector<SDValue, 4> Ops;
6926 for (unsigned i = 0; i != NumOperands; ++i)
6927 Ops.push_back(Op.getOperand(i));
6929 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6930 DAG.ReplaceAllUsesWith(Op, New);
6931 return SDValue(New.getNode(), 1);
6934 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6936 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6937 SelectionDAG &DAG) const {
6938 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6939 if (C->getAPIntValue() == 0)
6940 return EmitTest(Op0, X86CC, DAG);
6942 DebugLoc dl = Op0.getDebugLoc();
6943 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6946 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6947 /// if it's possible.
6948 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6949 DebugLoc dl, SelectionDAG &DAG) const {
6950 SDValue Op0 = And.getOperand(0);
6951 SDValue Op1 = And.getOperand(1);
6952 if (Op0.getOpcode() == ISD::TRUNCATE)
6953 Op0 = Op0.getOperand(0);
6954 if (Op1.getOpcode() == ISD::TRUNCATE)
6955 Op1 = Op1.getOperand(0);
6958 if (Op1.getOpcode() == ISD::SHL)
6959 std::swap(Op0, Op1);
6960 if (Op0.getOpcode() == ISD::SHL) {
6961 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6962 if (And00C->getZExtValue() == 1) {
6963 // If we looked past a truncate, check that it's only truncating away
6965 unsigned BitWidth = Op0.getValueSizeInBits();
6966 unsigned AndBitWidth = And.getValueSizeInBits();
6967 if (BitWidth > AndBitWidth) {
6968 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6969 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6970 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6974 RHS = Op0.getOperand(1);
6976 } else if (Op1.getOpcode() == ISD::Constant) {
6977 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6978 SDValue AndLHS = Op0;
6979 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6980 LHS = AndLHS.getOperand(0);
6981 RHS = AndLHS.getOperand(1);
6985 if (LHS.getNode()) {
6986 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
6987 // instruction. Since the shift amount is in-range-or-undefined, we know
6988 // that doing a bittest on the i32 value is ok. We extend to i32 because
6989 // the encoding for the i16 version is larger than the i32 version.
6990 // Also promote i16 to i32 for performance / code size reason.
6991 if (LHS.getValueType() == MVT::i8 ||
6992 LHS.getValueType() == MVT::i16)
6993 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6995 // If the operand types disagree, extend the shift amount to match. Since
6996 // BT ignores high bits (like shifts) we can use anyextend.
6997 if (LHS.getValueType() != RHS.getValueType())
6998 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7000 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7001 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7002 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7003 DAG.getConstant(Cond, MVT::i8), BT);
7009 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7010 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7011 SDValue Op0 = Op.getOperand(0);
7012 SDValue Op1 = Op.getOperand(1);
7013 DebugLoc dl = Op.getDebugLoc();
7014 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7016 // Optimize to BT if possible.
7017 // Lower (X & (1 << N)) == 0 to BT(X, N).
7018 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7019 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7020 if (Op0.getOpcode() == ISD::AND &&
7022 Op1.getOpcode() == ISD::Constant &&
7023 cast<ConstantSDNode>(Op1)->isNullValue() &&
7024 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7025 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7026 if (NewSetCC.getNode())
7030 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
7031 if (Op0.getOpcode() == X86ISD::SETCC &&
7032 Op1.getOpcode() == ISD::Constant &&
7033 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7034 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7035 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7036 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7037 bool Invert = (CC == ISD::SETNE) ^
7038 cast<ConstantSDNode>(Op1)->isNullValue();
7040 CCode = X86::GetOppositeBranchCondition(CCode);
7041 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7042 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7045 bool isFP = Op1.getValueType().isFloatingPoint();
7046 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7047 if (X86CC == X86::COND_INVALID)
7050 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7052 // Use sbb x, x to materialize carry bit into a GPR.
7053 if (X86CC == X86::COND_B)
7054 return DAG.getNode(ISD::AND, dl, MVT::i8,
7055 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7056 DAG.getConstant(X86CC, MVT::i8), Cond),
7057 DAG.getConstant(1, MVT::i8));
7059 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7060 DAG.getConstant(X86CC, MVT::i8), Cond);
7063 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7065 SDValue Op0 = Op.getOperand(0);
7066 SDValue Op1 = Op.getOperand(1);
7067 SDValue CC = Op.getOperand(2);
7068 EVT VT = Op.getValueType();
7069 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7070 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7071 DebugLoc dl = Op.getDebugLoc();
7075 EVT VT0 = Op0.getValueType();
7076 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7077 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7080 switch (SetCCOpcode) {
7083 case ISD::SETEQ: SSECC = 0; break;
7085 case ISD::SETGT: Swap = true; // Fallthrough
7087 case ISD::SETOLT: SSECC = 1; break;
7089 case ISD::SETGE: Swap = true; // Fallthrough
7091 case ISD::SETOLE: SSECC = 2; break;
7092 case ISD::SETUO: SSECC = 3; break;
7094 case ISD::SETNE: SSECC = 4; break;
7095 case ISD::SETULE: Swap = true;
7096 case ISD::SETUGE: SSECC = 5; break;
7097 case ISD::SETULT: Swap = true;
7098 case ISD::SETUGT: SSECC = 6; break;
7099 case ISD::SETO: SSECC = 7; break;
7102 std::swap(Op0, Op1);
7104 // In the two special cases we can't handle, emit two comparisons.
7106 if (SetCCOpcode == ISD::SETUEQ) {
7108 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7109 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7110 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7112 else if (SetCCOpcode == ISD::SETONE) {
7114 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7115 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7116 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7118 llvm_unreachable("Illegal FP comparison");
7120 // Handle all other FP comparisons here.
7121 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7124 // We are handling one of the integer comparisons here. Since SSE only has
7125 // GT and EQ comparisons for integer, swapping operands and multiple
7126 // operations may be required for some comparisons.
7127 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7128 bool Swap = false, Invert = false, FlipSigns = false;
7130 switch (VT.getSimpleVT().SimpleTy) {
7132 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7133 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7134 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7135 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7138 switch (SetCCOpcode) {
7140 case ISD::SETNE: Invert = true;
7141 case ISD::SETEQ: Opc = EQOpc; break;
7142 case ISD::SETLT: Swap = true;
7143 case ISD::SETGT: Opc = GTOpc; break;
7144 case ISD::SETGE: Swap = true;
7145 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7146 case ISD::SETULT: Swap = true;
7147 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7148 case ISD::SETUGE: Swap = true;
7149 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7152 std::swap(Op0, Op1);
7154 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7155 // bits of the inputs before performing those operations.
7157 EVT EltVT = VT.getVectorElementType();
7158 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7160 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7161 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7163 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7164 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7167 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7169 // If the logical-not of the result is required, perform that now.
7171 Result = DAG.getNOT(dl, Result, VT);
7176 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7177 static bool isX86LogicalCmp(SDValue Op) {
7178 unsigned Opc = Op.getNode()->getOpcode();
7179 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7181 if (Op.getResNo() == 1 &&
7182 (Opc == X86ISD::ADD ||
7183 Opc == X86ISD::SUB ||
7184 Opc == X86ISD::SMUL ||
7185 Opc == X86ISD::UMUL ||
7186 Opc == X86ISD::INC ||
7187 Opc == X86ISD::DEC ||
7188 Opc == X86ISD::OR ||
7189 Opc == X86ISD::XOR ||
7190 Opc == X86ISD::AND))
7196 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7197 bool addTest = true;
7198 SDValue Cond = Op.getOperand(0);
7199 DebugLoc dl = Op.getDebugLoc();
7202 if (Cond.getOpcode() == ISD::SETCC) {
7203 SDValue NewCond = LowerSETCC(Cond, DAG);
7204 if (NewCond.getNode())
7208 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
7209 SDValue Op1 = Op.getOperand(1);
7210 SDValue Op2 = Op.getOperand(2);
7211 if (Cond.getOpcode() == X86ISD::SETCC &&
7212 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
7213 SDValue Cmp = Cond.getOperand(1);
7214 if (Cmp.getOpcode() == X86ISD::CMP) {
7215 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
7216 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7217 ConstantSDNode *RHSC =
7218 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
7219 if (N1C && N1C->isAllOnesValue() &&
7220 N2C && N2C->isNullValue() &&
7221 RHSC && RHSC->isNullValue()) {
7222 SDValue CmpOp0 = Cmp.getOperand(0);
7223 Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7224 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7225 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
7226 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7231 // Look pass (and (setcc_carry (cmp ...)), 1).
7232 if (Cond.getOpcode() == ISD::AND &&
7233 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7234 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7235 if (C && C->getAPIntValue() == 1)
7236 Cond = Cond.getOperand(0);
7239 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7240 // setting operand in place of the X86ISD::SETCC.
7241 if (Cond.getOpcode() == X86ISD::SETCC ||
7242 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7243 CC = Cond.getOperand(0);
7245 SDValue Cmp = Cond.getOperand(1);
7246 unsigned Opc = Cmp.getOpcode();
7247 EVT VT = Op.getValueType();
7249 bool IllegalFPCMov = false;
7250 if (VT.isFloatingPoint() && !VT.isVector() &&
7251 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7252 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7254 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7255 Opc == X86ISD::BT) { // FIXME
7262 // Look pass the truncate.
7263 if (Cond.getOpcode() == ISD::TRUNCATE)
7264 Cond = Cond.getOperand(0);
7266 // We know the result of AND is compared against zero. Try to match
7268 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7269 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7270 if (NewSetCC.getNode()) {
7271 CC = NewSetCC.getOperand(0);
7272 Cond = NewSetCC.getOperand(1);
7279 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7280 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7283 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7284 // condition is true.
7285 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7286 SDValue Ops[] = { Op2, Op1, CC, Cond };
7287 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
7290 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7291 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7292 // from the AND / OR.
7293 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7294 Opc = Op.getOpcode();
7295 if (Opc != ISD::OR && Opc != ISD::AND)
7297 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7298 Op.getOperand(0).hasOneUse() &&
7299 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7300 Op.getOperand(1).hasOneUse());
7303 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7304 // 1 and that the SETCC node has a single use.
7305 static bool isXor1OfSetCC(SDValue Op) {
7306 if (Op.getOpcode() != ISD::XOR)
7308 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7309 if (N1C && N1C->getAPIntValue() == 1) {
7310 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7311 Op.getOperand(0).hasOneUse();
7316 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7317 bool addTest = true;
7318 SDValue Chain = Op.getOperand(0);
7319 SDValue Cond = Op.getOperand(1);
7320 SDValue Dest = Op.getOperand(2);
7321 DebugLoc dl = Op.getDebugLoc();
7324 if (Cond.getOpcode() == ISD::SETCC) {
7325 SDValue NewCond = LowerSETCC(Cond, DAG);
7326 if (NewCond.getNode())
7330 // FIXME: LowerXALUO doesn't handle these!!
7331 else if (Cond.getOpcode() == X86ISD::ADD ||
7332 Cond.getOpcode() == X86ISD::SUB ||
7333 Cond.getOpcode() == X86ISD::SMUL ||
7334 Cond.getOpcode() == X86ISD::UMUL)
7335 Cond = LowerXALUO(Cond, DAG);
7338 // Look pass (and (setcc_carry (cmp ...)), 1).
7339 if (Cond.getOpcode() == ISD::AND &&
7340 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7341 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7342 if (C && C->getAPIntValue() == 1)
7343 Cond = Cond.getOperand(0);
7346 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7347 // setting operand in place of the X86ISD::SETCC.
7348 if (Cond.getOpcode() == X86ISD::SETCC ||
7349 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7350 CC = Cond.getOperand(0);
7352 SDValue Cmp = Cond.getOperand(1);
7353 unsigned Opc = Cmp.getOpcode();
7354 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7355 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7359 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7363 // These can only come from an arithmetic instruction with overflow,
7364 // e.g. SADDO, UADDO.
7365 Cond = Cond.getNode()->getOperand(1);
7372 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7373 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7374 if (CondOpc == ISD::OR) {
7375 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7376 // two branches instead of an explicit OR instruction with a
7378 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7379 isX86LogicalCmp(Cmp)) {
7380 CC = Cond.getOperand(0).getOperand(0);
7381 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7382 Chain, Dest, CC, Cmp);
7383 CC = Cond.getOperand(1).getOperand(0);
7387 } else { // ISD::AND
7388 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7389 // two branches instead of an explicit AND instruction with a
7390 // separate test. However, we only do this if this block doesn't
7391 // have a fall-through edge, because this requires an explicit
7392 // jmp when the condition is false.
7393 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7394 isX86LogicalCmp(Cmp) &&
7395 Op.getNode()->hasOneUse()) {
7396 X86::CondCode CCode =
7397 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7398 CCode = X86::GetOppositeBranchCondition(CCode);
7399 CC = DAG.getConstant(CCode, MVT::i8);
7400 SDNode *User = *Op.getNode()->use_begin();
7401 // Look for an unconditional branch following this conditional branch.
7402 // We need this because we need to reverse the successors in order
7403 // to implement FCMP_OEQ.
7404 if (User->getOpcode() == ISD::BR) {
7405 SDValue FalseBB = User->getOperand(1);
7407 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7408 assert(NewBR == User);
7412 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7413 Chain, Dest, CC, Cmp);
7414 X86::CondCode CCode =
7415 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7416 CCode = X86::GetOppositeBranchCondition(CCode);
7417 CC = DAG.getConstant(CCode, MVT::i8);
7423 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7424 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7425 // It should be transformed during dag combiner except when the condition
7426 // is set by a arithmetics with overflow node.
7427 X86::CondCode CCode =
7428 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7429 CCode = X86::GetOppositeBranchCondition(CCode);
7430 CC = DAG.getConstant(CCode, MVT::i8);
7431 Cond = Cond.getOperand(0).getOperand(1);
7437 // Look pass the truncate.
7438 if (Cond.getOpcode() == ISD::TRUNCATE)
7439 Cond = Cond.getOperand(0);
7441 // We know the result of AND is compared against zero. Try to match
7443 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7444 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7445 if (NewSetCC.getNode()) {
7446 CC = NewSetCC.getOperand(0);
7447 Cond = NewSetCC.getOperand(1);
7454 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7455 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7457 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7458 Chain, Dest, CC, Cond);
7462 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7463 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7464 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7465 // that the guard pages used by the OS virtual memory manager are allocated in
7466 // correct sequence.
7468 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7469 SelectionDAG &DAG) const {
7470 assert(Subtarget->isTargetCygMing() &&
7471 "This should be used only on Cygwin/Mingw targets");
7472 DebugLoc dl = Op.getDebugLoc();
7475 SDValue Chain = Op.getOperand(0);
7476 SDValue Size = Op.getOperand(1);
7477 // FIXME: Ensure alignment here
7481 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7483 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7484 Flag = Chain.getValue(1);
7486 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7488 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
7489 Flag = Chain.getValue(1);
7491 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7493 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7494 return DAG.getMergeValues(Ops1, 2, dl);
7497 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7498 MachineFunction &MF = DAG.getMachineFunction();
7499 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7501 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7502 DebugLoc DL = Op.getDebugLoc();
7504 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7505 // vastart just stores the address of the VarArgsFrameIndex slot into the
7506 // memory location argument.
7507 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7509 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7510 MachinePointerInfo(SV), false, false, 0);
7514 // gp_offset (0 - 6 * 8)
7515 // fp_offset (48 - 48 + 8 * 16)
7516 // overflow_arg_area (point to parameters coming in memory).
7518 SmallVector<SDValue, 8> MemOps;
7519 SDValue FIN = Op.getOperand(1);
7521 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7522 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7524 FIN, MachinePointerInfo(SV), false, false, 0);
7525 MemOps.push_back(Store);
7528 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7529 FIN, DAG.getIntPtrConstant(4));
7530 Store = DAG.getStore(Op.getOperand(0), DL,
7531 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7533 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7534 MemOps.push_back(Store);
7536 // Store ptr to overflow_arg_area
7537 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7538 FIN, DAG.getIntPtrConstant(4));
7539 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7541 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7542 MachinePointerInfo(SV, 8),
7544 MemOps.push_back(Store);
7546 // Store ptr to reg_save_area.
7547 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7548 FIN, DAG.getIntPtrConstant(8));
7549 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7551 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7552 MachinePointerInfo(SV, 16), false, false, 0);
7553 MemOps.push_back(Store);
7554 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7555 &MemOps[0], MemOps.size());
7558 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7559 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7560 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
7562 report_fatal_error("VAArgInst is not yet implemented for x86-64!");
7566 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7567 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7568 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7569 SDValue Chain = Op.getOperand(0);
7570 SDValue DstPtr = Op.getOperand(1);
7571 SDValue SrcPtr = Op.getOperand(2);
7572 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7573 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7574 DebugLoc DL = Op.getDebugLoc();
7576 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7577 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7579 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7583 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7584 DebugLoc dl = Op.getDebugLoc();
7585 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7587 default: return SDValue(); // Don't custom lower most intrinsics.
7588 // Comparison intrinsics.
7589 case Intrinsic::x86_sse_comieq_ss:
7590 case Intrinsic::x86_sse_comilt_ss:
7591 case Intrinsic::x86_sse_comile_ss:
7592 case Intrinsic::x86_sse_comigt_ss:
7593 case Intrinsic::x86_sse_comige_ss:
7594 case Intrinsic::x86_sse_comineq_ss:
7595 case Intrinsic::x86_sse_ucomieq_ss:
7596 case Intrinsic::x86_sse_ucomilt_ss:
7597 case Intrinsic::x86_sse_ucomile_ss:
7598 case Intrinsic::x86_sse_ucomigt_ss:
7599 case Intrinsic::x86_sse_ucomige_ss:
7600 case Intrinsic::x86_sse_ucomineq_ss:
7601 case Intrinsic::x86_sse2_comieq_sd:
7602 case Intrinsic::x86_sse2_comilt_sd:
7603 case Intrinsic::x86_sse2_comile_sd:
7604 case Intrinsic::x86_sse2_comigt_sd:
7605 case Intrinsic::x86_sse2_comige_sd:
7606 case Intrinsic::x86_sse2_comineq_sd:
7607 case Intrinsic::x86_sse2_ucomieq_sd:
7608 case Intrinsic::x86_sse2_ucomilt_sd:
7609 case Intrinsic::x86_sse2_ucomile_sd:
7610 case Intrinsic::x86_sse2_ucomigt_sd:
7611 case Intrinsic::x86_sse2_ucomige_sd:
7612 case Intrinsic::x86_sse2_ucomineq_sd: {
7614 ISD::CondCode CC = ISD::SETCC_INVALID;
7617 case Intrinsic::x86_sse_comieq_ss:
7618 case Intrinsic::x86_sse2_comieq_sd:
7622 case Intrinsic::x86_sse_comilt_ss:
7623 case Intrinsic::x86_sse2_comilt_sd:
7627 case Intrinsic::x86_sse_comile_ss:
7628 case Intrinsic::x86_sse2_comile_sd:
7632 case Intrinsic::x86_sse_comigt_ss:
7633 case Intrinsic::x86_sse2_comigt_sd:
7637 case Intrinsic::x86_sse_comige_ss:
7638 case Intrinsic::x86_sse2_comige_sd:
7642 case Intrinsic::x86_sse_comineq_ss:
7643 case Intrinsic::x86_sse2_comineq_sd:
7647 case Intrinsic::x86_sse_ucomieq_ss:
7648 case Intrinsic::x86_sse2_ucomieq_sd:
7649 Opc = X86ISD::UCOMI;
7652 case Intrinsic::x86_sse_ucomilt_ss:
7653 case Intrinsic::x86_sse2_ucomilt_sd:
7654 Opc = X86ISD::UCOMI;
7657 case Intrinsic::x86_sse_ucomile_ss:
7658 case Intrinsic::x86_sse2_ucomile_sd:
7659 Opc = X86ISD::UCOMI;
7662 case Intrinsic::x86_sse_ucomigt_ss:
7663 case Intrinsic::x86_sse2_ucomigt_sd:
7664 Opc = X86ISD::UCOMI;
7667 case Intrinsic::x86_sse_ucomige_ss:
7668 case Intrinsic::x86_sse2_ucomige_sd:
7669 Opc = X86ISD::UCOMI;
7672 case Intrinsic::x86_sse_ucomineq_ss:
7673 case Intrinsic::x86_sse2_ucomineq_sd:
7674 Opc = X86ISD::UCOMI;
7679 SDValue LHS = Op.getOperand(1);
7680 SDValue RHS = Op.getOperand(2);
7681 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7682 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7683 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7684 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7685 DAG.getConstant(X86CC, MVT::i8), Cond);
7686 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7688 // ptest and testp intrinsics. The intrinsic these come from are designed to
7689 // return an integer value, not just an instruction so lower it to the ptest
7690 // or testp pattern and a setcc for the result.
7691 case Intrinsic::x86_sse41_ptestz:
7692 case Intrinsic::x86_sse41_ptestc:
7693 case Intrinsic::x86_sse41_ptestnzc:
7694 case Intrinsic::x86_avx_ptestz_256:
7695 case Intrinsic::x86_avx_ptestc_256:
7696 case Intrinsic::x86_avx_ptestnzc_256:
7697 case Intrinsic::x86_avx_vtestz_ps:
7698 case Intrinsic::x86_avx_vtestc_ps:
7699 case Intrinsic::x86_avx_vtestnzc_ps:
7700 case Intrinsic::x86_avx_vtestz_pd:
7701 case Intrinsic::x86_avx_vtestc_pd:
7702 case Intrinsic::x86_avx_vtestnzc_pd:
7703 case Intrinsic::x86_avx_vtestz_ps_256:
7704 case Intrinsic::x86_avx_vtestc_ps_256:
7705 case Intrinsic::x86_avx_vtestnzc_ps_256:
7706 case Intrinsic::x86_avx_vtestz_pd_256:
7707 case Intrinsic::x86_avx_vtestc_pd_256:
7708 case Intrinsic::x86_avx_vtestnzc_pd_256: {
7709 bool IsTestPacked = false;
7712 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7713 case Intrinsic::x86_avx_vtestz_ps:
7714 case Intrinsic::x86_avx_vtestz_pd:
7715 case Intrinsic::x86_avx_vtestz_ps_256:
7716 case Intrinsic::x86_avx_vtestz_pd_256:
7717 IsTestPacked = true; // Fallthrough
7718 case Intrinsic::x86_sse41_ptestz:
7719 case Intrinsic::x86_avx_ptestz_256:
7721 X86CC = X86::COND_E;
7723 case Intrinsic::x86_avx_vtestc_ps:
7724 case Intrinsic::x86_avx_vtestc_pd:
7725 case Intrinsic::x86_avx_vtestc_ps_256:
7726 case Intrinsic::x86_avx_vtestc_pd_256:
7727 IsTestPacked = true; // Fallthrough
7728 case Intrinsic::x86_sse41_ptestc:
7729 case Intrinsic::x86_avx_ptestc_256:
7731 X86CC = X86::COND_B;
7733 case Intrinsic::x86_avx_vtestnzc_ps:
7734 case Intrinsic::x86_avx_vtestnzc_pd:
7735 case Intrinsic::x86_avx_vtestnzc_ps_256:
7736 case Intrinsic::x86_avx_vtestnzc_pd_256:
7737 IsTestPacked = true; // Fallthrough
7738 case Intrinsic::x86_sse41_ptestnzc:
7739 case Intrinsic::x86_avx_ptestnzc_256:
7741 X86CC = X86::COND_A;
7745 SDValue LHS = Op.getOperand(1);
7746 SDValue RHS = Op.getOperand(2);
7747 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7748 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7749 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7750 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7751 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7754 // Fix vector shift instructions where the last operand is a non-immediate
7756 case Intrinsic::x86_sse2_pslli_w:
7757 case Intrinsic::x86_sse2_pslli_d:
7758 case Intrinsic::x86_sse2_pslli_q:
7759 case Intrinsic::x86_sse2_psrli_w:
7760 case Intrinsic::x86_sse2_psrli_d:
7761 case Intrinsic::x86_sse2_psrli_q:
7762 case Intrinsic::x86_sse2_psrai_w:
7763 case Intrinsic::x86_sse2_psrai_d:
7764 case Intrinsic::x86_mmx_pslli_w:
7765 case Intrinsic::x86_mmx_pslli_d:
7766 case Intrinsic::x86_mmx_pslli_q:
7767 case Intrinsic::x86_mmx_psrli_w:
7768 case Intrinsic::x86_mmx_psrli_d:
7769 case Intrinsic::x86_mmx_psrli_q:
7770 case Intrinsic::x86_mmx_psrai_w:
7771 case Intrinsic::x86_mmx_psrai_d: {
7772 SDValue ShAmt = Op.getOperand(2);
7773 if (isa<ConstantSDNode>(ShAmt))
7776 unsigned NewIntNo = 0;
7777 EVT ShAmtVT = MVT::v4i32;
7779 case Intrinsic::x86_sse2_pslli_w:
7780 NewIntNo = Intrinsic::x86_sse2_psll_w;
7782 case Intrinsic::x86_sse2_pslli_d:
7783 NewIntNo = Intrinsic::x86_sse2_psll_d;
7785 case Intrinsic::x86_sse2_pslli_q:
7786 NewIntNo = Intrinsic::x86_sse2_psll_q;
7788 case Intrinsic::x86_sse2_psrli_w:
7789 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7791 case Intrinsic::x86_sse2_psrli_d:
7792 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7794 case Intrinsic::x86_sse2_psrli_q:
7795 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7797 case Intrinsic::x86_sse2_psrai_w:
7798 NewIntNo = Intrinsic::x86_sse2_psra_w;
7800 case Intrinsic::x86_sse2_psrai_d:
7801 NewIntNo = Intrinsic::x86_sse2_psra_d;
7804 ShAmtVT = MVT::v2i32;
7806 case Intrinsic::x86_mmx_pslli_w:
7807 NewIntNo = Intrinsic::x86_mmx_psll_w;
7809 case Intrinsic::x86_mmx_pslli_d:
7810 NewIntNo = Intrinsic::x86_mmx_psll_d;
7812 case Intrinsic::x86_mmx_pslli_q:
7813 NewIntNo = Intrinsic::x86_mmx_psll_q;
7815 case Intrinsic::x86_mmx_psrli_w:
7816 NewIntNo = Intrinsic::x86_mmx_psrl_w;
7818 case Intrinsic::x86_mmx_psrli_d:
7819 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7821 case Intrinsic::x86_mmx_psrli_q:
7822 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7824 case Intrinsic::x86_mmx_psrai_w:
7825 NewIntNo = Intrinsic::x86_mmx_psra_w;
7827 case Intrinsic::x86_mmx_psrai_d:
7828 NewIntNo = Intrinsic::x86_mmx_psra_d;
7830 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7836 // The vector shift intrinsics with scalars uses 32b shift amounts but
7837 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7841 ShOps[1] = DAG.getConstant(0, MVT::i32);
7842 if (ShAmtVT == MVT::v4i32) {
7843 ShOps[2] = DAG.getUNDEF(MVT::i32);
7844 ShOps[3] = DAG.getUNDEF(MVT::i32);
7845 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7847 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7848 // FIXME this must be lowered to get rid of the invalid type.
7851 EVT VT = Op.getValueType();
7852 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7853 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7854 DAG.getConstant(NewIntNo, MVT::i32),
7855 Op.getOperand(1), ShAmt);
7860 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7861 SelectionDAG &DAG) const {
7862 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7863 MFI->setReturnAddressIsTaken(true);
7865 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7866 DebugLoc dl = Op.getDebugLoc();
7869 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7871 DAG.getConstant(TD->getPointerSize(),
7872 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7873 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7874 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7876 MachinePointerInfo(), false, false, 0);
7879 // Just load the return address.
7880 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7881 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7882 RetAddrFI, MachinePointerInfo(), false, false, 0);
7885 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7886 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7887 MFI->setFrameAddressIsTaken(true);
7889 EVT VT = Op.getValueType();
7890 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7891 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7892 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7893 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7895 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7896 MachinePointerInfo(),
7901 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7902 SelectionDAG &DAG) const {
7903 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7906 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7907 MachineFunction &MF = DAG.getMachineFunction();
7908 SDValue Chain = Op.getOperand(0);
7909 SDValue Offset = Op.getOperand(1);
7910 SDValue Handler = Op.getOperand(2);
7911 DebugLoc dl = Op.getDebugLoc();
7913 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
7914 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7916 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7918 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
7919 DAG.getIntPtrConstant(TD->getPointerSize()));
7920 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7921 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
7923 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7924 MF.getRegInfo().addLiveOut(StoreAddrReg);
7926 return DAG.getNode(X86ISD::EH_RETURN, dl,
7928 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7931 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7932 SelectionDAG &DAG) const {
7933 SDValue Root = Op.getOperand(0);
7934 SDValue Trmp = Op.getOperand(1); // trampoline
7935 SDValue FPtr = Op.getOperand(2); // nested function
7936 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7937 DebugLoc dl = Op.getDebugLoc();
7939 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7941 if (Subtarget->is64Bit()) {
7942 SDValue OutChains[6];
7944 // Large code-model.
7945 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
7946 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7948 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7949 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7951 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7953 // Load the pointer to the nested function into R11.
7954 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7955 SDValue Addr = Trmp;
7956 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7957 Addr, MachinePointerInfo(TrmpAddr),
7960 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7961 DAG.getConstant(2, MVT::i64));
7962 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
7963 MachinePointerInfo(TrmpAddr, 2),
7966 // Load the 'nest' parameter value into R10.
7967 // R10 is specified in X86CallingConv.td
7968 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7969 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7970 DAG.getConstant(10, MVT::i64));
7971 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7972 Addr, MachinePointerInfo(TrmpAddr, 10),
7975 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7976 DAG.getConstant(12, MVT::i64));
7977 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
7978 MachinePointerInfo(TrmpAddr, 12),
7981 // Jump to the nested function.
7982 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7983 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7984 DAG.getConstant(20, MVT::i64));
7985 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7986 Addr, MachinePointerInfo(TrmpAddr, 20),
7989 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7990 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7991 DAG.getConstant(22, MVT::i64));
7992 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7993 MachinePointerInfo(TrmpAddr, 22),
7997 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7998 return DAG.getMergeValues(Ops, 2, dl);
8000 const Function *Func =
8001 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8002 CallingConv::ID CC = Func->getCallingConv();
8007 llvm_unreachable("Unsupported calling convention");
8008 case CallingConv::C:
8009 case CallingConv::X86_StdCall: {
8010 // Pass 'nest' parameter in ECX.
8011 // Must be kept in sync with X86CallingConv.td
8014 // Check that ECX wasn't needed by an 'inreg' parameter.
8015 const FunctionType *FTy = Func->getFunctionType();
8016 const AttrListPtr &Attrs = Func->getAttributes();
8018 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8019 unsigned InRegCount = 0;
8022 for (FunctionType::param_iterator I = FTy->param_begin(),
8023 E = FTy->param_end(); I != E; ++I, ++Idx)
8024 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8025 // FIXME: should only count parameters that are lowered to integers.
8026 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8028 if (InRegCount > 2) {
8029 report_fatal_error("Nest register in use - reduce number of inreg"
8035 case CallingConv::X86_FastCall:
8036 case CallingConv::X86_ThisCall:
8037 case CallingConv::Fast:
8038 // Pass 'nest' parameter in EAX.
8039 // Must be kept in sync with X86CallingConv.td
8044 SDValue OutChains[4];
8047 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8048 DAG.getConstant(10, MVT::i32));
8049 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8051 // This is storing the opcode for MOV32ri.
8052 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8053 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8054 OutChains[0] = DAG.getStore(Root, dl,
8055 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8056 Trmp, MachinePointerInfo(TrmpAddr),
8059 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8060 DAG.getConstant(1, MVT::i32));
8061 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8062 MachinePointerInfo(TrmpAddr, 1),
8065 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8066 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8067 DAG.getConstant(5, MVT::i32));
8068 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8069 MachinePointerInfo(TrmpAddr, 5),
8072 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8073 DAG.getConstant(6, MVT::i32));
8074 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8075 MachinePointerInfo(TrmpAddr, 6),
8079 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8080 return DAG.getMergeValues(Ops, 2, dl);
8084 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8085 SelectionDAG &DAG) const {
8087 The rounding mode is in bits 11:10 of FPSR, and has the following
8094 FLT_ROUNDS, on the other hand, expects the following:
8101 To perform the conversion, we do:
8102 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8105 MachineFunction &MF = DAG.getMachineFunction();
8106 const TargetMachine &TM = MF.getTarget();
8107 const TargetFrameInfo &TFI = *TM.getFrameInfo();
8108 unsigned StackAlignment = TFI.getStackAlignment();
8109 EVT VT = Op.getValueType();
8110 DebugLoc DL = Op.getDebugLoc();
8112 // Save FP Control Word to stack slot
8113 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8114 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8117 MachineMemOperand *MMO =
8118 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8119 MachineMemOperand::MOStore, 2, 2);
8121 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8122 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8123 DAG.getVTList(MVT::Other),
8124 Ops, 2, MVT::i16, MMO);
8126 // Load FP Control Word from stack slot
8127 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8128 MachinePointerInfo(), false, false, 0);
8130 // Transform as necessary
8132 DAG.getNode(ISD::SRL, DL, MVT::i16,
8133 DAG.getNode(ISD::AND, DL, MVT::i16,
8134 CWD, DAG.getConstant(0x800, MVT::i16)),
8135 DAG.getConstant(11, MVT::i8));
8137 DAG.getNode(ISD::SRL, DL, MVT::i16,
8138 DAG.getNode(ISD::AND, DL, MVT::i16,
8139 CWD, DAG.getConstant(0x400, MVT::i16)),
8140 DAG.getConstant(9, MVT::i8));
8143 DAG.getNode(ISD::AND, DL, MVT::i16,
8144 DAG.getNode(ISD::ADD, DL, MVT::i16,
8145 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8146 DAG.getConstant(1, MVT::i16)),
8147 DAG.getConstant(3, MVT::i16));
8150 return DAG.getNode((VT.getSizeInBits() < 16 ?
8151 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8154 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8155 EVT VT = Op.getValueType();
8157 unsigned NumBits = VT.getSizeInBits();
8158 DebugLoc dl = Op.getDebugLoc();
8160 Op = Op.getOperand(0);
8161 if (VT == MVT::i8) {
8162 // Zero extend to i32 since there is not an i8 bsr.
8164 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8167 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8168 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8169 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8171 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8174 DAG.getConstant(NumBits+NumBits-1, OpVT),
8175 DAG.getConstant(X86::COND_E, MVT::i8),
8178 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8180 // Finally xor with NumBits-1.
8181 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8184 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8188 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8189 EVT VT = Op.getValueType();
8191 unsigned NumBits = VT.getSizeInBits();
8192 DebugLoc dl = Op.getDebugLoc();
8194 Op = Op.getOperand(0);
8195 if (VT == MVT::i8) {
8197 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8200 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8201 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8202 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8204 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8207 DAG.getConstant(NumBits, OpVT),
8208 DAG.getConstant(X86::COND_E, MVT::i8),
8211 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8214 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8218 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8219 EVT VT = Op.getValueType();
8220 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8221 DebugLoc dl = Op.getDebugLoc();
8223 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8224 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8225 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8226 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8227 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8229 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8230 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8231 // return AloBlo + AloBhi + AhiBlo;
8233 SDValue A = Op.getOperand(0);
8234 SDValue B = Op.getOperand(1);
8236 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8237 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8238 A, DAG.getConstant(32, MVT::i32));
8239 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8240 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8241 B, DAG.getConstant(32, MVT::i32));
8242 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8243 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8245 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8246 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8248 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8249 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8251 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8252 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8253 AloBhi, DAG.getConstant(32, MVT::i32));
8254 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8255 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8256 AhiBlo, DAG.getConstant(32, MVT::i32));
8257 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8258 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8262 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8263 EVT VT = Op.getValueType();
8264 DebugLoc dl = Op.getDebugLoc();
8265 SDValue R = Op.getOperand(0);
8267 LLVMContext *Context = DAG.getContext();
8269 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8271 if (VT == MVT::v4i32) {
8272 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8273 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8274 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8276 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8278 std::vector<Constant*> CV(4, CI);
8279 Constant *C = ConstantVector::get(CV);
8280 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8281 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8282 MachinePointerInfo::getConstantPool(),
8285 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8286 Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, Op);
8287 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8288 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8290 if (VT == MVT::v16i8) {
8292 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8293 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8294 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8296 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8297 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8299 std::vector<Constant*> CVM1(16, CM1);
8300 std::vector<Constant*> CVM2(16, CM2);
8301 Constant *C = ConstantVector::get(CVM1);
8302 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8303 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8304 MachinePointerInfo::getConstantPool(),
8307 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8308 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8309 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8310 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8311 DAG.getConstant(4, MVT::i32));
8312 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8313 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8316 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8318 C = ConstantVector::get(CVM2);
8319 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8320 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8321 MachinePointerInfo::getConstantPool(),
8324 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8325 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8326 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8327 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8328 DAG.getConstant(2, MVT::i32));
8329 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8330 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8333 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8335 // return pblendv(r, r+r, a);
8336 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8337 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8338 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8344 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8345 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8346 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8347 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8348 // has only one use.
8349 SDNode *N = Op.getNode();
8350 SDValue LHS = N->getOperand(0);
8351 SDValue RHS = N->getOperand(1);
8352 unsigned BaseOp = 0;
8354 DebugLoc dl = Op.getDebugLoc();
8356 switch (Op.getOpcode()) {
8357 default: llvm_unreachable("Unknown ovf instruction!");
8359 // A subtract of one will be selected as a INC. Note that INC doesn't
8360 // set CF, so we can't do this for UADDO.
8361 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8362 if (C->getAPIntValue() == 1) {
8363 BaseOp = X86ISD::INC;
8367 BaseOp = X86ISD::ADD;
8371 BaseOp = X86ISD::ADD;
8375 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8376 // set CF, so we can't do this for USUBO.
8377 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8378 if (C->getAPIntValue() == 1) {
8379 BaseOp = X86ISD::DEC;
8383 BaseOp = X86ISD::SUB;
8387 BaseOp = X86ISD::SUB;
8391 BaseOp = X86ISD::SMUL;
8395 BaseOp = X86ISD::UMUL;
8400 // Also sets EFLAGS.
8401 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8402 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
8405 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
8406 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
8408 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8412 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8413 DebugLoc dl = Op.getDebugLoc();
8415 if (!Subtarget->hasSSE2()) {
8416 SDValue Chain = Op.getOperand(0);
8417 SDValue Zero = DAG.getConstant(0,
8418 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8420 DAG.getRegister(X86::ESP, MVT::i32), // Base
8421 DAG.getTargetConstant(1, MVT::i8), // Scale
8422 DAG.getRegister(0, MVT::i32), // Index
8423 DAG.getTargetConstant(0, MVT::i32), // Disp
8424 DAG.getRegister(0, MVT::i32), // Segment.
8429 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8430 array_lengthof(Ops));
8431 return SDValue(Res, 0);
8434 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8436 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8438 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8439 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8440 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8441 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8443 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8444 if (!Op1 && !Op2 && !Op3 && Op4)
8445 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8447 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8448 if (Op1 && !Op2 && !Op3 && !Op4)
8449 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8451 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8453 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8456 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8457 EVT T = Op.getValueType();
8458 DebugLoc DL = Op.getDebugLoc();
8461 switch(T.getSimpleVT().SimpleTy) {
8463 assert(false && "Invalid value type!");
8464 case MVT::i8: Reg = X86::AL; size = 1; break;
8465 case MVT::i16: Reg = X86::AX; size = 2; break;
8466 case MVT::i32: Reg = X86::EAX; size = 4; break;
8468 assert(Subtarget->is64Bit() && "Node not type legal!");
8469 Reg = X86::RAX; size = 8;
8472 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8473 Op.getOperand(2), SDValue());
8474 SDValue Ops[] = { cpIn.getValue(0),
8477 DAG.getTargetConstant(size, MVT::i8),
8479 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8480 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8481 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8484 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8488 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8489 SelectionDAG &DAG) const {
8490 assert(Subtarget->is64Bit() && "Result not type legalized?");
8491 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8492 SDValue TheChain = Op.getOperand(0);
8493 DebugLoc dl = Op.getDebugLoc();
8494 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8495 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8496 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8498 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8499 DAG.getConstant(32, MVT::i8));
8501 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8504 return DAG.getMergeValues(Ops, 2, dl);
8507 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
8508 SelectionDAG &DAG) const {
8509 EVT SrcVT = Op.getOperand(0).getValueType();
8510 EVT DstVT = Op.getValueType();
8511 assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8512 Subtarget->hasMMX() && !DisableMMX) &&
8513 "Unexpected custom BIT_CONVERT");
8514 assert((DstVT == MVT::i64 ||
8515 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8516 "Unexpected custom BIT_CONVERT");
8517 // i64 <=> MMX conversions are Legal.
8518 if (SrcVT==MVT::i64 && DstVT.isVector())
8520 if (DstVT==MVT::i64 && SrcVT.isVector())
8522 // MMX <=> MMX conversions are Legal.
8523 if (SrcVT.isVector() && DstVT.isVector())
8525 // All other conversions need to be expanded.
8528 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8529 SDNode *Node = Op.getNode();
8530 DebugLoc dl = Node->getDebugLoc();
8531 EVT T = Node->getValueType(0);
8532 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8533 DAG.getConstant(0, T), Node->getOperand(2));
8534 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8535 cast<AtomicSDNode>(Node)->getMemoryVT(),
8536 Node->getOperand(0),
8537 Node->getOperand(1), negOp,
8538 cast<AtomicSDNode>(Node)->getSrcValue(),
8539 cast<AtomicSDNode>(Node)->getAlignment());
8542 /// LowerOperation - Provide custom lowering hooks for some operations.
8544 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8545 switch (Op.getOpcode()) {
8546 default: llvm_unreachable("Should not custom lower this!");
8547 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
8548 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
8549 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
8550 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8551 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8552 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8553 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8554 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8555 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8556 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8557 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8558 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8559 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
8560 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8561 case ISD::SHL_PARTS:
8562 case ISD::SRA_PARTS:
8563 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
8564 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
8565 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
8566 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
8567 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
8568 case ISD::FABS: return LowerFABS(Op, DAG);
8569 case ISD::FNEG: return LowerFNEG(Op, DAG);
8570 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8571 case ISD::SETCC: return LowerSETCC(Op, DAG);
8572 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
8573 case ISD::SELECT: return LowerSELECT(Op, DAG);
8574 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8575 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8576 case ISD::VASTART: return LowerVASTART(Op, DAG);
8577 case ISD::VAARG: return LowerVAARG(Op, DAG);
8578 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
8579 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8580 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8581 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8582 case ISD::FRAME_TO_ARGS_OFFSET:
8583 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8584 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8585 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
8586 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
8587 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8588 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
8589 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
8590 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
8591 case ISD::SHL: return LowerSHL(Op, DAG);
8597 case ISD::UMULO: return LowerXALUO(Op, DAG);
8598 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
8599 case ISD::BIT_CONVERT: return LowerBIT_CONVERT(Op, DAG);
8603 void X86TargetLowering::
8604 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8605 SelectionDAG &DAG, unsigned NewOp) const {
8606 EVT T = Node->getValueType(0);
8607 DebugLoc dl = Node->getDebugLoc();
8608 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8610 SDValue Chain = Node->getOperand(0);
8611 SDValue In1 = Node->getOperand(1);
8612 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8613 Node->getOperand(2), DAG.getIntPtrConstant(0));
8614 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8615 Node->getOperand(2), DAG.getIntPtrConstant(1));
8616 SDValue Ops[] = { Chain, In1, In2L, In2H };
8617 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8619 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8620 cast<MemSDNode>(Node)->getMemOperand());
8621 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8622 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8623 Results.push_back(Result.getValue(2));
8626 /// ReplaceNodeResults - Replace a node with an illegal result type
8627 /// with a new node built out of custom code.
8628 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8629 SmallVectorImpl<SDValue>&Results,
8630 SelectionDAG &DAG) const {
8631 DebugLoc dl = N->getDebugLoc();
8632 switch (N->getOpcode()) {
8634 assert(false && "Do not know how to custom type legalize this operation!");
8636 case ISD::FP_TO_SINT: {
8637 std::pair<SDValue,SDValue> Vals =
8638 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8639 SDValue FIST = Vals.first, StackSlot = Vals.second;
8640 if (FIST.getNode() != 0) {
8641 EVT VT = N->getValueType(0);
8642 // Return a load from the stack slot.
8643 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8644 MachinePointerInfo(), false, false, 0));
8648 case ISD::READCYCLECOUNTER: {
8649 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8650 SDValue TheChain = N->getOperand(0);
8651 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8652 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8654 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8656 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8657 SDValue Ops[] = { eax, edx };
8658 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8659 Results.push_back(edx.getValue(1));
8662 case ISD::ATOMIC_CMP_SWAP: {
8663 EVT T = N->getValueType(0);
8664 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8665 SDValue cpInL, cpInH;
8666 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8667 DAG.getConstant(0, MVT::i32));
8668 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8669 DAG.getConstant(1, MVT::i32));
8670 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8671 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8673 SDValue swapInL, swapInH;
8674 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8675 DAG.getConstant(0, MVT::i32));
8676 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8677 DAG.getConstant(1, MVT::i32));
8678 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8680 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8681 swapInL.getValue(1));
8682 SDValue Ops[] = { swapInH.getValue(0),
8684 swapInH.getValue(1) };
8685 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8686 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
8687 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8688 MVT::i32, Result.getValue(1));
8689 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8690 MVT::i32, cpOutL.getValue(2));
8691 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8692 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8693 Results.push_back(cpOutH.getValue(1));
8696 case ISD::ATOMIC_LOAD_ADD:
8697 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8699 case ISD::ATOMIC_LOAD_AND:
8700 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8702 case ISD::ATOMIC_LOAD_NAND:
8703 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8705 case ISD::ATOMIC_LOAD_OR:
8706 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8708 case ISD::ATOMIC_LOAD_SUB:
8709 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8711 case ISD::ATOMIC_LOAD_XOR:
8712 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8714 case ISD::ATOMIC_SWAP:
8715 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8720 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8722 default: return NULL;
8723 case X86ISD::BSF: return "X86ISD::BSF";
8724 case X86ISD::BSR: return "X86ISD::BSR";
8725 case X86ISD::SHLD: return "X86ISD::SHLD";
8726 case X86ISD::SHRD: return "X86ISD::SHRD";
8727 case X86ISD::FAND: return "X86ISD::FAND";
8728 case X86ISD::FOR: return "X86ISD::FOR";
8729 case X86ISD::FXOR: return "X86ISD::FXOR";
8730 case X86ISD::FSRL: return "X86ISD::FSRL";
8731 case X86ISD::FILD: return "X86ISD::FILD";
8732 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
8733 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8734 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8735 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8736 case X86ISD::FLD: return "X86ISD::FLD";
8737 case X86ISD::FST: return "X86ISD::FST";
8738 case X86ISD::CALL: return "X86ISD::CALL";
8739 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
8740 case X86ISD::BT: return "X86ISD::BT";
8741 case X86ISD::CMP: return "X86ISD::CMP";
8742 case X86ISD::COMI: return "X86ISD::COMI";
8743 case X86ISD::UCOMI: return "X86ISD::UCOMI";
8744 case X86ISD::SETCC: return "X86ISD::SETCC";
8745 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
8746 case X86ISD::CMOV: return "X86ISD::CMOV";
8747 case X86ISD::BRCOND: return "X86ISD::BRCOND";
8748 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
8749 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
8750 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
8751 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
8752 case X86ISD::Wrapper: return "X86ISD::Wrapper";
8753 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
8754 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
8755 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
8756 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
8757 case X86ISD::PINSRB: return "X86ISD::PINSRB";
8758 case X86ISD::PINSRW: return "X86ISD::PINSRW";
8759 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
8760 case X86ISD::FMAX: return "X86ISD::FMAX";
8761 case X86ISD::FMIN: return "X86ISD::FMIN";
8762 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
8763 case X86ISD::FRCP: return "X86ISD::FRCP";
8764 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
8765 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
8766 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
8767 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
8768 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
8769 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
8770 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
8771 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
8772 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
8773 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
8774 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
8775 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
8776 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
8777 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
8778 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
8779 case X86ISD::VSHL: return "X86ISD::VSHL";
8780 case X86ISD::VSRL: return "X86ISD::VSRL";
8781 case X86ISD::CMPPD: return "X86ISD::CMPPD";
8782 case X86ISD::CMPPS: return "X86ISD::CMPPS";
8783 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
8784 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
8785 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
8786 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
8787 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
8788 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
8789 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
8790 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
8791 case X86ISD::ADD: return "X86ISD::ADD";
8792 case X86ISD::SUB: return "X86ISD::SUB";
8793 case X86ISD::SMUL: return "X86ISD::SMUL";
8794 case X86ISD::UMUL: return "X86ISD::UMUL";
8795 case X86ISD::INC: return "X86ISD::INC";
8796 case X86ISD::DEC: return "X86ISD::DEC";
8797 case X86ISD::OR: return "X86ISD::OR";
8798 case X86ISD::XOR: return "X86ISD::XOR";
8799 case X86ISD::AND: return "X86ISD::AND";
8800 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
8801 case X86ISD::PTEST: return "X86ISD::PTEST";
8802 case X86ISD::TESTP: return "X86ISD::TESTP";
8803 case X86ISD::PALIGN: return "X86ISD::PALIGN";
8804 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
8805 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
8806 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
8807 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
8808 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
8809 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
8810 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
8811 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
8812 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
8813 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
8814 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
8815 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
8816 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
8817 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
8818 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
8819 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
8820 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
8821 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
8822 case X86ISD::MOVSD: return "X86ISD::MOVSD";
8823 case X86ISD::MOVSS: return "X86ISD::MOVSS";
8824 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
8825 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
8826 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
8827 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
8828 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
8829 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
8830 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
8831 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
8832 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
8833 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
8834 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
8835 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
8836 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8837 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
8841 // isLegalAddressingMode - Return true if the addressing mode represented
8842 // by AM is legal for this target, for a load/store of the specified type.
8843 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8844 const Type *Ty) const {
8845 // X86 supports extremely general addressing modes.
8846 CodeModel::Model M = getTargetMachine().getCodeModel();
8847 Reloc::Model R = getTargetMachine().getRelocationModel();
8849 // X86 allows a sign-extended 32-bit immediate field as a displacement.
8850 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8855 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8857 // If a reference to this global requires an extra load, we can't fold it.
8858 if (isGlobalStubReference(GVFlags))
8861 // If BaseGV requires a register for the PIC base, we cannot also have a
8862 // BaseReg specified.
8863 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8866 // If lower 4G is not available, then we must use rip-relative addressing.
8867 if ((M != CodeModel::Small || R != Reloc::Static) &&
8868 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8878 // These scales always work.
8883 // These scales are formed with basereg+scalereg. Only accept if there is
8888 default: // Other stuff never works.
8896 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8897 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8899 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8900 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8901 if (NumBits1 <= NumBits2)
8906 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8907 if (!VT1.isInteger() || !VT2.isInteger())
8909 unsigned NumBits1 = VT1.getSizeInBits();
8910 unsigned NumBits2 = VT2.getSizeInBits();
8911 if (NumBits1 <= NumBits2)
8916 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
8917 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8918 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
8921 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8922 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8923 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
8926 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
8927 // i16 instructions are longer (0x66 prefix) and potentially slower.
8928 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
8931 /// isShuffleMaskLegal - Targets can use this to indicate that they only
8932 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8933 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8934 /// are assumed to be legal.
8936 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
8938 // Very little shuffling can be done for 64-bit vectors right now.
8939 if (VT.getSizeInBits() == 64)
8940 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
8942 // FIXME: pshufb, blends, shifts.
8943 return (VT.getVectorNumElements() == 2 ||
8944 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8945 isMOVLMask(M, VT) ||
8946 isSHUFPMask(M, VT) ||
8947 isPSHUFDMask(M, VT) ||
8948 isPSHUFHWMask(M, VT) ||
8949 isPSHUFLWMask(M, VT) ||
8950 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
8951 isUNPCKLMask(M, VT) ||
8952 isUNPCKHMask(M, VT) ||
8953 isUNPCKL_v_undef_Mask(M, VT) ||
8954 isUNPCKH_v_undef_Mask(M, VT));
8958 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
8960 unsigned NumElts = VT.getVectorNumElements();
8961 // FIXME: This collection of masks seems suspect.
8964 if (NumElts == 4 && VT.getSizeInBits() == 128) {
8965 return (isMOVLMask(Mask, VT) ||
8966 isCommutedMOVLMask(Mask, VT, true) ||
8967 isSHUFPMask(Mask, VT) ||
8968 isCommutedSHUFPMask(Mask, VT));
8973 //===----------------------------------------------------------------------===//
8974 // X86 Scheduler Hooks
8975 //===----------------------------------------------------------------------===//
8977 // private utility function
8979 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
8980 MachineBasicBlock *MBB,
8987 TargetRegisterClass *RC,
8988 bool invSrc) const {
8989 // For the atomic bitwise operator, we generate
8992 // ld t1 = [bitinstr.addr]
8993 // op t2 = t1, [bitinstr.val]
8995 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8997 // fallthrough -->nextMBB
8998 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8999 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9000 MachineFunction::iterator MBBIter = MBB;
9003 /// First build the CFG
9004 MachineFunction *F = MBB->getParent();
9005 MachineBasicBlock *thisMBB = MBB;
9006 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9007 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9008 F->insert(MBBIter, newMBB);
9009 F->insert(MBBIter, nextMBB);
9011 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9012 nextMBB->splice(nextMBB->begin(), thisMBB,
9013 llvm::next(MachineBasicBlock::iterator(bInstr)),
9015 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9017 // Update thisMBB to fall through to newMBB
9018 thisMBB->addSuccessor(newMBB);
9020 // newMBB jumps to itself and fall through to nextMBB
9021 newMBB->addSuccessor(nextMBB);
9022 newMBB->addSuccessor(newMBB);
9024 // Insert instructions into newMBB based on incoming instruction
9025 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9026 "unexpected number of operands");
9027 DebugLoc dl = bInstr->getDebugLoc();
9028 MachineOperand& destOper = bInstr->getOperand(0);
9029 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9030 int numArgs = bInstr->getNumOperands() - 1;
9031 for (int i=0; i < numArgs; ++i)
9032 argOpers[i] = &bInstr->getOperand(i+1);
9034 // x86 address has 4 operands: base, index, scale, and displacement
9035 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9036 int valArgIndx = lastAddrIndx + 1;
9038 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9039 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9040 for (int i=0; i <= lastAddrIndx; ++i)
9041 (*MIB).addOperand(*argOpers[i]);
9043 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9045 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9050 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9051 assert((argOpers[valArgIndx]->isReg() ||
9052 argOpers[valArgIndx]->isImm()) &&
9054 if (argOpers[valArgIndx]->isReg())
9055 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9057 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9059 (*MIB).addOperand(*argOpers[valArgIndx]);
9061 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9064 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9065 for (int i=0; i <= lastAddrIndx; ++i)
9066 (*MIB).addOperand(*argOpers[i]);
9068 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9069 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9070 bInstr->memoperands_end());
9072 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9076 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9078 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9082 // private utility function: 64 bit atomics on 32 bit host.
9084 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9085 MachineBasicBlock *MBB,
9090 bool invSrc) const {
9091 // For the atomic bitwise operator, we generate
9092 // thisMBB (instructions are in pairs, except cmpxchg8b)
9093 // ld t1,t2 = [bitinstr.addr]
9095 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9096 // op t5, t6 <- out1, out2, [bitinstr.val]
9097 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9098 // mov ECX, EBX <- t5, t6
9099 // mov EAX, EDX <- t1, t2
9100 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9101 // mov t3, t4 <- EAX, EDX
9103 // result in out1, out2
9104 // fallthrough -->nextMBB
9106 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9107 const unsigned LoadOpc = X86::MOV32rm;
9108 const unsigned NotOpc = X86::NOT32r;
9109 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9110 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9111 MachineFunction::iterator MBBIter = MBB;
9114 /// First build the CFG
9115 MachineFunction *F = MBB->getParent();
9116 MachineBasicBlock *thisMBB = MBB;
9117 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9118 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9119 F->insert(MBBIter, newMBB);
9120 F->insert(MBBIter, nextMBB);
9122 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9123 nextMBB->splice(nextMBB->begin(), thisMBB,
9124 llvm::next(MachineBasicBlock::iterator(bInstr)),
9126 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9128 // Update thisMBB to fall through to newMBB
9129 thisMBB->addSuccessor(newMBB);
9131 // newMBB jumps to itself and fall through to nextMBB
9132 newMBB->addSuccessor(nextMBB);
9133 newMBB->addSuccessor(newMBB);
9135 DebugLoc dl = bInstr->getDebugLoc();
9136 // Insert instructions into newMBB based on incoming instruction
9137 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9138 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9139 "unexpected number of operands");
9140 MachineOperand& dest1Oper = bInstr->getOperand(0);
9141 MachineOperand& dest2Oper = bInstr->getOperand(1);
9142 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9143 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9144 argOpers[i] = &bInstr->getOperand(i+2);
9146 // We use some of the operands multiple times, so conservatively just
9147 // clear any kill flags that might be present.
9148 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9149 argOpers[i]->setIsKill(false);
9152 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9153 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9155 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9156 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9157 for (int i=0; i <= lastAddrIndx; ++i)
9158 (*MIB).addOperand(*argOpers[i]);
9159 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9160 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9161 // add 4 to displacement.
9162 for (int i=0; i <= lastAddrIndx-2; ++i)
9163 (*MIB).addOperand(*argOpers[i]);
9164 MachineOperand newOp3 = *(argOpers[3]);
9166 newOp3.setImm(newOp3.getImm()+4);
9168 newOp3.setOffset(newOp3.getOffset()+4);
9169 (*MIB).addOperand(newOp3);
9170 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9172 // t3/4 are defined later, at the bottom of the loop
9173 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9174 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9175 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9176 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9177 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9178 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9180 // The subsequent operations should be using the destination registers of
9181 //the PHI instructions.
9183 t1 = F->getRegInfo().createVirtualRegister(RC);
9184 t2 = F->getRegInfo().createVirtualRegister(RC);
9185 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9186 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9188 t1 = dest1Oper.getReg();
9189 t2 = dest2Oper.getReg();
9192 int valArgIndx = lastAddrIndx + 1;
9193 assert((argOpers[valArgIndx]->isReg() ||
9194 argOpers[valArgIndx]->isImm()) &&
9196 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9197 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9198 if (argOpers[valArgIndx]->isReg())
9199 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9201 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9202 if (regOpcL != X86::MOV32rr)
9204 (*MIB).addOperand(*argOpers[valArgIndx]);
9205 assert(argOpers[valArgIndx + 1]->isReg() ==
9206 argOpers[valArgIndx]->isReg());
9207 assert(argOpers[valArgIndx + 1]->isImm() ==
9208 argOpers[valArgIndx]->isImm());
9209 if (argOpers[valArgIndx + 1]->isReg())
9210 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9212 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9213 if (regOpcH != X86::MOV32rr)
9215 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9217 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9219 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9222 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9224 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9227 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9228 for (int i=0; i <= lastAddrIndx; ++i)
9229 (*MIB).addOperand(*argOpers[i]);
9231 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9232 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9233 bInstr->memoperands_end());
9235 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9236 MIB.addReg(X86::EAX);
9237 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9238 MIB.addReg(X86::EDX);
9241 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9243 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9247 // private utility function
9249 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9250 MachineBasicBlock *MBB,
9251 unsigned cmovOpc) const {
9252 // For the atomic min/max operator, we generate
9255 // ld t1 = [min/max.addr]
9256 // mov t2 = [min/max.val]
9258 // cmov[cond] t2 = t1
9260 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9262 // fallthrough -->nextMBB
9264 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9265 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9266 MachineFunction::iterator MBBIter = MBB;
9269 /// First build the CFG
9270 MachineFunction *F = MBB->getParent();
9271 MachineBasicBlock *thisMBB = MBB;
9272 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9273 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9274 F->insert(MBBIter, newMBB);
9275 F->insert(MBBIter, nextMBB);
9277 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9278 nextMBB->splice(nextMBB->begin(), thisMBB,
9279 llvm::next(MachineBasicBlock::iterator(mInstr)),
9281 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9283 // Update thisMBB to fall through to newMBB
9284 thisMBB->addSuccessor(newMBB);
9286 // newMBB jumps to newMBB and fall through to nextMBB
9287 newMBB->addSuccessor(nextMBB);
9288 newMBB->addSuccessor(newMBB);
9290 DebugLoc dl = mInstr->getDebugLoc();
9291 // Insert instructions into newMBB based on incoming instruction
9292 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9293 "unexpected number of operands");
9294 MachineOperand& destOper = mInstr->getOperand(0);
9295 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9296 int numArgs = mInstr->getNumOperands() - 1;
9297 for (int i=0; i < numArgs; ++i)
9298 argOpers[i] = &mInstr->getOperand(i+1);
9300 // x86 address has 4 operands: base, index, scale, and displacement
9301 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9302 int valArgIndx = lastAddrIndx + 1;
9304 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9305 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9306 for (int i=0; i <= lastAddrIndx; ++i)
9307 (*MIB).addOperand(*argOpers[i]);
9309 // We only support register and immediate values
9310 assert((argOpers[valArgIndx]->isReg() ||
9311 argOpers[valArgIndx]->isImm()) &&
9314 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9315 if (argOpers[valArgIndx]->isReg())
9316 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9318 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9319 (*MIB).addOperand(*argOpers[valArgIndx]);
9321 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9324 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9329 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9330 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9334 // Cmp and exchange if none has modified the memory location
9335 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9336 for (int i=0; i <= lastAddrIndx; ++i)
9337 (*MIB).addOperand(*argOpers[i]);
9339 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9340 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9341 mInstr->memoperands_end());
9343 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9344 MIB.addReg(X86::EAX);
9347 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9349 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9353 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9354 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9357 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9358 unsigned numArgs, bool memArg) const {
9360 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9361 "Target must have SSE4.2 or AVX features enabled");
9363 DebugLoc dl = MI->getDebugLoc();
9364 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9368 if (!Subtarget->hasAVX()) {
9370 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9372 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9375 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9377 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9380 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
9382 for (unsigned i = 0; i < numArgs; ++i) {
9383 MachineOperand &Op = MI->getOperand(i+1);
9385 if (!(Op.isReg() && Op.isImplicit()))
9389 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9392 MI->eraseFromParent();
9398 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9400 MachineBasicBlock *MBB) const {
9401 // Emit code to save XMM registers to the stack. The ABI says that the
9402 // number of registers to save is given in %al, so it's theoretically
9403 // possible to do an indirect jump trick to avoid saving all of them,
9404 // however this code takes a simpler approach and just executes all
9405 // of the stores if %al is non-zero. It's less code, and it's probably
9406 // easier on the hardware branch predictor, and stores aren't all that
9407 // expensive anyway.
9409 // Create the new basic blocks. One block contains all the XMM stores,
9410 // and one block is the final destination regardless of whether any
9411 // stores were performed.
9412 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9413 MachineFunction *F = MBB->getParent();
9414 MachineFunction::iterator MBBIter = MBB;
9416 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9417 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9418 F->insert(MBBIter, XMMSaveMBB);
9419 F->insert(MBBIter, EndMBB);
9421 // Transfer the remainder of MBB and its successor edges to EndMBB.
9422 EndMBB->splice(EndMBB->begin(), MBB,
9423 llvm::next(MachineBasicBlock::iterator(MI)),
9425 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9427 // The original block will now fall through to the XMM save block.
9428 MBB->addSuccessor(XMMSaveMBB);
9429 // The XMMSaveMBB will fall through to the end block.
9430 XMMSaveMBB->addSuccessor(EndMBB);
9432 // Now add the instructions.
9433 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9434 DebugLoc DL = MI->getDebugLoc();
9436 unsigned CountReg = MI->getOperand(0).getReg();
9437 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9438 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9440 if (!Subtarget->isTargetWin64()) {
9441 // If %al is 0, branch around the XMM save block.
9442 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9443 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9444 MBB->addSuccessor(EndMBB);
9447 // In the XMM save block, save all the XMM argument registers.
9448 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9449 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9450 MachineMemOperand *MMO =
9451 F->getMachineMemOperand(
9452 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9453 MachineMemOperand::MOStore,
9454 /*Size=*/16, /*Align=*/16);
9455 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9456 .addFrameIndex(RegSaveFrameIndex)
9457 .addImm(/*Scale=*/1)
9458 .addReg(/*IndexReg=*/0)
9459 .addImm(/*Disp=*/Offset)
9460 .addReg(/*Segment=*/0)
9461 .addReg(MI->getOperand(i).getReg())
9462 .addMemOperand(MMO);
9465 MI->eraseFromParent(); // The pseudo instruction is gone now.
9471 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9472 MachineBasicBlock *BB) const {
9473 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9474 DebugLoc DL = MI->getDebugLoc();
9476 // To "insert" a SELECT_CC instruction, we actually have to insert the
9477 // diamond control-flow pattern. The incoming instruction knows the
9478 // destination vreg to set, the condition code register to branch on, the
9479 // true/false values to select between, and a branch opcode to use.
9480 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9481 MachineFunction::iterator It = BB;
9487 // cmpTY ccX, r1, r2
9489 // fallthrough --> copy0MBB
9490 MachineBasicBlock *thisMBB = BB;
9491 MachineFunction *F = BB->getParent();
9492 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9493 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9494 F->insert(It, copy0MBB);
9495 F->insert(It, sinkMBB);
9497 // If the EFLAGS register isn't dead in the terminator, then claim that it's
9498 // live into the sink and copy blocks.
9499 const MachineFunction *MF = BB->getParent();
9500 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9501 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9503 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9504 const MachineOperand &MO = MI->getOperand(I);
9505 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9506 unsigned Reg = MO.getReg();
9507 if (Reg != X86::EFLAGS) continue;
9508 copy0MBB->addLiveIn(Reg);
9509 sinkMBB->addLiveIn(Reg);
9512 // Transfer the remainder of BB and its successor edges to sinkMBB.
9513 sinkMBB->splice(sinkMBB->begin(), BB,
9514 llvm::next(MachineBasicBlock::iterator(MI)),
9516 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9518 // Add the true and fallthrough blocks as its successors.
9519 BB->addSuccessor(copy0MBB);
9520 BB->addSuccessor(sinkMBB);
9522 // Create the conditional branch instruction.
9524 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9525 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9528 // %FalseValue = ...
9529 // # fallthrough to sinkMBB
9530 copy0MBB->addSuccessor(sinkMBB);
9533 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9535 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9536 TII->get(X86::PHI), MI->getOperand(0).getReg())
9537 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9538 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9540 MI->eraseFromParent(); // The pseudo instruction is gone now.
9545 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
9546 MachineBasicBlock *BB) const {
9547 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9548 DebugLoc DL = MI->getDebugLoc();
9550 // The lowering is pretty easy: we're just emitting the call to _alloca. The
9551 // non-trivial part is impdef of ESP.
9552 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9555 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9556 .addExternalSymbol("_alloca")
9557 .addReg(X86::EAX, RegState::Implicit)
9558 .addReg(X86::ESP, RegState::Implicit)
9559 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9560 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9561 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9563 MI->eraseFromParent(); // The pseudo instruction is gone now.
9568 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9569 MachineBasicBlock *BB) const {
9570 // This is pretty easy. We're taking the value that we received from
9571 // our load from the relocation, sticking it in either RDI (x86-64)
9572 // or EAX and doing an indirect call. The return value will then
9573 // be in the normal return register.
9574 const X86InstrInfo *TII
9575 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9576 DebugLoc DL = MI->getDebugLoc();
9577 MachineFunction *F = BB->getParent();
9579 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
9580 assert(MI->getOperand(3).isGlobal() && "This should be a global");
9582 if (Subtarget->is64Bit()) {
9583 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9584 TII->get(X86::MOV64rm), X86::RDI)
9586 .addImm(0).addReg(0)
9587 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9588 MI->getOperand(3).getTargetFlags())
9590 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
9591 addDirectMem(MIB, X86::RDI);
9592 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
9593 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9594 TII->get(X86::MOV32rm), X86::EAX)
9596 .addImm(0).addReg(0)
9597 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9598 MI->getOperand(3).getTargetFlags())
9600 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9601 addDirectMem(MIB, X86::EAX);
9603 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9604 TII->get(X86::MOV32rm), X86::EAX)
9605 .addReg(TII->getGlobalBaseReg(F))
9606 .addImm(0).addReg(0)
9607 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9608 MI->getOperand(3).getTargetFlags())
9610 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9611 addDirectMem(MIB, X86::EAX);
9614 MI->eraseFromParent(); // The pseudo instruction is gone now.
9619 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
9620 MachineBasicBlock *BB) const {
9621 switch (MI->getOpcode()) {
9622 default: assert(false && "Unexpected instr type to insert");
9623 case X86::MINGW_ALLOCA:
9624 return EmitLoweredMingwAlloca(MI, BB);
9625 case X86::TLSCall_32:
9626 case X86::TLSCall_64:
9627 return EmitLoweredTLSCall(MI, BB);
9629 case X86::CMOV_FR32:
9630 case X86::CMOV_FR64:
9631 case X86::CMOV_V4F32:
9632 case X86::CMOV_V2F64:
9633 case X86::CMOV_V2I64:
9634 case X86::CMOV_GR16:
9635 case X86::CMOV_GR32:
9636 case X86::CMOV_RFP32:
9637 case X86::CMOV_RFP64:
9638 case X86::CMOV_RFP80:
9639 return EmitLoweredSelect(MI, BB);
9641 case X86::FP32_TO_INT16_IN_MEM:
9642 case X86::FP32_TO_INT32_IN_MEM:
9643 case X86::FP32_TO_INT64_IN_MEM:
9644 case X86::FP64_TO_INT16_IN_MEM:
9645 case X86::FP64_TO_INT32_IN_MEM:
9646 case X86::FP64_TO_INT64_IN_MEM:
9647 case X86::FP80_TO_INT16_IN_MEM:
9648 case X86::FP80_TO_INT32_IN_MEM:
9649 case X86::FP80_TO_INT64_IN_MEM: {
9650 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9651 DebugLoc DL = MI->getDebugLoc();
9653 // Change the floating point control register to use "round towards zero"
9654 // mode when truncating to an integer value.
9655 MachineFunction *F = BB->getParent();
9656 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
9657 addFrameReference(BuildMI(*BB, MI, DL,
9658 TII->get(X86::FNSTCW16m)), CWFrameIdx);
9660 // Load the old value of the high byte of the control word...
9662 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
9663 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
9666 // Set the high part to be round to zero...
9667 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
9670 // Reload the modified control word now...
9671 addFrameReference(BuildMI(*BB, MI, DL,
9672 TII->get(X86::FLDCW16m)), CWFrameIdx);
9674 // Restore the memory image of control word to original value
9675 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
9678 // Get the X86 opcode to use.
9680 switch (MI->getOpcode()) {
9681 default: llvm_unreachable("illegal opcode!");
9682 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
9683 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
9684 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
9685 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
9686 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
9687 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
9688 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
9689 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
9690 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
9694 MachineOperand &Op = MI->getOperand(0);
9696 AM.BaseType = X86AddressMode::RegBase;
9697 AM.Base.Reg = Op.getReg();
9699 AM.BaseType = X86AddressMode::FrameIndexBase;
9700 AM.Base.FrameIndex = Op.getIndex();
9702 Op = MI->getOperand(1);
9704 AM.Scale = Op.getImm();
9705 Op = MI->getOperand(2);
9707 AM.IndexReg = Op.getImm();
9708 Op = MI->getOperand(3);
9709 if (Op.isGlobal()) {
9710 AM.GV = Op.getGlobal();
9712 AM.Disp = Op.getImm();
9714 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
9715 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
9717 // Reload the original control word now.
9718 addFrameReference(BuildMI(*BB, MI, DL,
9719 TII->get(X86::FLDCW16m)), CWFrameIdx);
9721 MI->eraseFromParent(); // The pseudo instruction is gone now.
9724 // String/text processing lowering.
9725 case X86::PCMPISTRM128REG:
9726 case X86::VPCMPISTRM128REG:
9727 return EmitPCMP(MI, BB, 3, false /* in-mem */);
9728 case X86::PCMPISTRM128MEM:
9729 case X86::VPCMPISTRM128MEM:
9730 return EmitPCMP(MI, BB, 3, true /* in-mem */);
9731 case X86::PCMPESTRM128REG:
9732 case X86::VPCMPESTRM128REG:
9733 return EmitPCMP(MI, BB, 5, false /* in mem */);
9734 case X86::PCMPESTRM128MEM:
9735 case X86::VPCMPESTRM128MEM:
9736 return EmitPCMP(MI, BB, 5, true /* in mem */);
9739 case X86::ATOMAND32:
9740 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9741 X86::AND32ri, X86::MOV32rm,
9743 X86::NOT32r, X86::EAX,
9744 X86::GR32RegisterClass);
9746 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
9747 X86::OR32ri, X86::MOV32rm,
9749 X86::NOT32r, X86::EAX,
9750 X86::GR32RegisterClass);
9751 case X86::ATOMXOR32:
9752 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
9753 X86::XOR32ri, X86::MOV32rm,
9755 X86::NOT32r, X86::EAX,
9756 X86::GR32RegisterClass);
9757 case X86::ATOMNAND32:
9758 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9759 X86::AND32ri, X86::MOV32rm,
9761 X86::NOT32r, X86::EAX,
9762 X86::GR32RegisterClass, true);
9763 case X86::ATOMMIN32:
9764 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
9765 case X86::ATOMMAX32:
9766 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
9767 case X86::ATOMUMIN32:
9768 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
9769 case X86::ATOMUMAX32:
9770 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
9772 case X86::ATOMAND16:
9773 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9774 X86::AND16ri, X86::MOV16rm,
9776 X86::NOT16r, X86::AX,
9777 X86::GR16RegisterClass);
9779 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
9780 X86::OR16ri, X86::MOV16rm,
9782 X86::NOT16r, X86::AX,
9783 X86::GR16RegisterClass);
9784 case X86::ATOMXOR16:
9785 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
9786 X86::XOR16ri, X86::MOV16rm,
9788 X86::NOT16r, X86::AX,
9789 X86::GR16RegisterClass);
9790 case X86::ATOMNAND16:
9791 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9792 X86::AND16ri, X86::MOV16rm,
9794 X86::NOT16r, X86::AX,
9795 X86::GR16RegisterClass, true);
9796 case X86::ATOMMIN16:
9797 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
9798 case X86::ATOMMAX16:
9799 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
9800 case X86::ATOMUMIN16:
9801 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
9802 case X86::ATOMUMAX16:
9803 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
9806 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9807 X86::AND8ri, X86::MOV8rm,
9809 X86::NOT8r, X86::AL,
9810 X86::GR8RegisterClass);
9812 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
9813 X86::OR8ri, X86::MOV8rm,
9815 X86::NOT8r, X86::AL,
9816 X86::GR8RegisterClass);
9818 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
9819 X86::XOR8ri, X86::MOV8rm,
9821 X86::NOT8r, X86::AL,
9822 X86::GR8RegisterClass);
9823 case X86::ATOMNAND8:
9824 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9825 X86::AND8ri, X86::MOV8rm,
9827 X86::NOT8r, X86::AL,
9828 X86::GR8RegisterClass, true);
9829 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
9830 // This group is for 64-bit host.
9831 case X86::ATOMAND64:
9832 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9833 X86::AND64ri32, X86::MOV64rm,
9835 X86::NOT64r, X86::RAX,
9836 X86::GR64RegisterClass);
9838 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
9839 X86::OR64ri32, X86::MOV64rm,
9841 X86::NOT64r, X86::RAX,
9842 X86::GR64RegisterClass);
9843 case X86::ATOMXOR64:
9844 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
9845 X86::XOR64ri32, X86::MOV64rm,
9847 X86::NOT64r, X86::RAX,
9848 X86::GR64RegisterClass);
9849 case X86::ATOMNAND64:
9850 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9851 X86::AND64ri32, X86::MOV64rm,
9853 X86::NOT64r, X86::RAX,
9854 X86::GR64RegisterClass, true);
9855 case X86::ATOMMIN64:
9856 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
9857 case X86::ATOMMAX64:
9858 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
9859 case X86::ATOMUMIN64:
9860 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
9861 case X86::ATOMUMAX64:
9862 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
9864 // This group does 64-bit operations on a 32-bit host.
9865 case X86::ATOMAND6432:
9866 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9867 X86::AND32rr, X86::AND32rr,
9868 X86::AND32ri, X86::AND32ri,
9870 case X86::ATOMOR6432:
9871 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9872 X86::OR32rr, X86::OR32rr,
9873 X86::OR32ri, X86::OR32ri,
9875 case X86::ATOMXOR6432:
9876 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9877 X86::XOR32rr, X86::XOR32rr,
9878 X86::XOR32ri, X86::XOR32ri,
9880 case X86::ATOMNAND6432:
9881 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9882 X86::AND32rr, X86::AND32rr,
9883 X86::AND32ri, X86::AND32ri,
9885 case X86::ATOMADD6432:
9886 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9887 X86::ADD32rr, X86::ADC32rr,
9888 X86::ADD32ri, X86::ADC32ri,
9890 case X86::ATOMSUB6432:
9891 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9892 X86::SUB32rr, X86::SBB32rr,
9893 X86::SUB32ri, X86::SBB32ri,
9895 case X86::ATOMSWAP6432:
9896 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9897 X86::MOV32rr, X86::MOV32rr,
9898 X86::MOV32ri, X86::MOV32ri,
9900 case X86::VASTART_SAVE_XMM_REGS:
9901 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
9905 //===----------------------------------------------------------------------===//
9906 // X86 Optimization Hooks
9907 //===----------------------------------------------------------------------===//
9909 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9913 const SelectionDAG &DAG,
9914 unsigned Depth) const {
9915 unsigned Opc = Op.getOpcode();
9916 assert((Opc >= ISD::BUILTIN_OP_END ||
9917 Opc == ISD::INTRINSIC_WO_CHAIN ||
9918 Opc == ISD::INTRINSIC_W_CHAIN ||
9919 Opc == ISD::INTRINSIC_VOID) &&
9920 "Should use MaskedValueIsZero if you don't know whether Op"
9921 " is a target node!");
9923 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
9935 // These nodes' second result is a boolean.
9936 if (Op.getResNo() == 0)
9940 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
9941 Mask.getBitWidth() - 1);
9946 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
9947 unsigned Depth) const {
9948 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
9949 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
9950 return Op.getValueType().getScalarType().getSizeInBits();
9956 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
9957 /// node is a GlobalAddress + offset.
9958 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
9959 const GlobalValue* &GA,
9960 int64_t &Offset) const {
9961 if (N->getOpcode() == X86ISD::Wrapper) {
9962 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
9963 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
9964 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
9968 return TargetLowering::isGAPlusOffset(N, GA, Offset);
9971 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
9972 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
9973 /// if the load addresses are consecutive, non-overlapping, and in the right
9975 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
9976 const TargetLowering &TLI) {
9977 DebugLoc dl = N->getDebugLoc();
9978 EVT VT = N->getValueType(0);
9980 if (VT.getSizeInBits() != 128)
9983 SmallVector<SDValue, 16> Elts;
9984 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
9985 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
9987 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
9990 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
9991 /// generation and convert it from being a bunch of shuffles and extracts
9992 /// to a simple store and scalar loads to extract the elements.
9993 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
9994 const TargetLowering &TLI) {
9995 SDValue InputVector = N->getOperand(0);
9997 // Only operate on vectors of 4 elements, where the alternative shuffling
9998 // gets to be more expensive.
9999 if (InputVector.getValueType() != MVT::v4i32)
10002 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10003 // single use which is a sign-extend or zero-extend, and all elements are
10005 SmallVector<SDNode *, 4> Uses;
10006 unsigned ExtractedElements = 0;
10007 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10008 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10009 if (UI.getUse().getResNo() != InputVector.getResNo())
10012 SDNode *Extract = *UI;
10013 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10016 if (Extract->getValueType(0) != MVT::i32)
10018 if (!Extract->hasOneUse())
10020 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10021 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10023 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10026 // Record which element was extracted.
10027 ExtractedElements |=
10028 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10030 Uses.push_back(Extract);
10033 // If not all the elements were used, this may not be worthwhile.
10034 if (ExtractedElements != 15)
10037 // Ok, we've now decided to do the transformation.
10038 DebugLoc dl = InputVector.getDebugLoc();
10040 // Store the value to a temporary stack slot.
10041 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10042 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10043 MachinePointerInfo(), false, false, 0);
10045 // Replace each use (extract) with a load of the appropriate element.
10046 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10047 UE = Uses.end(); UI != UE; ++UI) {
10048 SDNode *Extract = *UI;
10050 // Compute the element's address.
10051 SDValue Idx = Extract->getOperand(1);
10053 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10054 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10055 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10057 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10058 StackPtr, OffsetVal);
10060 // Load the scalar.
10061 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10062 ScalarAddr, MachinePointerInfo(),
10065 // Replace the exact with the load.
10066 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10069 // The replacement was made in place; don't return anything.
10073 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10074 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10075 const X86Subtarget *Subtarget) {
10076 DebugLoc DL = N->getDebugLoc();
10077 SDValue Cond = N->getOperand(0);
10078 // Get the LHS/RHS of the select.
10079 SDValue LHS = N->getOperand(1);
10080 SDValue RHS = N->getOperand(2);
10082 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10083 // instructions match the semantics of the common C idiom x<y?x:y but not
10084 // x<=y?x:y, because of how they handle negative zero (which can be
10085 // ignored in unsafe-math mode).
10086 if (Subtarget->hasSSE2() &&
10087 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10088 Cond.getOpcode() == ISD::SETCC) {
10089 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10091 unsigned Opcode = 0;
10092 // Check for x CC y ? x : y.
10093 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10094 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10098 // Converting this to a min would handle NaNs incorrectly, and swapping
10099 // the operands would cause it to handle comparisons between positive
10100 // and negative zero incorrectly.
10101 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10102 if (!UnsafeFPMath &&
10103 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10105 std::swap(LHS, RHS);
10107 Opcode = X86ISD::FMIN;
10110 // Converting this to a min would handle comparisons between positive
10111 // and negative zero incorrectly.
10112 if (!UnsafeFPMath &&
10113 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10115 Opcode = X86ISD::FMIN;
10118 // Converting this to a min would handle both negative zeros and NaNs
10119 // incorrectly, but we can swap the operands to fix both.
10120 std::swap(LHS, RHS);
10124 Opcode = X86ISD::FMIN;
10128 // Converting this to a max would handle comparisons between positive
10129 // and negative zero incorrectly.
10130 if (!UnsafeFPMath &&
10131 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10133 Opcode = X86ISD::FMAX;
10136 // Converting this to a max would handle NaNs incorrectly, and swapping
10137 // the operands would cause it to handle comparisons between positive
10138 // and negative zero incorrectly.
10139 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10140 if (!UnsafeFPMath &&
10141 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10143 std::swap(LHS, RHS);
10145 Opcode = X86ISD::FMAX;
10148 // Converting this to a max would handle both negative zeros and NaNs
10149 // incorrectly, but we can swap the operands to fix both.
10150 std::swap(LHS, RHS);
10154 Opcode = X86ISD::FMAX;
10157 // Check for x CC y ? y : x -- a min/max with reversed arms.
10158 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10159 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10163 // Converting this to a min would handle comparisons between positive
10164 // and negative zero incorrectly, and swapping the operands would
10165 // cause it to handle NaNs incorrectly.
10166 if (!UnsafeFPMath &&
10167 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10168 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10170 std::swap(LHS, RHS);
10172 Opcode = X86ISD::FMIN;
10175 // Converting this to a min would handle NaNs incorrectly.
10176 if (!UnsafeFPMath &&
10177 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10179 Opcode = X86ISD::FMIN;
10182 // Converting this to a min would handle both negative zeros and NaNs
10183 // incorrectly, but we can swap the operands to fix both.
10184 std::swap(LHS, RHS);
10188 Opcode = X86ISD::FMIN;
10192 // Converting this to a max would handle NaNs incorrectly.
10193 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10195 Opcode = X86ISD::FMAX;
10198 // Converting this to a max would handle comparisons between positive
10199 // and negative zero incorrectly, and swapping the operands would
10200 // cause it to handle NaNs incorrectly.
10201 if (!UnsafeFPMath &&
10202 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10203 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10205 std::swap(LHS, RHS);
10207 Opcode = X86ISD::FMAX;
10210 // Converting this to a max would handle both negative zeros and NaNs
10211 // incorrectly, but we can swap the operands to fix both.
10212 std::swap(LHS, RHS);
10216 Opcode = X86ISD::FMAX;
10222 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10225 // If this is a select between two integer constants, try to do some
10227 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10228 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10229 // Don't do this for crazy integer types.
10230 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10231 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10232 // so that TrueC (the true value) is larger than FalseC.
10233 bool NeedsCondInvert = false;
10235 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10236 // Efficiently invertible.
10237 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
10238 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
10239 isa<ConstantSDNode>(Cond.getOperand(1))))) {
10240 NeedsCondInvert = true;
10241 std::swap(TrueC, FalseC);
10244 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
10245 if (FalseC->getAPIntValue() == 0 &&
10246 TrueC->getAPIntValue().isPowerOf2()) {
10247 if (NeedsCondInvert) // Invert the condition if needed.
10248 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10249 DAG.getConstant(1, Cond.getValueType()));
10251 // Zero extend the condition if needed.
10252 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10254 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10255 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10256 DAG.getConstant(ShAmt, MVT::i8));
10259 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10260 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10261 if (NeedsCondInvert) // Invert the condition if needed.
10262 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10263 DAG.getConstant(1, Cond.getValueType()));
10265 // Zero extend the condition if needed.
10266 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10267 FalseC->getValueType(0), Cond);
10268 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10269 SDValue(FalseC, 0));
10272 // Optimize cases that will turn into an LEA instruction. This requires
10273 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10274 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10275 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10276 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10278 bool isFastMultiplier = false;
10280 switch ((unsigned char)Diff) {
10282 case 1: // result = add base, cond
10283 case 2: // result = lea base( , cond*2)
10284 case 3: // result = lea base(cond, cond*2)
10285 case 4: // result = lea base( , cond*4)
10286 case 5: // result = lea base(cond, cond*4)
10287 case 8: // result = lea base( , cond*8)
10288 case 9: // result = lea base(cond, cond*8)
10289 isFastMultiplier = true;
10294 if (isFastMultiplier) {
10295 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10296 if (NeedsCondInvert) // Invert the condition if needed.
10297 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10298 DAG.getConstant(1, Cond.getValueType()));
10300 // Zero extend the condition if needed.
10301 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10303 // Scale the condition by the difference.
10305 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10306 DAG.getConstant(Diff, Cond.getValueType()));
10308 // Add the base if non-zero.
10309 if (FalseC->getAPIntValue() != 0)
10310 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10311 SDValue(FalseC, 0));
10321 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10322 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10323 TargetLowering::DAGCombinerInfo &DCI) {
10324 DebugLoc DL = N->getDebugLoc();
10326 // If the flag operand isn't dead, don't touch this CMOV.
10327 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10330 // If this is a select between two integer constants, try to do some
10331 // optimizations. Note that the operands are ordered the opposite of SELECT
10333 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10334 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10335 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10336 // larger than FalseC (the false value).
10337 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10339 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10340 CC = X86::GetOppositeBranchCondition(CC);
10341 std::swap(TrueC, FalseC);
10344 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
10345 // This is efficient for any integer data type (including i8/i16) and
10347 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10348 SDValue Cond = N->getOperand(3);
10349 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10350 DAG.getConstant(CC, MVT::i8), Cond);
10352 // Zero extend the condition if needed.
10353 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10355 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10356 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10357 DAG.getConstant(ShAmt, MVT::i8));
10358 if (N->getNumValues() == 2) // Dead flag value?
10359 return DCI.CombineTo(N, Cond, SDValue());
10363 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
10364 // for any integer data type, including i8/i16.
10365 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10366 SDValue Cond = N->getOperand(3);
10367 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10368 DAG.getConstant(CC, MVT::i8), Cond);
10370 // Zero extend the condition if needed.
10371 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10372 FalseC->getValueType(0), Cond);
10373 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10374 SDValue(FalseC, 0));
10376 if (N->getNumValues() == 2) // Dead flag value?
10377 return DCI.CombineTo(N, Cond, SDValue());
10381 // Optimize cases that will turn into an LEA instruction. This requires
10382 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10383 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10384 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10385 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10387 bool isFastMultiplier = false;
10389 switch ((unsigned char)Diff) {
10391 case 1: // result = add base, cond
10392 case 2: // result = lea base( , cond*2)
10393 case 3: // result = lea base(cond, cond*2)
10394 case 4: // result = lea base( , cond*4)
10395 case 5: // result = lea base(cond, cond*4)
10396 case 8: // result = lea base( , cond*8)
10397 case 9: // result = lea base(cond, cond*8)
10398 isFastMultiplier = true;
10403 if (isFastMultiplier) {
10404 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10405 SDValue Cond = N->getOperand(3);
10406 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10407 DAG.getConstant(CC, MVT::i8), Cond);
10408 // Zero extend the condition if needed.
10409 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10411 // Scale the condition by the difference.
10413 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10414 DAG.getConstant(Diff, Cond.getValueType()));
10416 // Add the base if non-zero.
10417 if (FalseC->getAPIntValue() != 0)
10418 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10419 SDValue(FalseC, 0));
10420 if (N->getNumValues() == 2) // Dead flag value?
10421 return DCI.CombineTo(N, Cond, SDValue());
10431 /// PerformMulCombine - Optimize a single multiply with constant into two
10432 /// in order to implement it with two cheaper instructions, e.g.
10433 /// LEA + SHL, LEA + LEA.
10434 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10435 TargetLowering::DAGCombinerInfo &DCI) {
10436 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10439 EVT VT = N->getValueType(0);
10440 if (VT != MVT::i64)
10443 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10446 uint64_t MulAmt = C->getZExtValue();
10447 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10450 uint64_t MulAmt1 = 0;
10451 uint64_t MulAmt2 = 0;
10452 if ((MulAmt % 9) == 0) {
10454 MulAmt2 = MulAmt / 9;
10455 } else if ((MulAmt % 5) == 0) {
10457 MulAmt2 = MulAmt / 5;
10458 } else if ((MulAmt % 3) == 0) {
10460 MulAmt2 = MulAmt / 3;
10463 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10464 DebugLoc DL = N->getDebugLoc();
10466 if (isPowerOf2_64(MulAmt2) &&
10467 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10468 // If second multiplifer is pow2, issue it first. We want the multiply by
10469 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10471 std::swap(MulAmt1, MulAmt2);
10474 if (isPowerOf2_64(MulAmt1))
10475 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10476 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10478 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10479 DAG.getConstant(MulAmt1, VT));
10481 if (isPowerOf2_64(MulAmt2))
10482 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10483 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10485 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10486 DAG.getConstant(MulAmt2, VT));
10488 // Do not add new nodes to DAG combiner worklist.
10489 DCI.CombineTo(N, NewMul, false);
10494 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10495 SDValue N0 = N->getOperand(0);
10496 SDValue N1 = N->getOperand(1);
10497 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10498 EVT VT = N0.getValueType();
10500 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10501 // since the result of setcc_c is all zero's or all ones.
10502 if (N1C && N0.getOpcode() == ISD::AND &&
10503 N0.getOperand(1).getOpcode() == ISD::Constant) {
10504 SDValue N00 = N0.getOperand(0);
10505 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10506 ((N00.getOpcode() == ISD::ANY_EXTEND ||
10507 N00.getOpcode() == ISD::ZERO_EXTEND) &&
10508 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10509 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10510 APInt ShAmt = N1C->getAPIntValue();
10511 Mask = Mask.shl(ShAmt);
10513 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10514 N00, DAG.getConstant(Mask, VT));
10521 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10523 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10524 const X86Subtarget *Subtarget) {
10525 EVT VT = N->getValueType(0);
10526 if (!VT.isVector() && VT.isInteger() &&
10527 N->getOpcode() == ISD::SHL)
10528 return PerformSHLCombine(N, DAG);
10530 // On X86 with SSE2 support, we can transform this to a vector shift if
10531 // all elements are shifted by the same amount. We can't do this in legalize
10532 // because the a constant vector is typically transformed to a constant pool
10533 // so we have no knowledge of the shift amount.
10534 if (!Subtarget->hasSSE2())
10537 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10540 SDValue ShAmtOp = N->getOperand(1);
10541 EVT EltVT = VT.getVectorElementType();
10542 DebugLoc DL = N->getDebugLoc();
10543 SDValue BaseShAmt = SDValue();
10544 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10545 unsigned NumElts = VT.getVectorNumElements();
10547 for (; i != NumElts; ++i) {
10548 SDValue Arg = ShAmtOp.getOperand(i);
10549 if (Arg.getOpcode() == ISD::UNDEF) continue;
10553 for (; i != NumElts; ++i) {
10554 SDValue Arg = ShAmtOp.getOperand(i);
10555 if (Arg.getOpcode() == ISD::UNDEF) continue;
10556 if (Arg != BaseShAmt) {
10560 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10561 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10562 SDValue InVec = ShAmtOp.getOperand(0);
10563 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10564 unsigned NumElts = InVec.getValueType().getVectorNumElements();
10566 for (; i != NumElts; ++i) {
10567 SDValue Arg = InVec.getOperand(i);
10568 if (Arg.getOpcode() == ISD::UNDEF) continue;
10572 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10573 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10574 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10575 if (C->getZExtValue() == SplatIdx)
10576 BaseShAmt = InVec.getOperand(1);
10579 if (BaseShAmt.getNode() == 0)
10580 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
10581 DAG.getIntPtrConstant(0));
10585 // The shift amount is an i32.
10586 if (EltVT.bitsGT(MVT::i32))
10587 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
10588 else if (EltVT.bitsLT(MVT::i32))
10589 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
10591 // The shift amount is identical so we can do a vector shift.
10592 SDValue ValOp = N->getOperand(0);
10593 switch (N->getOpcode()) {
10595 llvm_unreachable("Unknown shift opcode!");
10598 if (VT == MVT::v2i64)
10599 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10600 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10602 if (VT == MVT::v4i32)
10603 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10604 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10606 if (VT == MVT::v8i16)
10607 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10608 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10612 if (VT == MVT::v4i32)
10613 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10614 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10616 if (VT == MVT::v8i16)
10617 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10618 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10622 if (VT == MVT::v2i64)
10623 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10624 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10626 if (VT == MVT::v4i32)
10627 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10628 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10630 if (VT == MVT::v8i16)
10631 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10632 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10639 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
10640 TargetLowering::DAGCombinerInfo &DCI,
10641 const X86Subtarget *Subtarget) {
10642 if (DCI.isBeforeLegalizeOps())
10645 EVT VT = N->getValueType(0);
10646 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
10649 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
10650 SDValue N0 = N->getOperand(0);
10651 SDValue N1 = N->getOperand(1);
10652 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
10654 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
10656 if (!N0.hasOneUse() || !N1.hasOneUse())
10659 SDValue ShAmt0 = N0.getOperand(1);
10660 if (ShAmt0.getValueType() != MVT::i8)
10662 SDValue ShAmt1 = N1.getOperand(1);
10663 if (ShAmt1.getValueType() != MVT::i8)
10665 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
10666 ShAmt0 = ShAmt0.getOperand(0);
10667 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
10668 ShAmt1 = ShAmt1.getOperand(0);
10670 DebugLoc DL = N->getDebugLoc();
10671 unsigned Opc = X86ISD::SHLD;
10672 SDValue Op0 = N0.getOperand(0);
10673 SDValue Op1 = N1.getOperand(0);
10674 if (ShAmt0.getOpcode() == ISD::SUB) {
10675 Opc = X86ISD::SHRD;
10676 std::swap(Op0, Op1);
10677 std::swap(ShAmt0, ShAmt1);
10680 unsigned Bits = VT.getSizeInBits();
10681 if (ShAmt1.getOpcode() == ISD::SUB) {
10682 SDValue Sum = ShAmt1.getOperand(0);
10683 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
10684 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
10685 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
10686 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
10687 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
10688 return DAG.getNode(Opc, DL, VT,
10690 DAG.getNode(ISD::TRUNCATE, DL,
10693 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
10694 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
10696 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
10697 return DAG.getNode(Opc, DL, VT,
10698 N0.getOperand(0), N1.getOperand(0),
10699 DAG.getNode(ISD::TRUNCATE, DL,
10706 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
10707 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
10708 const X86Subtarget *Subtarget) {
10709 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
10710 // the FP state in cases where an emms may be missing.
10711 // A preferable solution to the general problem is to figure out the right
10712 // places to insert EMMS. This qualifies as a quick hack.
10714 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
10715 StoreSDNode *St = cast<StoreSDNode>(N);
10716 EVT VT = St->getValue().getValueType();
10717 if (VT.getSizeInBits() != 64)
10720 const Function *F = DAG.getMachineFunction().getFunction();
10721 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
10722 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
10723 && Subtarget->hasSSE2();
10724 if ((VT.isVector() ||
10725 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
10726 isa<LoadSDNode>(St->getValue()) &&
10727 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
10728 St->getChain().hasOneUse() && !St->isVolatile()) {
10729 SDNode* LdVal = St->getValue().getNode();
10730 LoadSDNode *Ld = 0;
10731 int TokenFactorIndex = -1;
10732 SmallVector<SDValue, 8> Ops;
10733 SDNode* ChainVal = St->getChain().getNode();
10734 // Must be a store of a load. We currently handle two cases: the load
10735 // is a direct child, and it's under an intervening TokenFactor. It is
10736 // possible to dig deeper under nested TokenFactors.
10737 if (ChainVal == LdVal)
10738 Ld = cast<LoadSDNode>(St->getChain());
10739 else if (St->getValue().hasOneUse() &&
10740 ChainVal->getOpcode() == ISD::TokenFactor) {
10741 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
10742 if (ChainVal->getOperand(i).getNode() == LdVal) {
10743 TokenFactorIndex = i;
10744 Ld = cast<LoadSDNode>(St->getValue());
10746 Ops.push_back(ChainVal->getOperand(i));
10750 if (!Ld || !ISD::isNormalLoad(Ld))
10753 // If this is not the MMX case, i.e. we are just turning i64 load/store
10754 // into f64 load/store, avoid the transformation if there are multiple
10755 // uses of the loaded value.
10756 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
10759 DebugLoc LdDL = Ld->getDebugLoc();
10760 DebugLoc StDL = N->getDebugLoc();
10761 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
10762 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
10764 if (Subtarget->is64Bit() || F64IsLegal) {
10765 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
10766 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
10767 Ld->getPointerInfo(), Ld->isVolatile(),
10768 Ld->isNonTemporal(), Ld->getAlignment());
10769 SDValue NewChain = NewLd.getValue(1);
10770 if (TokenFactorIndex != -1) {
10771 Ops.push_back(NewChain);
10772 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10775 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
10776 St->getPointerInfo(),
10777 St->isVolatile(), St->isNonTemporal(),
10778 St->getAlignment());
10781 // Otherwise, lower to two pairs of 32-bit loads / stores.
10782 SDValue LoAddr = Ld->getBasePtr();
10783 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
10784 DAG.getConstant(4, MVT::i32));
10786 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
10787 Ld->getPointerInfo(),
10788 Ld->isVolatile(), Ld->isNonTemporal(),
10789 Ld->getAlignment());
10790 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
10791 Ld->getPointerInfo().getWithOffset(4),
10792 Ld->isVolatile(), Ld->isNonTemporal(),
10793 MinAlign(Ld->getAlignment(), 4));
10795 SDValue NewChain = LoLd.getValue(1);
10796 if (TokenFactorIndex != -1) {
10797 Ops.push_back(LoLd);
10798 Ops.push_back(HiLd);
10799 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10803 LoAddr = St->getBasePtr();
10804 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
10805 DAG.getConstant(4, MVT::i32));
10807 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
10808 St->getPointerInfo(),
10809 St->isVolatile(), St->isNonTemporal(),
10810 St->getAlignment());
10811 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
10812 St->getPointerInfo().getWithOffset(4),
10814 St->isNonTemporal(),
10815 MinAlign(St->getAlignment(), 4));
10816 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
10821 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
10822 /// X86ISD::FXOR nodes.
10823 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
10824 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
10825 // F[X]OR(0.0, x) -> x
10826 // F[X]OR(x, 0.0) -> x
10827 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10828 if (C->getValueAPF().isPosZero())
10829 return N->getOperand(1);
10830 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10831 if (C->getValueAPF().isPosZero())
10832 return N->getOperand(0);
10836 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
10837 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
10838 // FAND(0.0, x) -> 0.0
10839 // FAND(x, 0.0) -> 0.0
10840 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10841 if (C->getValueAPF().isPosZero())
10842 return N->getOperand(0);
10843 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10844 if (C->getValueAPF().isPosZero())
10845 return N->getOperand(1);
10849 static SDValue PerformBTCombine(SDNode *N,
10851 TargetLowering::DAGCombinerInfo &DCI) {
10852 // BT ignores high bits in the bit index operand.
10853 SDValue Op1 = N->getOperand(1);
10854 if (Op1.hasOneUse()) {
10855 unsigned BitWidth = Op1.getValueSizeInBits();
10856 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
10857 APInt KnownZero, KnownOne;
10858 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10859 !DCI.isBeforeLegalizeOps());
10860 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10861 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
10862 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
10863 DCI.CommitTargetLoweringOpt(TLO);
10868 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
10869 SDValue Op = N->getOperand(0);
10870 if (Op.getOpcode() == ISD::BIT_CONVERT)
10871 Op = Op.getOperand(0);
10872 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
10873 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
10874 VT.getVectorElementType().getSizeInBits() ==
10875 OpVT.getVectorElementType().getSizeInBits()) {
10876 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
10881 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
10882 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
10883 // (and (i32 x86isd::setcc_carry), 1)
10884 // This eliminates the zext. This transformation is necessary because
10885 // ISD::SETCC is always legalized to i8.
10886 DebugLoc dl = N->getDebugLoc();
10887 SDValue N0 = N->getOperand(0);
10888 EVT VT = N->getValueType(0);
10889 if (N0.getOpcode() == ISD::AND &&
10891 N0.getOperand(0).hasOneUse()) {
10892 SDValue N00 = N0.getOperand(0);
10893 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
10895 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10896 if (!C || C->getZExtValue() != 1)
10898 return DAG.getNode(ISD::AND, dl, VT,
10899 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
10900 N00.getOperand(0), N00.getOperand(1)),
10901 DAG.getConstant(1, VT));
10907 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
10908 DAGCombinerInfo &DCI) const {
10909 SelectionDAG &DAG = DCI.DAG;
10910 switch (N->getOpcode()) {
10912 case ISD::EXTRACT_VECTOR_ELT:
10913 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
10914 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
10915 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
10916 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
10919 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
10920 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
10921 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
10923 case X86ISD::FOR: return PerformFORCombine(N, DAG);
10924 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
10925 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
10926 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
10927 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
10928 case X86ISD::SHUFPS: // Handle all target specific shuffles
10929 case X86ISD::SHUFPD:
10930 case X86ISD::PALIGN:
10931 case X86ISD::PUNPCKHBW:
10932 case X86ISD::PUNPCKHWD:
10933 case X86ISD::PUNPCKHDQ:
10934 case X86ISD::PUNPCKHQDQ:
10935 case X86ISD::UNPCKHPS:
10936 case X86ISD::UNPCKHPD:
10937 case X86ISD::PUNPCKLBW:
10938 case X86ISD::PUNPCKLWD:
10939 case X86ISD::PUNPCKLDQ:
10940 case X86ISD::PUNPCKLQDQ:
10941 case X86ISD::UNPCKLPS:
10942 case X86ISD::UNPCKLPD:
10943 case X86ISD::MOVHLPS:
10944 case X86ISD::MOVLHPS:
10945 case X86ISD::PSHUFD:
10946 case X86ISD::PSHUFHW:
10947 case X86ISD::PSHUFLW:
10948 case X86ISD::MOVSS:
10949 case X86ISD::MOVSD:
10950 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
10956 /// isTypeDesirableForOp - Return true if the target has native support for
10957 /// the specified value type and it is 'desirable' to use the type for the
10958 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
10959 /// instruction encodings are longer and some i16 instructions are slow.
10960 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
10961 if (!isTypeLegal(VT))
10963 if (VT != MVT::i16)
10970 case ISD::SIGN_EXTEND:
10971 case ISD::ZERO_EXTEND:
10972 case ISD::ANY_EXTEND:
10985 /// IsDesirableToPromoteOp - This method query the target whether it is
10986 /// beneficial for dag combiner to promote the specified node. If true, it
10987 /// should return the desired promotion type by reference.
10988 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
10989 EVT VT = Op.getValueType();
10990 if (VT != MVT::i16)
10993 bool Promote = false;
10994 bool Commute = false;
10995 switch (Op.getOpcode()) {
10998 LoadSDNode *LD = cast<LoadSDNode>(Op);
10999 // If the non-extending load has a single use and it's not live out, then it
11000 // might be folded.
11001 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11002 Op.hasOneUse()*/) {
11003 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11004 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11005 // The only case where we'd want to promote LOAD (rather then it being
11006 // promoted as an operand is when it's only use is liveout.
11007 if (UI->getOpcode() != ISD::CopyToReg)
11014 case ISD::SIGN_EXTEND:
11015 case ISD::ZERO_EXTEND:
11016 case ISD::ANY_EXTEND:
11021 SDValue N0 = Op.getOperand(0);
11022 // Look out for (store (shl (load), x)).
11023 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11036 SDValue N0 = Op.getOperand(0);
11037 SDValue N1 = Op.getOperand(1);
11038 if (!Commute && MayFoldLoad(N1))
11040 // Avoid disabling potential load folding opportunities.
11041 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11043 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11053 //===----------------------------------------------------------------------===//
11054 // X86 Inline Assembly Support
11055 //===----------------------------------------------------------------------===//
11057 static bool LowerToBSwap(CallInst *CI) {
11058 // FIXME: this should verify that we are targetting a 486 or better. If not,
11059 // we will turn this bswap into something that will be lowered to logical ops
11060 // instead of emitting the bswap asm. For now, we don't support 486 or lower
11061 // so don't worry about this.
11063 // Verify this is a simple bswap.
11064 if (CI->getNumArgOperands() != 1 ||
11065 CI->getType() != CI->getArgOperand(0)->getType() ||
11066 !CI->getType()->isIntegerTy())
11069 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11070 if (!Ty || Ty->getBitWidth() % 16 != 0)
11073 // Okay, we can do this xform, do so now.
11074 const Type *Tys[] = { Ty };
11075 Module *M = CI->getParent()->getParent()->getParent();
11076 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11078 Value *Op = CI->getArgOperand(0);
11079 Op = CallInst::Create(Int, Op, CI->getName(), CI);
11081 CI->replaceAllUsesWith(Op);
11082 CI->eraseFromParent();
11086 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11087 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11088 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
11090 std::string AsmStr = IA->getAsmString();
11092 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11093 SmallVector<StringRef, 4> AsmPieces;
11094 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
11096 switch (AsmPieces.size()) {
11097 default: return false;
11099 AsmStr = AsmPieces[0];
11101 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
11104 if (AsmPieces.size() == 2 &&
11105 (AsmPieces[0] == "bswap" ||
11106 AsmPieces[0] == "bswapq" ||
11107 AsmPieces[0] == "bswapl") &&
11108 (AsmPieces[1] == "$0" ||
11109 AsmPieces[1] == "${0:q}")) {
11110 // No need to check constraints, nothing other than the equivalent of
11111 // "=r,0" would be valid here.
11112 return LowerToBSwap(CI);
11114 // rorw $$8, ${0:w} --> llvm.bswap.i16
11115 if (CI->getType()->isIntegerTy(16) &&
11116 AsmPieces.size() == 3 &&
11117 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11118 AsmPieces[1] == "$$8," &&
11119 AsmPieces[2] == "${0:w}" &&
11120 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11122 const std::string &Constraints = IA->getConstraintString();
11123 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11124 std::sort(AsmPieces.begin(), AsmPieces.end());
11125 if (AsmPieces.size() == 4 &&
11126 AsmPieces[0] == "~{cc}" &&
11127 AsmPieces[1] == "~{dirflag}" &&
11128 AsmPieces[2] == "~{flags}" &&
11129 AsmPieces[3] == "~{fpsr}") {
11130 return LowerToBSwap(CI);
11135 if (CI->getType()->isIntegerTy(64) &&
11136 Constraints.size() >= 2 &&
11137 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11138 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11139 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
11140 SmallVector<StringRef, 4> Words;
11141 SplitString(AsmPieces[0], Words, " \t");
11142 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11144 SplitString(AsmPieces[1], Words, " \t");
11145 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11147 SplitString(AsmPieces[2], Words, " \t,");
11148 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11149 Words[2] == "%edx") {
11150 return LowerToBSwap(CI);
11162 /// getConstraintType - Given a constraint letter, return the type of
11163 /// constraint it is for this target.
11164 X86TargetLowering::ConstraintType
11165 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11166 if (Constraint.size() == 1) {
11167 switch (Constraint[0]) {
11179 return C_RegisterClass;
11187 return TargetLowering::getConstraintType(Constraint);
11190 /// Examine constraint type and operand type and determine a weight value,
11191 /// where: -1 = invalid match, and 0 = so-so match to 3 = good match.
11192 /// This object must already have been set up with the operand type
11193 /// and the current alternative constraint selected.
11194 int X86TargetLowering::getSingleConstraintMatchWeight(
11195 AsmOperandInfo &info, const char *constraint) const {
11197 Value *CallOperandVal = info.CallOperandVal;
11198 // If we don't have a value, we can't do a match,
11199 // but allow it at the lowest weight.
11200 if (CallOperandVal == NULL)
11202 // Look at the constraint type.
11203 switch (*constraint) {
11205 return TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11208 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11209 if (C->getZExtValue() <= 31)
11218 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11219 /// with another that has more specific requirements based on the type of the
11220 /// corresponding operand.
11221 const char *X86TargetLowering::
11222 LowerXConstraint(EVT ConstraintVT) const {
11223 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11224 // 'f' like normal targets.
11225 if (ConstraintVT.isFloatingPoint()) {
11226 if (Subtarget->hasSSE2())
11228 if (Subtarget->hasSSE1())
11232 return TargetLowering::LowerXConstraint(ConstraintVT);
11235 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11236 /// vector. If it is invalid, don't add anything to Ops.
11237 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11239 std::vector<SDValue>&Ops,
11240 SelectionDAG &DAG) const {
11241 SDValue Result(0, 0);
11243 switch (Constraint) {
11246 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11247 if (C->getZExtValue() <= 31) {
11248 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11254 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11255 if (C->getZExtValue() <= 63) {
11256 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11262 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11263 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11264 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11270 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11271 if (C->getZExtValue() <= 255) {
11272 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11278 // 32-bit signed value
11279 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11280 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11281 C->getSExtValue())) {
11282 // Widen to 64 bits here to get it sign extended.
11283 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11286 // FIXME gcc accepts some relocatable values here too, but only in certain
11287 // memory models; it's complicated.
11292 // 32-bit unsigned value
11293 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11294 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11295 C->getZExtValue())) {
11296 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11300 // FIXME gcc accepts some relocatable values here too, but only in certain
11301 // memory models; it's complicated.
11305 // Literal immediates are always ok.
11306 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11307 // Widen to 64 bits here to get it sign extended.
11308 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11312 // In any sort of PIC mode addresses need to be computed at runtime by
11313 // adding in a register or some sort of table lookup. These can't
11314 // be used as immediates.
11315 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11318 // If we are in non-pic codegen mode, we allow the address of a global (with
11319 // an optional displacement) to be used with 'i'.
11320 GlobalAddressSDNode *GA = 0;
11321 int64_t Offset = 0;
11323 // Match either (GA), (GA+C), (GA+C1+C2), etc.
11325 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11326 Offset += GA->getOffset();
11328 } else if (Op.getOpcode() == ISD::ADD) {
11329 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11330 Offset += C->getZExtValue();
11331 Op = Op.getOperand(0);
11334 } else if (Op.getOpcode() == ISD::SUB) {
11335 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11336 Offset += -C->getZExtValue();
11337 Op = Op.getOperand(0);
11342 // Otherwise, this isn't something we can handle, reject it.
11346 const GlobalValue *GV = GA->getGlobal();
11347 // If we require an extra load to get this address, as in PIC mode, we
11348 // can't accept it.
11349 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
11350 getTargetMachine())))
11353 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
11354 GA->getValueType(0), Offset);
11359 if (Result.getNode()) {
11360 Ops.push_back(Result);
11363 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11366 std::vector<unsigned> X86TargetLowering::
11367 getRegClassForInlineAsmConstraint(const std::string &Constraint,
11369 if (Constraint.size() == 1) {
11370 // FIXME: not handling fp-stack yet!
11371 switch (Constraint[0]) { // GCC X86 Constraint Letters
11372 default: break; // Unknown constraint letter
11373 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
11374 if (Subtarget->is64Bit()) {
11375 if (VT == MVT::i32)
11376 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
11377 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
11378 X86::R10D,X86::R11D,X86::R12D,
11379 X86::R13D,X86::R14D,X86::R15D,
11380 X86::EBP, X86::ESP, 0);
11381 else if (VT == MVT::i16)
11382 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
11383 X86::SI, X86::DI, X86::R8W,X86::R9W,
11384 X86::R10W,X86::R11W,X86::R12W,
11385 X86::R13W,X86::R14W,X86::R15W,
11386 X86::BP, X86::SP, 0);
11387 else if (VT == MVT::i8)
11388 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
11389 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
11390 X86::R10B,X86::R11B,X86::R12B,
11391 X86::R13B,X86::R14B,X86::R15B,
11392 X86::BPL, X86::SPL, 0);
11394 else if (VT == MVT::i64)
11395 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
11396 X86::RSI, X86::RDI, X86::R8, X86::R9,
11397 X86::R10, X86::R11, X86::R12,
11398 X86::R13, X86::R14, X86::R15,
11399 X86::RBP, X86::RSP, 0);
11403 // 32-bit fallthrough
11404 case 'Q': // Q_REGS
11405 if (VT == MVT::i32)
11406 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
11407 else if (VT == MVT::i16)
11408 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
11409 else if (VT == MVT::i8)
11410 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
11411 else if (VT == MVT::i64)
11412 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
11417 return std::vector<unsigned>();
11420 std::pair<unsigned, const TargetRegisterClass*>
11421 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
11423 // First, see if this is a constraint that directly corresponds to an LLVM
11425 if (Constraint.size() == 1) {
11426 // GCC Constraint Letters
11427 switch (Constraint[0]) {
11429 case 'r': // GENERAL_REGS
11430 case 'l': // INDEX_REGS
11432 return std::make_pair(0U, X86::GR8RegisterClass);
11433 if (VT == MVT::i16)
11434 return std::make_pair(0U, X86::GR16RegisterClass);
11435 if (VT == MVT::i32 || !Subtarget->is64Bit())
11436 return std::make_pair(0U, X86::GR32RegisterClass);
11437 return std::make_pair(0U, X86::GR64RegisterClass);
11438 case 'R': // LEGACY_REGS
11440 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
11441 if (VT == MVT::i16)
11442 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
11443 if (VT == MVT::i32 || !Subtarget->is64Bit())
11444 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
11445 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
11446 case 'f': // FP Stack registers.
11447 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
11448 // value to the correct fpstack register class.
11449 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
11450 return std::make_pair(0U, X86::RFP32RegisterClass);
11451 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
11452 return std::make_pair(0U, X86::RFP64RegisterClass);
11453 return std::make_pair(0U, X86::RFP80RegisterClass);
11454 case 'y': // MMX_REGS if MMX allowed.
11455 if (!Subtarget->hasMMX()) break;
11456 return std::make_pair(0U, X86::VR64RegisterClass);
11457 case 'Y': // SSE_REGS if SSE2 allowed
11458 if (!Subtarget->hasSSE2()) break;
11460 case 'x': // SSE_REGS if SSE1 allowed
11461 if (!Subtarget->hasSSE1()) break;
11463 switch (VT.getSimpleVT().SimpleTy) {
11465 // Scalar SSE types.
11468 return std::make_pair(0U, X86::FR32RegisterClass);
11471 return std::make_pair(0U, X86::FR64RegisterClass);
11479 return std::make_pair(0U, X86::VR128RegisterClass);
11485 // Use the default implementation in TargetLowering to convert the register
11486 // constraint into a member of a register class.
11487 std::pair<unsigned, const TargetRegisterClass*> Res;
11488 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
11490 // Not found as a standard register?
11491 if (Res.second == 0) {
11492 // Map st(0) -> st(7) -> ST0
11493 if (Constraint.size() == 7 && Constraint[0] == '{' &&
11494 tolower(Constraint[1]) == 's' &&
11495 tolower(Constraint[2]) == 't' &&
11496 Constraint[3] == '(' &&
11497 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
11498 Constraint[5] == ')' &&
11499 Constraint[6] == '}') {
11501 Res.first = X86::ST0+Constraint[4]-'0';
11502 Res.second = X86::RFP80RegisterClass;
11506 // GCC allows "st(0)" to be called just plain "st".
11507 if (StringRef("{st}").equals_lower(Constraint)) {
11508 Res.first = X86::ST0;
11509 Res.second = X86::RFP80RegisterClass;
11514 if (StringRef("{flags}").equals_lower(Constraint)) {
11515 Res.first = X86::EFLAGS;
11516 Res.second = X86::CCRRegisterClass;
11520 // 'A' means EAX + EDX.
11521 if (Constraint == "A") {
11522 Res.first = X86::EAX;
11523 Res.second = X86::GR32_ADRegisterClass;
11529 // Otherwise, check to see if this is a register class of the wrong value
11530 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
11531 // turn into {ax},{dx}.
11532 if (Res.second->hasType(VT))
11533 return Res; // Correct type already, nothing to do.
11535 // All of the single-register GCC register classes map their values onto
11536 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
11537 // really want an 8-bit or 32-bit register, map to the appropriate register
11538 // class and return the appropriate register.
11539 if (Res.second == X86::GR16RegisterClass) {
11540 if (VT == MVT::i8) {
11541 unsigned DestReg = 0;
11542 switch (Res.first) {
11544 case X86::AX: DestReg = X86::AL; break;
11545 case X86::DX: DestReg = X86::DL; break;
11546 case X86::CX: DestReg = X86::CL; break;
11547 case X86::BX: DestReg = X86::BL; break;
11550 Res.first = DestReg;
11551 Res.second = X86::GR8RegisterClass;
11553 } else if (VT == MVT::i32) {
11554 unsigned DestReg = 0;
11555 switch (Res.first) {
11557 case X86::AX: DestReg = X86::EAX; break;
11558 case X86::DX: DestReg = X86::EDX; break;
11559 case X86::CX: DestReg = X86::ECX; break;
11560 case X86::BX: DestReg = X86::EBX; break;
11561 case X86::SI: DestReg = X86::ESI; break;
11562 case X86::DI: DestReg = X86::EDI; break;
11563 case X86::BP: DestReg = X86::EBP; break;
11564 case X86::SP: DestReg = X86::ESP; break;
11567 Res.first = DestReg;
11568 Res.second = X86::GR32RegisterClass;
11570 } else if (VT == MVT::i64) {
11571 unsigned DestReg = 0;
11572 switch (Res.first) {
11574 case X86::AX: DestReg = X86::RAX; break;
11575 case X86::DX: DestReg = X86::RDX; break;
11576 case X86::CX: DestReg = X86::RCX; break;
11577 case X86::BX: DestReg = X86::RBX; break;
11578 case X86::SI: DestReg = X86::RSI; break;
11579 case X86::DI: DestReg = X86::RDI; break;
11580 case X86::BP: DestReg = X86::RBP; break;
11581 case X86::SP: DestReg = X86::RSP; break;
11584 Res.first = DestReg;
11585 Res.second = X86::GR64RegisterClass;
11588 } else if (Res.second == X86::FR32RegisterClass ||
11589 Res.second == X86::FR64RegisterClass ||
11590 Res.second == X86::VR128RegisterClass) {
11591 // Handle references to XMM physical registers that got mapped into the
11592 // wrong class. This can happen with constraints like {xmm0} where the
11593 // target independent register mapper will just pick the first match it can
11594 // find, ignoring the required type.
11595 if (VT == MVT::f32)
11596 Res.second = X86::FR32RegisterClass;
11597 else if (VT == MVT::f64)
11598 Res.second = X86::FR64RegisterClass;
11599 else if (X86::VR128RegisterClass->hasType(VT))
11600 Res.second = X86::VR128RegisterClass;